body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm developing a web application that leverages multiple programming languages. The data flow resembles:</p>
<ul>
<li>Browser » <strong>PHP</strong> » <strong>PL/SQL</strong> » XML » <strong>XSLT</strong> » XHTML + <strong>JavaScript</strong> » Browser</li>
</ul>
<p>Using different languages makes it tempting to hard-code various constants within the different languages, which encourages inconsistencies. Without a single source, it is highly probable that "Your Name" will sometimes be "Your name" or "your name" or even "Username", depending on what language requires the value.</p>
<p>To avoid duplicating these values, a "configuration" table exists:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>| code | label | languages | data_type |
+-------------------+---------------------+------------+-----------+
| DEFAULT_USER_NAME | Your Name | xsl,js,php | string |
| BASE_IMAGE | ${BASE_APP}images/ | xsl,js | string |
| BASE_ICON | ${BASE_IMAGE}icons/ | xsl,js | string |
| BASE_APP | /app/ | xsl,js,php | string |
</code></pre>
</blockquote>
<p>The configuration table is then converted to XML, with the references expanded as expected:</p>
<pre class="lang-none prettyprint-override"><code>BASE_ICON = /app/images/icons/
</code></pre>
<p>Once in XML, files for constants are generated for the appropriate syntax:</p>
<ul>
<li>constants.php</li>
<li>constants.xsl</li>
<li>constants.js</li>
</ul>
<p>Since the constants are now defined in a single table, there is no more duplication.</p>
<h1>Problem</h1>
<p>I am concerned that the problem of multi-language constants has a technically better solution.</p>
<p>When a project uses multiple programming languages that tightly communicate, how would you prevent constant values from being repeated throughout different language-specific source files?</p>
<p>In other words, is there a better design for eliminating duplicate values across different programming languages?</p>
<h2>Generate XML</h2>
<p>The code to generate the XML resembles...</p>
<pre class="lang-none prettyprint-override"><code>CREATE OR REPLACE FUNCTION generate_configuration_xml()
RETURNS text AS
$BODY$
DECLARE
v_result TEXT DEFAULT '<configuration/>';
BEGIN
SELECT
xmlroot (
xmlelement( name "configuration",
xmlagg(
xmlelement( name "constant",
xmlattributes(
c.code AS "name",
c.languages AS "languages"
),
xmlelement( name "value",
xmlattributes(
c.data_type AS "type"
),
recipe.get_configuration_value( c.code, 0 )
)
)
)
),
VERSION '1.0',
STANDALONE YES
)
INTO
v_result
FROM
configuration c;
RETURN v_result;
END;
</code></pre>
<h2>Get Configuration Value</h2>
<p>The code to retrieve a constant (as called above) resembles:</p>
<pre class="lang-none prettyprint-override"><code>LOOP
SELECT substring( v_result from '\$\{.+?\}' ) INTO v_code_replace;
EXIT WHEN v_code_replace IS NULL;
p_code := substr( v_code_replace, 3, length( v_code_replace ) - 3 );
v_code_value := get_configuration_value( p_code, p_depth + 1 );
v_result := replace( v_result, v_code_replace, v_code_value );
END LOOP;
</code></pre>
<h2>Generated XML</h2>
<p>This produces an XML file similar to the following:</p>
<pre class="lang-none prettyprint-override"><code><?xml version="1.0" standalone="yes"?>
<configuration>
<constant name="BASE_IMAGE" languages="xsl.js">
<value type="string">/app/images/</value>
</constant>
<constant name="BASE_ICON" languages="xsl.js">
<value type="string">/app/images/icons/</value>
</constant>
<constant name="DEFAULT_USER_NAME" languages="xsl.js,php">
<value type="string">Your Name</value>
</constant>
</configuration>
</code></pre>
<h2>Transformation</h2>
<p>Using the above language-neutral XML document, XSL can generate constants in all programming languages used by the project. The template to transform the constants into various language-specific declarations resembles:</p>
<pre class="lang-none prettyprint-override"><code><xsl:template match="//configuration">
<xsl:choose>
<xsl:when test="$language = 'xsl'">
<xsl:call-template name="xsl-header" />
<xsl:text disable-output-escaping="yes"><![CDATA[<!-- ]]></xsl:text> <xsl:call-template name="comment" /> <xsl:text disable-output-escaping="yes"><![CDATA[ -->]]></xsl:text>
<xsl:text>&#xA;</xsl:text>
<xsl:apply-templates select="constant[contains(@languages,'xsl')]" mode="xsl" />
<xsl:call-template name="xsl-footer" />
</xsl:when>
<xsl:when test="$language = 'php'">
<xsl:call-template name="php-header" />
<xsl:text>// </xsl:text><xsl:call-template name="comment" />
<xsl:text>&#xA;</xsl:text>
<xsl:apply-templates select="constant[contains(@languages,'php')]" mode="php" />
<xsl:call-template name="php-footer" />
</xsl:when>
<xsl:when test="$language = 'javascript'">
<xsl:text>// </xsl:text><xsl:call-template name="comment" />
<xsl:text>&#xA;</xsl:text>
<xsl:apply-templates select="constant[contains(@languages,'javascript')]" mode="javascript" />
</xsl:when>
</xsl:choose>
</xsl:template>
</code></pre>
<h3>XSL</h3>
<p>The XML can be transformed into XSL (e.g., <strong>constants.xsl</strong>):</p>
<pre class="lang-none prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:variable name="DEFAULT_USER_NAME">Your Name</xsl:variable>
</xsl:stylesheet>
</code></pre>
<h3>JavaScript</h3>
<p>The XML can be transformed into JavaScript (e.g., <strong>constants.js</strong>):</p>
<pre class="lang-none prettyprint-override"><code>var DEFAULT_USER_NAME = "Your Name";
</code></pre>
<h3>PHP</h3>
<p>And the XML can be transformed into PHP (e.g., <strong>constants.php</strong>):</p>
<pre class="lang-none prettyprint-override"><code><?php
$DEFAULT_USER_NAME = 'Your Name';
?>
</code></pre>
<p>These files can then be included by their respective "main" entry points. Any time a new value is required (i.e., change "Your Name" to "Click 'Your Name' To Begin"), the constants can be auto-generated from the configuration table, enforcing consistency.</p>
<h1>Execution</h1>
<p>The constants are then generated as follows:</p>
<pre class="lang-none prettyprint-override"><code>#!/bin/bash
# Fetch the most recent values for the constants.
psql schema -t -A -q -c 'select generate_configuration_xml();' -o constants.xml
# Transform the constants into a programming language variable.
xsltproc --stringparam language javascript generate.xsl constants.xml > constants.js
xsltproc --stringparam language xsl generate.xsl constants.xml > constants.xsl
xsltproc --stringparam language php generate.xsl constants.xml > constants.php
rm constants.xml
</code></pre>
<p>This produces a number of different files. Publishing the same constants in Java would require little more than the following:</p>
<pre class="lang-none prettyprint-override"><code>xsltproc --stringparam language java generate.xsl constants.xml > Constants.java
</code></pre>
<p>Is there a better way?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-26T21:14:03.773",
"Id": "31896",
"Score": "0",
"body": "What's wrong with putting everything in this table? Each language doesn't have to use all of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-26T21:54:47.340",
"Id": "31899",
"Score": "0",
"body": "There's nothing wrong with putting everything in the table. I'm wondering what other approaches are possible -- perhaps using a table to generate constants for different programming languages is not ideal?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-26T21:57:48.057",
"Id": "31900",
"Score": "0",
"body": "This is a very interesting dilemma. But you should know that this is code review and code to review is required by the FAQ, even if that code is just a sample or invented on the spot (as long as it works). Besides, I'm having a difficult time trying to figure out exactly what you are talking about. If you could provide an example in each case that would help immensely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-10T19:51:56.340",
"Id": "114066",
"Score": "0",
"body": "(assume Oracle because of PHP/SQL) What is the value of including xml and xlst in the mix, why not just use PHP and the Oracle Database on backend, JS in front-end. This would solve most of your worries."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-10T21:33:39.360",
"Id": "114086",
"Score": "0",
"body": "Gotcha! Thanks for shedding light on this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-07T10:11:19.410",
"Id": "507128",
"Score": "0",
"body": "I wrote a Python tool called [Reconstant](https://github.com/aantn/reconstant) to solve this exact problem."
}
] |
[
{
"body": "<p>I'm not familiar with PL/SQL so I'm unsure what exactly is being done with it. However, the commonly accepted solution for sharing between PHP and JavaScript is to use a JSON file. JSON is native to JS, its even in the name. PHP also supports JSON via its <code>json_encode()</code> and <code>json_decode()</code> functions. Here's an example of what the JSON file might look like:</p>\n\n<pre><code>{\n \"BASE_IMAGE\" : \"/app/images/\",\n \"BASE_ICON\" : \"/app/images/icons/\",\n \"DEFAULT_USER_NAME\" : \"Your Name\"\n}\n</code></pre>\n\n<p>You can import a JSON string with <code>json_decode()</code>, which means you need to read the file into a string first, in order to get either a JSON object or a multidimensional array.</p>\n\n<pre><code>//as an object\n$constants = json_decode( $json );\necho $constants->BASE_IMAGE;// echos /app/images/\n\n//as an array\n$constants = json_decode( $json, TRUE );\necho $constants[ 'BASE_IMAGE' ];// echos /app/images/\n</code></pre>\n\n<p>And of course, if you wish to use them as actual constants, you can loop over the array and define them.</p>\n\n<pre><code>foreach( $constants AS $constant => $value ) {\n define( $constant, $value );\n}\n</code></pre>\n\n<p>I believe this accomplishes the same thing you are currently doing, only without the extra files. The only downfall is that you wont be able to use those XML entities to declare shared elements, unless of course you end up generating the JSON from the XML. However, I think that might be just a bit much. At that point you should then just turn to some JS library to read the XML directly as you can already do with PHP. Hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T17:50:24.197",
"Id": "31929",
"Score": "0",
"body": "@DaveJarvis: I was assuming the XSLT was simply to help convert the XML file into the various languages you needed to use them in. If the XML file became unnecessary wouldn't the XSLT file also become unnecessary? I don't know PL/SQL so I'm unable to offer much advice here, but a quick google search suggests there might be libraries for it. The same goes for bash. I know Java has libraries, though I haven't had much experience with them. The problem would be downloading these extra libraries, but I don't know of any other way. Then again, I didn't even know about the one you found."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T18:58:33.113",
"Id": "31934",
"Score": "0",
"body": "The same value (e.g., DEFAULT_USER_NAME) could be used in PHP, JavaScript, XSL, Java, PL/SQL, or even bash. For PL/SQL, there's not much of an issue because the database can select from the configuration table directly. I'm wondering if this approach (using a configuration table, generating an XML document, then transforming the constants into their native implementation language via XSL) to isolate duplicate constants is a good design. I don't know why you mention Java libraries -- it has nothing to do with the problem?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T19:19:00.943",
"Id": "31935",
"Score": "0",
"body": "@DaveJarvis: I mentioned Java and bash libraries because you mentioned possible future expansion into them. I think I may have been missing something which is why there seems to be confusion. I was under the impression your configuration table began with the XML file. But I think I got it now. Is PL/SQL being used for anything else, or would removing it, the original config table, the XML, AND XSLT and replacing them with a single JSON file be plausible? As I mentioned, all those other languages have libraries to import the JSON to be used directly, which seemingly solves your dilemma."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T20:50:51.310",
"Id": "31936",
"Score": "0",
"body": "The configuration table is, quite literally, a database table. I use the configuration table to generate an XML document, and that XML document becomes the source point for creating variables in other languages. There is PL/SQL code that relies on the configuration table. Moving to JSON away from a configuration table means duplicating `'/app/'` in the JSON file. I'm trying to avoid duplication altogether. Plus, maintaining a database is easier than a JSON file (i.e., there is a huge supporting infrastructure that exists for generating web based code table editors)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T22:08:00.400",
"Id": "31938",
"Score": "0",
"body": "@DaveJarvis: I don't really think there's any other solution than the one you have then. The problem is the libraries available to you. If it wasn't for JavaScript you could probably have all the other languages just access the table directly, but at most you can subtract one step from what you are currently doing. Every language you listed can import XML data, so you don't have to use XSLT to create those custom constant pages, you can just access them directly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T23:40:55.310",
"Id": "31940",
"Score": "1",
"body": "But then to access the XML, wouldn't I have to write and maintain import code (i.e., more than one line of code) for every language in separate source files? (As opposed to one XSL file, which also avoids repetitious logic?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T01:27:42.270",
"Id": "31943",
"Score": "0",
"body": "Yes. I didn't say better, just that it was an alternative and the only one I could see. Right now you are more or less maintaining that anyways, just in XML and XSLT. I think the method you found may be the best, but I would wait to see what others think. I've never needed to maintain my code across so many platforms before."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T14:44:57.523",
"Id": "19968",
"ParentId": "19953",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "19968",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-26T21:03:01.607",
"Id": "19953",
"Score": "12",
"Tags": [
"javascript",
"php",
"postgresql",
"xslt"
],
"Title": "Cross-language constants"
}
|
19953
|
<p>This is what i had before (using the MySQL api)</p>
<pre><code>$info_get = mysqli_query("SELECT * FROM `users` WHERE `uid`='".$_SESSION['uid']."'") or die(mysqli_error());
$info = mysql_fetch_assoc($info_get);
</code></pre>
<p>This is after I converted it to MySQLi</p>
<pre><code>$var = $_SESSION['uid']; //var is an integet
$table = "users"
if($stmt = mysqli_prepare($link, "SELECT * FROM ? WHERE `uid`=?")) {
mysqli_stmt_bind_param($stmt, "i", $var);
mysqli_stmt_execute($stmt);
$info = mysqli_fetch_assoc($stmt);
}
</code></pre>
<p><strong>1. Would the above two examples output the same result for $info['column']</strong></p>
<p><strong>2. <code>require_once</code> or <code>include</code> : Which one is better to use?</strong></p>
<p><strong>3. Any more advice?</strong></p>
|
[] |
[
{
"body": "<p>No need to \"bump\" someone will eventually get around to it. It doesn't even work that way. Your question will always be towards the top of the PHP section, assuming it hasn't been too long (days). The only thing \"bumping\" does is boost it to the top of the ALL Languages section which isn't likely to get too much more attention. Code Review is a lot slower than SO, so patience is required.</p>\n\n<p><strong>Would the above two examples output the same result for $info['column']</strong></p>\n\n<p>I don't think so. I was never really good with SQL, and I have never done anything with MySQLi, always preferring PDO, but correct me if I'm wrong: You have two entities to fill in your prepared statement. The first is the field for <code>FROM</code>, the second is the <code>uid</code>. The bind statement would then bind <code>$var</code> to the <code>FROM</code> field. Maybe change that first question mark back to what you had before and it looks like it should work. But again, SQL is a failing of mine, so you might want to hold out for a more definitive answer, or just try it for yourself.</p>\n\n<p><strong>require_once or include : Which one is better to use?</strong></p>\n\n<p>That really depends. And seen as you are not providing any code for consideration all I can do is just give you some general advice. The <code>*_once()</code> versions of <code>require()</code> and <code>include()</code> are always going to be slightly less efficient than their counterparts, but that is to be expected as they must determine if the page they are being asked to include already exists. With just a few files this difference is negligible, though typically you should still avoid it. You should always know whether a page has already been included, thus making the need for verifying it unnecessary.</p>\n\n<p>Now, as to the difference between <code>require()</code> and <code>include()</code>. Again, that depends. If the page you are including is \"required\" to perform the next bit of operations, you should require it, otherwise you risk the PHP engine outpacing the render and failing. If it is of no consequence, then a normal include is fine.</p>\n\n<p><strong>Any more advice?</strong></p>\n\n<p>Initially, with the MySQL, or rather what you are saying is the MySQL as it still mostly looks like MySQLi, the <code>or die()</code> phrase should die. It was never really all that acceptable even though many sites use it to demonstrate. <code>die()</code> is a very inelegant way of terminating execution. The proper way would be to throw an error or render some sort of error page, with the former eventually leading to latter anyways. You especially shouldn't output the error for anyone to see, that should be saved to a log. No need to give potential malicious users more information than necessary.</p>\n\n<p><code>$var</code> is a very undescriptive variable, and the comment afterwards doesn't really help either. You shouldn't really rely on comments to explain your code anyways. Make your code self-documenting and comments, excluding doccomments, will become unnecessary. Why not just use <code>$user_id</code>, or <code>$uid</code>, or even just <code>$id</code>?</p>\n\n<p>You should always avoid declaring a variable in a statement. There are some exceptions, such as in loops, but if statements should definitely be avoided. There's no way to tell, for 100%, whether an assignment was meant or a comparison. I know that's what the PHP documentation shows, but they should be ashamed of themselves. That's bad form. Abstract it.</p>\n\n<pre><code>$stmt = mysqli_prepare( $link, \"SELECT * FROM ? WHERE `uid`=?\" );\nif( $stmt ) {\n</code></pre>\n\n<p>That being said, why are you adamant about the procedural style? The OOP style seems to make more sense, at least to me. There is less to type and it makes use of the <code>$stmt</code> object you created.</p>\n\n<pre><code>if( $stmt ) {\n $stmt->bind_param( 'i', $var );\n</code></pre>\n\n<p>Finally, this question is bordering on being off topic. It may have even already passed that line seen as the code you gave looks like it has errors. Be careful of that in the future.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T00:16:13.317",
"Id": "31941",
"Score": "0",
"body": "Thank you very much. I will be weary of that in the future, and thanks for the general advice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T15:33:52.800",
"Id": "19970",
"ParentId": "19957",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19970",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T03:15:04.003",
"Id": "19957",
"Score": "-1",
"Tags": [
"php",
"mysqli"
],
"Title": "(Procedural)(Snippet) MySQL to MySQLi. Any advice?"
}
|
19957
|
<p>Essentially I'm wondering if this implementation of an interface is correct. I mostly don't like having to repeat the exact same getters and setters. Is there a better way or is this alright?</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
namespace TetrisPro
{
interface Block
{
Color GetColor();
Position[] GetPosition();
Position GetPosition(int i);
Position[] GetOldPosition();
Position GetOldPosition(int i);
}
class Square : Block
{
private Color color;
private Position[] position;
private Position[] oldPosition;
public Square()
{
this.color = Color.Firebrick;
this.position = new Position[4];
this.oldPosition = new Position[4];
SetPosition();
}
public Square(int x, int y)
{
this.color = Color.GreenYellow;
this.position = new Position[4];
this.oldPosition = new Position[4];
SetPosition();
SetPosition(x, y);
}
public void SetPosition()
{
this.position[0] = new Position(0, 0);
this.position[1] = new Position(0, 1);
this.position[2] = new Position(1, 0);
this.position[3] = new Position(1, 1);
}
public void SetPosition(int x, int y)
{
this.oldPosition = position;
this.position[0] = new Position(x, y);
this.position[1] = new Position(x, y + 1);
this.position[2] = new Position(x + 1, y);
this.position[3] = new Position(x + 1, y + 1);
}
public Color GetColor()
{
return this.color;
}
public Position[] GetPosition()
{
return this.position;
}
public Position GetPosition(int i)
{
return this.position[i];
}
public Position[] GetOldPosition()
{
return this.oldPosition;
}
public Position GetOldPosition(int i)
{
return this.oldPosition[i];
}
}
class Line : Block
{
private Color color;
private Position[] position;
private Position[] oldPosition;
public Line()
{
this.color = Color.BlueViolet;
this.position = new Position[4];
this.oldPosition = new Position[4];
SetPosition();
}
public void SetPosition()
{
this.position[0] = new Position(0, 0);
this.position[1] = new Position(0, 1);
this.position[2] = new Position(0, 2);
this.position[3] = new Position(0, 3);
}
public void SetPosition(int x, int y)
{
this.oldPosition = position;
this.position[0] = new Position(x, y);
this.position[1] = new Position(x, y + 1);
this.position[2] = new Position(x, y + 2);
this.position[3] = new Position(x, y + 3);
}
public Color GetColor()
{
return this.color;
}
public Position[] GetPosition()
{
return this.position;
}
public Position GetPosition(int i)
{
return this.position[i];
}
public Position[] GetOldPosition()
{
return this.oldPosition;
}
public Position GetOldPosition(int i)
{
return this.oldPosition[i];
}
}
class ZLeft : Block
{
private Color color;
private Position[] position;
private Position[] oldPosition;
public ZLeft()
{
this.color = Color.DodgerBlue;
this.position = new Position[4];
this.oldPosition = new Position[4];
SetPosition();
}
public void SetPosition()
{
this.position[0] = new Position(0, 0);
this.position[1] = new Position(1, 0);
this.position[2] = new Position(1, 1);
this.position[3] = new Position(2, 1);
}
public void SetPosition(int x, int y)
{
this.oldPosition = position;
this.position[0] = new Position(x, y);
this.position[1] = new Position(x + 1, y);
this.position[2] = new Position(x + 1, y + 1);
this.position[3] = new Position(x + 2, y + 1);
}
public Color GetColor()
{
return this.color;
}
public Position[] GetPosition()
{
return this.position;
}
public Position GetPosition(int i)
{
return this.position[i];
}
public Position[] GetOldPosition()
{
return this.oldPosition;
}
public Position GetOldPosition(int i)
{
return this.oldPosition[i];
}
}
// ... more classes
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-11T18:13:29.837",
"Id": "71153",
"Score": "0",
"body": "Check for the snippet creation walkthrough on MSDN. It can help if you want to implement some properties and getter + setter over dozen of class without having to rewrite everything."
}
] |
[
{
"body": "<p>Please read <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/ms229040%28v=vs.100%29.aspx\">.NET Naming conventions</a>, in particular interfaces should be prefixed with <code>I</code> (<code>Block</code> => <code>IBlock</code>).</p>\n\n<ul>\n<li>Your interface doesn't include SetPosition while all classes that implement this interface do have it. </li>\n<li>There is no need to declare both <code>GetPosition()</code> and <code>GetPosition(int)</code> as latter doesn't add any value to interface, can be implemented as an extension method if needed.</li>\n<li>When your objects are created via parameterless constructor you get an inconsistent state (OldPosition is not initialised with <code>Position</code> objects)</li>\n<li>You mentioned getters and setters while you don't have any properties defined. I would replace <code>GetPosition()</code> with read-only property, and define only one <code>SetPosition(int,int)</code> method as an object mutator. If you do need parameterless <code>SetPosition</code> you can create extension method for <code>IBlock</code> interface that will call <code>SetPosition(0, 0)</code></li>\n<li><p>In order to avoid repeating implementation you can consider creating a base class, so that derived classes will only need to override <code>SetPosition(int,int)</code>.</p>\n\n<pre><code>public interface IBlock\n{\n Color Color { get; }\n Position[] Position { get; }\n Position[] OldPosition { get; }\n void SetPosition(int x, int y);\n}\n\npublic class Block : IBlock\n{\n private readonly Point[] _structure;\n\n public Color Color { get; private set; }\n public Position[] Position { get; private set; }\n public Position[] OldPosition { get; private set; }\n\n public Block(Color color, Point[] structure, int x = 0, int y = 0)\n {\n Color = color;\n _structure = structure;\n //to properly initialise both Old and current positions\n SetPosition(0, 0);\n SetPosition(x, y);\n }\n\n private Position[] BuildPosition(int x, int y)\n {\n return Array.ConvertAll(_structure, point => new Position(x + point.X, y + point.Y));\n }\n\n public void SetPosition(int x, int y)\n {\n OldPosition = Position;\n Position = BuildPosition(x, y);\n }\n}\n\npublic class Line : Block\n{\n public Line(int x = 0, int y = 0)\n : base(Color.BlueViolet, new Point[] { new Point(0, 0), new Point(0, 1), new Point(0, 2), new Point(0, 3) }, x, y)\n {\n\n }\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T11:39:57.253",
"Id": "31914",
"Score": "0",
"body": "You shouldn't be calling virtual members from a base class (`Block`) constructor. Also, since `Block` class is abstract the constructors should be `protected` not `public`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T14:48:55.200",
"Id": "31923",
"Score": "0",
"body": "Agree, updated answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T06:40:39.137",
"Id": "31947",
"Score": "0",
"body": "i'm sorry I'm not very familiar with C# yet, but what does Point mean or do? Also can you explain the constructor for line? does that mean it defaults to x=0, y=0? I'm also new to what base means"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T10:29:03.927",
"Id": "31950",
"Score": "1",
"body": "`Point` is the structure that has 2 integer properties: X and Y. I use it to store the figure configuration (shifts from base coordinates. Constructor's `x = 0` means that these parameters are optional, and if caller won't provide provide this parameter it will be defaulted to 0. As to your last question - it looks like you're new to object-oriented programming, you need to learn it. `base` means that we're calling constructor of the base class, see [Inheritance](http://msdn.microsoft.com/en-us/library/ms173149(v=vs.110).aspx)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T06:22:23.763",
"Id": "19960",
"ParentId": "19958",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "19960",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T03:53:45.383",
"Id": "19958",
"Score": "1",
"Tags": [
"c#",
"xna"
],
"Title": "C#/XNA interface usage, repeating functions"
}
|
19958
|
<p>So, I have coded a PHP script that will make it able for the users to edit their Post, or comments on a site that runs SociaEngine 4.</p>
<p>So, Is there anything that could get inproved/fixed on this?</p>
<pre><code><?php
session_start();
$Mysql_Hostname = "192.168.1.110";
$Mysql_Username = "*user";
$Mysql_Password = "************";
$Mysql_Database = "Socialengine";
$Sql = new mysqli($Mysql_Hostname, $Mysql_Username, $Mysql_Password, $Mysql_Database);
if ($Sql->connect_error){die($Sql->connect_error);}
$ID = session_id(); // Get session cookie data / id
$GetSession = $Sql->query("SELECT * FROM `engine4_core_session` WHERE id = '".$ID."'"); // Get the session data for the user.
$Session = $GetSession->fetch_array(); // blah blah...
if($Session['user_id'] == NULL) { die("You need to be logged inn to use this"); } // Check if the user is logged inn
$GetUser = $Sql->query("SELECT * FROM `engine4_users` WHERE `user_id` = '".$Session['user_id']."'"); // Get user data
$User = $GetUser->fetch_array(); // blah...
echo "<p>You are currenty logged inn as: ".$User['displayname']."</p>"; // Give a message that they are logged in
if($_GET['mode'] == "done") { // If they have edited, Then close the window
echo '<script type="text/javascript"> window.close(); </script>';
}
if($_GET['mode'] == "edit") { // If they want to edit a comment...
$CID = $_GET['id']; // Get comment id
$GetComment = $Sql->query("SELECT * FROM `engine4_activity_comments` WHERE `poster_id` = '".$Session['user_id']."' AND `comment_id` = '".$Sql->real_escape_string($CID)."'"); // Get the comment from Mysql with User restriction...
$Comment = $GetComment->fetch_array(); // blah
if($GetComment->num_rows == 0) { die("Not authorized to edit"); } // If the comment wasn't theirs, Then die...
echo <<<HTML
<form action="Session.php?mode=done&type=comment" method="post">
<input type="hidden" name="ID" value="{$Comment['comment_id']}">
<textarea rows="3" cols="45" name="Comment">{$Comment['body']}</textarea>
<p><input type="submit" value="Edit comment"></p>
</form>
HTML;
// Render the edit form
exit; // Stop processing
}
if($_GET['mode'] == "post") { // If they want to edit a post...
$CID = $_GET['id']; // Get post id
$GetPost = $Sql->query("SELECT * FROM `engine4_activity_actions` WHERE `subject_id` = '".$Session['user_id']."' AND `action_id` = '".$Sql->real_escape_string($CID)."'"); // Same as comments, Get with post id and user id
$Post = $GetPost->fetch_array(); // blah
if($GetPost->num_rows == 0) { die("Not authorized to edit"); } // No! Don't try to edit others post's...
echo <<<HTML
<form action="Session.php?mode=done&type=post" method="post">
<input type="hidden" name="ID" value="{$Post['action_id']}">
<textarea rows="3" cols="45" name="Comment">{$Post['body']}</textarea>
<p><input type="submit" value="Edit post"></p>
</form>
HTML;
// Render the post edit form
exit; // and stop
}
if(isset($_POST['Comment'])) { // If the form has been submitted.
if($_GET['type'] == "comment") { // Check if it's a comment or a post
$Verify = $Sql->query("SELECT * FROM `engine4_activity_comments` WHERE `poster_id` = '".$Session['user_id']."' AND `comment_id` = '".$Sql->real_escape_string($_POST['ID'])."'"); // Verify if it's theirs...
if($Verify->num_rows == 1) { // If it's theirs, Contiune
$Update = $Sql->query("UPDATE `Manehatten`.`engine4_activity_comments` SET `body` = '".$Sql->real_escape_string($_POST['Comment'])."'
WHERE `poster_id` = '".$Session['user_id']."' AND `comment_id` = '".$Sql->real_escape_string($_POST['ID'])."'"); // Update the data in mysql
}
}
elseif($_GET['type'] == "post") { // Check if it's a comment or a post
$Verify = $Sql->query("SELECT * FROM `engine4_activity_actions` WHERE `subject_id` = '".$Session['user_id']."' AND `action_id` = '".$Sql->real_escape_string($_POST['ID'])."'"); // Verify if it's theirs...
if($Verify->num_rows == 1) { // If it's theirs, Contiune
$Update = $Sql->query("UPDATE `Manehatten`.`engine4_activity_actions` SET `body` = '".$Sql->real_escape_string($_POST['Comment'])."'
WHERE `subject_id` = '".$Session['user_id']."' AND `action_id` = '".$Sql->real_escape_string($_POST['ID'])."'"); // Update the data..
}
}
}
// This script is only for test, or comment id getting /IGNORE THIS/
echo "<p>Displaying Comments with Limit of 30 </p>";
echo "<hr>";
$GetComments = $Sql->query("SELECT * FROM `engine4_activity_comments` WHERE `poster_id` = '".$Session['user_id']."' ORDER BY `engine4_activity_comments`.`creation_date` DESC LIMIT 0, 30");
while($Data = $GetComments->fetch_assoc()){
echo "<p>".$Data['body'].' | ID: <a href="Session.php?mode=edit&id='.$Data['comment_id'].'">'.$Data['comment_id']."</a> <- Click to edit</p>";
}
</code></pre>
<p>I have added comments for what lines do what.</p>
<p>I am just a bit unsure if they can use this and alter their session cookie to gather a valid user cookie. </p>
<p>The script works fine, Just that if there was something that could be improved.</p>
|
[] |
[
{
"body": "<p>You might consider incorporating a config file for your SQL connection. This will allow you to reuse it should that become necessary and update it more easily. Additionally, the <code>$Mysql_*</code> namespace seems unnecessary.</p>\n\n<p>Typically variables are not capitalized. This may just be a style choice, but it looks odd and may cause issues should anyone decide to try and integrate your script into their own.</p>\n\n<p><code>die()</code> is a very inelegant way of terminating your script. You should throw an error or render an error page, with the former eventually accomplishing the latter anyways. You especially shouldn't just dump the error onto the page for any malicious user to see. Save it to a log. The same goes for <code>exit</code>, except you should return early instead. Returning early is really only possible with functions, but exiting the script completely stops everything. That means that if this script were included in another and that other script still needed to do something it couldn't, making your script very hard to incorporate.</p>\n\n<p>Comments explaining your code should be unnecessary. If your code is self-documenting then it should be obvious. You should especially avoid comments that don't add anything to your code, such as \"blah...\", its just clutter and makes your code less legible.</p>\n\n<p>You are using MySQLi, which is a prepared SQL language, but you aren't using prepared statements. I'm not much of a SQL guru here, but I thought that was the whole reason for the switch from MySQL to MySQLi/PDO.</p>\n\n<p>You might also consider adding whitespace to your SQL statements and long PHP statements. Neither PHP nor SQL minds extra whitespace, so making your code more legible is always a plus. The following might be a little excessive, I rewrote it using my style, but it just demonstrates how little whitespace makes a difference in operation, and how much more it adds to legibility.</p>\n\n<pre><code>$GetSession = $Sql->query( \"\n SELECT *\n FROM `engine4_core_session`\n WHERE id = '\" . $ID . \"'\n\" );\n\n//and\n\nif( $Session[ 'user_id' ] == NULL ) {\n die( \"You need to be logged inn to use this\" );\n}\n</code></pre>\n\n<p>Also, there is no need to escape the string sequence to incorporate the PHP variable. That's the whole reason for using double quotes. PHP automatically escapes any entities or variables it finds in double quoted strings.</p>\n\n<pre><code>\"WHERE id = '$ID'\"\n</code></pre>\n\n<p>There is no need to explicitly check for a NULL value when doing a loose <code>==</code> comparison. Unless you are specifically looking for NULL, in which case you should be using an absolute <code>===</code> comparison.</p>\n\n<pre><code>if( ! $Session[ 'user_id' ] ) {\n</code></pre>\n\n<p>Instead of echoing HTML, you should consider escaping from PHP. This will allow your IDE to do proper tag matching/highlighting, and will make your code a little easier to read.</p>\n\n<pre><code>?>\n\n<p>You are currently logged in as: <?php echo $User[ 'displayname' ]; ?></p>\n\n<?php\n</code></pre>\n\n<p>When outputting a lot of HTML, you can consider creating an include. This cleans up some of the clutter from your PHP and separates the display from the logic.</p>\n\n<pre><code>//include page\n<form action=\"Session.php?mode=done&type=comment\" method=\"post\">\n<input type=\"hidden\" name=\"ID\" value=\"<?php echo $Comment[ 'comment_id' ]; ?>\">\n<textarea rows=\"3\" cols=\"45\" name=\"Comment\">\n <?php echo $Comment[ 'body' ]; ?>\n</textarea>\n<p><input type=\"submit\" value=\"Edit comment\"></p>\n</form>\n</code></pre>\n\n<p>When you find yourself comparing the same variable multiple times against different values, you might consider using a switch. Switches are slightly faster than a normal if statement and are a little cleaner.</p>\n\n<pre><code>switch( $_GET[ 'mode' ] ) {\n case 'done' :\n //etc...\n break;\n\n case 'edit' :\n //etc...\n break;\n\n //etc...\n}\n</code></pre>\n\n<p>The rest appears to be more of the same. The biggest improvement I can suggest would be to incorporate the use of functions to make this more legible and reusable. Also you appear to be violating the \"Don't Repeat Yourself\" (DRY) Principle. As the name implies, your code should not repeat itself. Some of those latter SQL statements appeared very similar, meaning you could probably create a template string and modify it as necessary. Hope this helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T16:21:29.607",
"Id": "19973",
"ParentId": "19959",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "19973",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T05:45:18.103",
"Id": "19959",
"Score": "0",
"Tags": [
"php"
],
"Title": "SocialEngine 4: Edit Post / Comment feature [Anything that can be improved? ]"
}
|
19959
|
<p>I have following queries</p>
<p>First one using inner join</p>
<blockquote>
<pre><code>SELECT item_ID,item_Code,item_Name
FROM [Pharmacy].[tblitemHdr] I INNER JOIN EMR.tblFavourites F ON I.item_ID=F.itemID
WHERE F.doctorID = @doctorId AND F.favType = 'I'
</code></pre>
</blockquote>
<p>second one using sub query like</p>
<pre><code>SELECT item_ID,item_Code,item_Name from [Pharmacy].[tblitemHdr]
WHERE item_ID IN
(SELECT itemID FROM EMR.tblFavourites
WHERE doctorID = @doctorId AND favType = 'I'
)
</code></pre>
<p>In this item table <code>[Pharmacy].[tblitemHdr]</code> Contains 15 columns and 2000 records. And <code>[Pharmacy].[tblitemHdr]</code> contains 5 columns and around 100 records. in this scenario <code>which query gives me better performance?</code></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T01:36:32.513",
"Id": "31945",
"Score": "0",
"body": "Have you checked the [execution plans](http://sqlserverpedia.com/wiki/Examining_Query_Execution_Plans) for the two queries?"
}
] |
[
{
"body": "<p>The SQL Server query analyzer is smart enough to understand that these queries are identical (given that <code>item_ID</code> is unique in <code>EMR.tblFavourites</code> for a certain doctorID/favType pair). </p>\n\n<p>They should yield exactly the same execution plan, and thus they are equal in terms of performance. I would prefer second variant though...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T10:19:58.917",
"Id": "19964",
"ParentId": "19962",
"Score": "3"
}
},
{
"body": "<p>I'm not familiar with Microsoft SQL server (I assume that this is actual SQL server mentioned here). Actually I'm pretty sure that <code>IN</code> will not produce multiplication of rows if there is two entries for single <code>F.itemID</code> in contrast with <code>INNER JOIN</code>.</p>\n\n<p>I suspect that with absence of unique index on <code>F.itemID</code> performance may differ too. Probably <code>IN</code> will prefer to ordered unique set of relations while <code>FROM</code> will consider statistics of both tables more equally than <code>IN</code>.</p>\n\n<p>P.S. I prefer <code>JOIN</code> because of giving hint for optimizer while dropping off additional constraint. And it looks a bit more readable as for me (less amount of <code>SELECT</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T11:59:10.477",
"Id": "19965",
"ParentId": "19962",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "19964",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T09:39:35.967",
"Id": "19962",
"Score": "3",
"Tags": [
"optimization",
"sql",
"sql-server"
],
"Title": "Subquery v/s inner join in sql server"
}
|
19962
|
<p>Given the following code, I have written a <code>for</code> loop that returns a key and value (0 or 1) of file names passed. 1 means present, and 0 means not present.</p>
<p>Is there a way to construct a flat map without having to use <code>into</code>?</p>
<pre><code>(defn kind-stat
[filename expected-type]
(let [f (File. filename)
s (cond
(.isFile f) "f"
(.isDirectory f) "d"
(.exists f) "o"
:else "n" )]
(if (= expected-type s)
0
1)))
(defn look-for
[filename expected-type]
(let [find-status (kind-stat filename expected-type)]
find-status))
(defn all-files-present?
"Takes a list of real file names, and returns a sequence of maps
indicating the file name and its availability status 1 for present
and 0 for not present. Please note look-for returns 0 for success,
so its return logic needs to be reversed for the return sequence
of maps."
[file-seq]
(for [fnam file-seq
:let [stat-map {(keyword fnam)
(if (= (look-for fnam "f") 0)
1
0)}]]
stat-map))
(into {}
(all-files-present? '("Makefile" "build.sh" "real-estate.csv")))
{:Makefile 1, :build.sh 1, :real-estate.csv 0}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T17:28:52.980",
"Id": "31928",
"Score": "0",
"body": "I agree, this belongs on codereview. Though I would get rid of your let and if, and make them one whole, and have expected type be the function that accepts f so instead of f, d, o, h, you actually hand it .isFile .isDirectory .exists. That's the critique I would give on code review in my immediate albeit small review. Also I would return instead of 1 or 0 in the sequence, make it the closure to execute to find out if it's present, since it's presence may be transient and can then be checked as needed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T17:55:23.710",
"Id": "31930",
"Score": "0",
"body": "What is the *purpose* of this code? Do you want to know if *all* files are present, or if *each* file is present? If it's an all or nothing, you just need to do a reduce with the kind-stat returning true/false and an and"
}
] |
[
{
"body": "<p>You could use <a href=\"http://clojuredocs.org/clojure_core/1.2.0/clojure.core/zipmap\" rel=\"nofollow\"><code>zipmap</code></a>:</p>\n\n<pre><code>(defn all-files-present?\n [file-seq]\n (let [f #(bit-flip (look-for % \"f\") 0)]\n (zipmap (map keyword file-seq) (map f file-seq))))\n</code></pre>\n\n<p>or <a href=\"http://clojuredocs.org/clojure_core/1.2.0/clojure.core/juxt\" rel=\"nofollow\"><code>juxt</code></a>:</p>\n\n<pre><code>(defn all-files-present?\n [file-seq]\n (let [f #(bit-flip (look-for % \"f\") 0)]\n (into {} (map (juxt keyword f) file-seq))))\n</code></pre>\n\n<p>Note that I use <a href=\"http://clojuredocs.org/clojure_core/clojure.core/bit-flip\" rel=\"nofollow\"><code>bit-flip</code></a> instead of the <code>if</code> to flip <code>1<->0</code>. </p>\n\n<hr>\n\n<p>It would be nicer if <code>kind-stat</code> would just return a boolen value, so you would simply use</p>\n\n<pre><code>(defn kind-stat\n [filename expected-type]\n (let [f (File. filename)]\n (= expected-type \n (cond\n (.isFile f) \"f\"\n (.isDirectory f) \"d\"\n (.exists f) \"o\" \n :else \"n\"))))\n\n(defn all-files-present?\n [file-seq]\n (let [f #(if (kind-stat % \"f\") 1 0)]\n (into {} (map (juxt keyword f) file-seq))))\n</code></pre>\n\n<p>I removed <code>look-for</code>, since it is virtually useless.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-14T15:41:55.977",
"Id": "22715",
"ParentId": "19974",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "22715",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T16:55:04.193",
"Id": "19974",
"Score": "3",
"Tags": [
"file-system",
"clojure"
],
"Title": "Check for the presence of multiple files"
}
|
19974
|
<p>I've started to learn an OOP and I've built a class called accountactions, and I would like to know if I did a good job writing it.</p>
<p>The class is in the file: accountactions.class.php.</p>
<pre><code><?php
class accountactions(){
public function register($login, $password, $email){
//Zapisujemy dane wysłane formularzem
$this->username = mysql_real_escape_string($login);
$this->password = mysql_real_escape_string($password);
$this->email = mysql_real_escape_string($email);
//Hash password
$this->password = md5(sha1($this->password));
$db->simplequery("INSERT INTO radio_users(id, username, password, email) VALUES('', '$this->username', '$this->password', '$this->email')");
}
}
?>
</code></pre>
<p>The register.php file:</p>
<pre><code><?php
require_once("accountactions.class.php");
$account = new accountactions();
$account->register('samplelogin', 'samplepassword', 'sample@email');
?>
</code></pre>
<p>And I am having some issues with this fragment:</p>
<pre><code>$db->simplequery("INSERT INTO radio_users(id, username, password, email) VALUES('', '$this->username', '$this->password', '$this->email')");
</code></pre>
<p>How do I join my db class to my account class?</p>
<p>I'd like to keep a model where I can do something like:</p>
<pre><code>$account->register('$_POST['login']', '$_POST['password']', '$_POST['email']');
</code></pre>
<p>Unless there is a better way to do this.</p>
<p>Im newbie in OOP so any tips and guidelines are appreciated.</p>
|
[] |
[
{
"body": "<p>I think you have three options:</p>\n\n<ol>\n<li>Create a setter: <code>public function setDatabase($database) { ... }</code> and everytime the <code>accountactions</code> class is instantiated call it to provide the database functionality.</li>\n<li>Make a constructor that will require your database instance: `public function __construct($database) { ... }</li>\n<li>Create some kind of static factory class/method (e.g. <code>Configuration</code> class) that would instantiate database class - then you could use both above solutions to provide the database or even use the static factory class/method inside the <code>accountactions</code> class (which is the least preferable as far as OOP is concerned)</li>\n</ol>\n\n<p>The most flexible (e.g. for testing) is the 1st solution. </p>\n\n<p>The 2nd solution is what I did in my last project.</p>\n\n<p>The 3rd solution would give you the benefit of writing less code because you wouldn't have to write constructors with the database parameter or instantiate your database class before setting/constructing a particular class. But this is a killer for testing - you should then provide some mechanism of e.g. injection a database prototype factory into the class with the static factory method. Then the real instantiation of database objects would be delegated to a prototype factory that could be replaced by the mock while testing.</p>\n\n<p>In my last small PHP project I've created class <code>Database</code>:</p>\n\n<pre><code>class Database {\n\nprivate $log;\nprivate $db_host;\nprivate $db_user;\nprivate $db_password;\nprivate $db_name;\nprivate $con = NULL;\n\npublic function __construct($db_host, $db_user, $db_password) {\n $this->log = ...;\n $this->db_host = $db_host;\n $this->db_user = $db_user;\n $this->db_password = $db_password;\n $this->db_name = NULL;\n}\n...\npublic function connect($db_name = NULL) { ... }\npublic function close() { ... }\npublic function dropTable($tableName) { ... }\npublic function rawQuery($query, $safeQuery = false) { ... }\n...\n}\n</code></pre>\n\n<p>And I provided it in a constructor of the particular class:</p>\n\n<pre><code>class OtherClass {\n ...\n public function __construct($db, $param, ...) { ... }\n ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T19:56:59.493",
"Id": "19979",
"ParentId": "19976",
"Score": "0"
}
},
{
"body": "<p>Organization, while not exactly code related, is still very important. Especially when it comes to OOP and especially when you're just getting started. If your code is organized correctly, there is no need for namespaces such as \".class\". I spent a solid week perusing different frameworks before finally deciding on one I liked. Then I spent another month fine tuning and tweaking it. Originally, my organizational scheme came from the Zend framework.</p>\n\n<pre><code>application\n configs\n controllers\n models\n views\ndata\n logs\n cache\npublic\n images\n css\n js\n</code></pre>\n\n<p>There's a bit more to it, but I got the most important bits. This scheme specifically caters to an MVC framework, so it may not apply to your situation. You don't have to use this scheme, you don't even have to use a popular one. Hell, you can create your own to fit your own needs, and sometimes that is required. However, a good organizational scheme is hard to find and the popular ones are usually popular for a reason. And one thing a good organizational scheme should do is allow you to avoid namespacing your files. In my scheme my class files would go in one of two folders. The \"controllers\" or the \"models\". Knowing these were the only locations for class files means I don't have to namespace them.</p>\n\n<p>Sorry for the mini-rant, let's move along now. I don't really see anything wrong with the OOP, but then again, there's not really much going on here. I do have a few suggestions that might help though.</p>\n\n<p>First, your class is incomplete. You have three class properties and have not declared them. You should always declare your properties, otherwise you risk allowing public access to private properties, such as the password property.</p>\n\n<pre><code>class accountactions() {\n private\n $username,\n $password,\n $emal\n ;\n</code></pre>\n\n<p>You should avoid internal comments as they just add clutter to your code. If your code is self-documenting then most comments become unnecessary anyways. Everything else can be relegated to doccomments. So, for instance: \"Hash password\" is pretty obvious from the context and is unnecessary.</p>\n\n<p>Its a minor violation, but still, there is a violation of the \"Don't Repeat Yourself\" (DRY) Principle here. As the name implies, your code should not repeat itself. You use the same function on each of your method's parameters in order to sanitize them. The easiest way to do this would be to change the way the method accepts its parameters so that you instead accepted an array. Then you could loop or walk over the array to sanitize its contents. For instance:</p>\n\n<pre><code>public function register( Array $credentials ) {\n array_walk( $credentials, 'mysql_real_escape_string' );\n\n $this->username = $credentials[ 'username' ];\n //etc...\n</code></pre>\n\n<p>However, there is a problem with this. For one, these parameters should not be sanitized. Validated: yes; Sanitized: no. You validate for registry; You sanitize for login. If you sanitize them now then you could be changing what that user provided without informing them, which could cause all kinds of confusion. The better thing to do here would be to verify that it has no illegal characters and have the user change it if necessary. Once you validate it, it has essentially been sanitized and you can use it like normal.</p>\n\n<p>Another thing you might consider is using custom sanitizing/validating filters. <code>mysql_real_escape_string()</code> was a very nifty tool when you had nothing better to use, but now there are options such as <code>filter_input()</code> and <code>filter_var()</code>. The former should only be used when accessing raw user input from a form directly, the latter when accepting unknown variables. In this instance, even though you will probably get these values from a form, you will use the latter because your method only sees it as a variable and doesn't know for sure where it comes from.</p>\n\n<pre><code>if( filter_var( $username, FILTER_SANITIZE_STRING ) === $username ) {\n $this->username = $username;\n}\nif( filter_var( $email, FILTER_VALIDATE_EMAIL ) ) {\n $this->email = $email;\n}\n</code></pre>\n\n<p>You might want to consider adding whitespace for legibility on lines that are too long. The rule of thumb here is 80 characters, including indentation. Both PHP and SQL are very lax when it comes to whitespace, so don't be afraid to use it.</p>\n\n<pre><code>$db->simplequery( \"\n INSERT INTO radio_users( \n id,\n username,\n password,\n email\n ) VALUES (\n '',\n '$this->username',\n '$this->password',\n '$this->email'\n )\n\" );\n</code></pre>\n\n<p>Now, as to how you can incorporate your <code>$db</code> class into your <code>accountactions</code> class. The easiest, and best, way is to inject it. This can either be done during construction, or via some sort of setter. I'm going to assume that your database model is still MySQL because I can't find anything to contradict it, so I'll use that to type hint it. By the way, you should really upgrade your MySQL to MySQLi or PDO and take advantage of their prepared statements if you haven't already done so.</p>\n\n<pre><code>public function __construct( MySQL $db ) {\n $this->db = $db;\n}\n\n/** or as a setter */\npublic function setDb( MySQL $db ) {\n $this->db = $db;\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T20:44:29.703",
"Id": "19980",
"ParentId": "19976",
"Score": "5"
}
},
{
"body": "<p>Several problems that you should be aware of:</p>\n\n<ol>\n<li>You are using the soon to be <a href=\"http://php.net/manual/en/intro.mysql.php\" rel=\"nofollow noreferrer\">deprecated mysql functions</a>. Instead, use <a href=\"http://php.net/manual/en/book.mysqli.php\" rel=\"nofollow noreferrer\">mysqli</a> or <a href=\"http://php.net/manual/en/book.pdo.php\" rel=\"nofollow noreferrer\">pdo</a>.</li>\n<li>You aren't <a href=\"https://stackoverflow.com/a/12870972/231774\">salting your passwords</a>.</li>\n<li>You should not use md5 for password+salt encryption. Use sha-512 or 256.</li>\n<li>You have no error handling.</li>\n</ol>\n\n<p>I can not stress the first three problems enough. I would also question the wisdom of storing user credentials at all. You might consider using something like <a href=\"http://openid.net/\" rel=\"nofollow noreferrer\">openid</a>.</p>\n\n<p>Now for some general observations:</p>\n\n<p>Consider a camel case naming convention for classes. These are easier to read. e.g. AccountActions instead of accountactions. I also think it's a good idea to use namespaces (if you are using php 5.3 or higher). Put each class in separate file and use a <a href=\"https://gist.github.com/221634\" rel=\"nofollow noreferrer\">PSR-0 classloader</a>.</p>\n\n<p>You get alot more benefit from OOP if you have interaction between re-usable objects. When starting out, it's tempting to take code and simply dump it into some kind of god class. Consider how these classes work together and how the User class is re-usable.</p>\n\n<pre><code><?php\nclass User\n{\n private $name;\n private $email;\n private $password;\n private $salt;\n\n //assume there are methods set/getName, etc\n\n /*\n * @param string $clearPassword\n */\n public function setPasword($clearPassword)\n {\n $this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);\n $this->password = crypt($clearPassword, $this->salt);\n }\n}\n\nclass Registrar\n{\n private $pdo;\n\n public function __construct(PDO $pdo)\n {\n $this->pdo = $pdo;\n }\n\n /*\n * @param User $user\n * @throws RegistrarException\n */\n public function registerUser(User $user)\n {\n //todo: All values should be possibly \n //filtered and certainly validated\n\n try {\n $sql = \"INSERT INTO users set name=?, email=?, pass=?, salt=?\";\n $stmt = $this->pdo->prepare($sql);\n $stmt->execute(array(\n $user->getName(),\n $user->getEmail(),\n $user->getPassword(),\n $user->getSalt()\n ));\n } catch (PDOException $e) {\n throw new RegistrarException('insert error', null, $e);\n }\n }\n}\n\nclass RegistrarException extends Exception {}\n</code></pre>\n\n<p>Then we use it this way:</p>\n\n<pre><code><?php\n$user = new User();\n$user->setName($_POST['name']);\n$user->setEmail($_POST['email']);\n$user->setPassword($_POST['password']);\n\ntry {\n $pdo = new PDO($dsn, $dbuser, $dbpass); //get values from a config\n $registrar = new Registrar($pdo);\n $registrar->registerUser($user);\n} catch (Exception $e) {\n //handle the exception accordingly. i.e. log it and display error page\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T01:34:48.787",
"Id": "31944",
"Score": "1",
"body": "Not everyone has the newest version of PHP to play with, so namespaces may not be available to them. When suggesting a newish feature you should note what version is required, in this case 5.3.0. Otherwise these are some good points."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T18:46:34.217",
"Id": "32163",
"Score": "1",
"body": "PHP 5.3.0 isn't really that new. In fact, when I run PEAR commands with PHP 5.3.0 I get a message warning me that my version of PHP is old and that I should upgrade. So if someone is using PHP < 5.3 there is even more reason to consider upgrading. That said, for people how really can't use namespaces, a PSR-0 classloader will still work for you. I would recommend looking at [the spec](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md) for more information."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T01:07:05.043",
"Id": "19983",
"ParentId": "19976",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T18:34:45.813",
"Id": "19976",
"Score": "4",
"Tags": [
"php",
"object-oriented",
"sql"
],
"Title": "A method to insert a database entry for a newly registered account"
}
|
19976
|
<p>I wrote this perl script that analizes a text and plot out a bar graph of the word occurrences during the text.</p>
<p>Since come mainly from Javascript and PHP, i would like to know how bad is this code and if there is room for improvement and how, any tip will be appreciated! </p>
<p>Thanks!</p>
<pre><code>#!usr/bin/perl -w
use strict;
use warnings;
use GD::Graph::bars;
use GD::Graph::colour;
if (!$ARGV[0]) {
die "Error:\nPlease supply a txt file and a database of words to exclude\n";
}
my $file = $ARGV[0];
my $dbfile = $ARGV[1];
my $cnt = 0;
my %wordlist = ();
my @db = ();
my $threshold = 18;
binmode STDOUT,"utf8";
open (HNDL,'<:utf8', $file) || die "wrong filename";
if ($dbfile){
open (HDB,'<:utf8', $dbfile) || die "wrong filename";
@db = <HDB>; # load file into array
foreach my $db (@db) {
# remove newlines
#$db =~ s/\n\s*//;
chomp($db);
}
}
while (my $val = <HNDL>)
{
my @val = split / /, $val; # split each space build words array
foreach my $word (@val){
# clean the word remove newlines
#$word =~ s/\n\s*//;
chomp($word);
# clean the word remove everything until '
$word =~ s/^.\'//;
# clean the word remove any nonword characters
# $word =~ s/[^a-zA-Z_0-9]//;
# clean the word remove dots and commas
$word =~ s/,|\.//;
if (length($word) < 2){
next;
};
# check if the word is to be excluded
my $exclude = 0;
if ($dbfile){
foreach my $dbword (@db) {
# check if the string contains dbword
# ^ check for occurence at start
# $ check for occurence at end
# /i case insensitive
if ($word =~ m/^$dbword$/i){
$exclude = 1;
#print "Escluso: $word";
}
}
}
if($exclude == 0) {
# check word in the hash
if (exists $wordlist{$word}) {
#if present augment value by one
$wordlist{$word}++;
}else{
#if not present add
$wordlist{$word} = 1;
}
}else{
# do nothing
}
}
}
# Export CSV
# Print header
print ("Word,Value\n");
# print hash elements for each sorted element
for my $key ( sort { $wordlist{$a} <=> $wordlist{$b} } keys %wordlist){
#print "$key ---> $wordlist{$key}\n\n";
if ($wordlist{$key} >= $threshold){
print "$key,$wordlist{$key}\n";
}
}
# Export Graph
my $graph = GD::Graph::bars->new(1024, 600);
# Build data arrays
my @xdata = ();
my @ydata = ();
my @data = ();
for my $key ( sort { $wordlist{$a} <=> $wordlist{$b} } keys %wordlist){
#print "$key ---> $wordlist{$key}\n\n";
if ($wordlist{$key} >= $threshold){
push(@xdata,$key);
push(@ydata,$wordlist{$key});
}
}
push (@data,\@xdata);
push (@data,\@ydata);
$graph->set(
x_label => 'Words',
x_label_position => '0.5',
y_label => 'Number of Hits',
title => 'Number of Hits for Each Word',
bar_spacing => 5,
bar_width => 25,
transparent => '0',
bgclr => 'white'
) or warn $graph->error;
my $image = $graph->plot(\@data) or die $graph->error;
# write file to output
$file =~ s/\.[*]$//;
open(PNGOUT,">","$file.png");
binmode PNGOUT;
print PNGOUT $image->png;
close(PNGOUT);
close (HDB);
close (HNDL);
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Use lexical filehandles instead of typeglobs (read <a href=\"https://stackoverflow.com/questions/1479741/why-is-three-argument-open-calls-with-autovivified-filehandles-a-perl-best-pract\">here</a> for more about why; the biggest problem with typeglobs is that they are global in scope).</p>\n\n<pre><code>open (my $handle,'<:utf8', $file) || die \"wrong filename\";\n</code></pre></li>\n<li><p>You should close your filehandles sooner rather than waiting til the end of the program, if possible. For example, there's no reason to keep <code>HDB</code> open after its contents have been read into memory.</p></li>\n<li><p>Consider changing <code>@db</code> to a hash, then using <code>exists</code> to check whether a word is in the exclude list. This should be faster than looping through the array (depending on how many words are in the exclude list and how often a word will be in the list). Since case is not important, you could call <code>lc</code> or <code>uc</code> before testing.</p>\n\n<p>If you want to keep it as an array, then consider exiting the loop using <code>last</code> once the first match is found.</p></li>\n<li><p>You sort the keys of <code>%wordlist</code> twice using the same criteria. Consider storing the sorted list in a new variable.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T01:32:02.993",
"Id": "19985",
"ParentId": "19977",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "19985",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T19:20:07.507",
"Id": "19977",
"Score": "2",
"Tags": [
"perl"
],
"Title": "Perl project review - Word counter"
}
|
19977
|
<p>For a project I need to give a load of diverseinformation in JSON format. All the information will be used on the same page so a single call would result in the least overhead. The information all concerns the same database object and is all nescessary on the page. It basically is a collection of counts of the amount of objects that are of one or more of a certain type (the types are all booleans) and we require to know a lot of different variations of this. I used the code below but my co-worker believes the way I put it in the JSON list is a bit clunky and the code could be far more performant. How could I improve this code?</p>
<pre><code>public function getContactsStatisticsAction()
{
$response = new Response();
$json = array();
$em = $this->getDoctrine()->getEntityManager();
$cr = $em->getRepository('BlaCoreBundle:Company');
$json['numberOfCompanies'] = $cr->numberOfCompanies();
$json['numberOfAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true));
$json['numberOfCompetitors'] = $cr->numberOfCompanies(array("typeCompetitor" => true));
$json['numberOfSuppliers'] = $cr->numberOfCompanies(array("typeSupplier" => true));
$json['numberOfOthers'] = $cr->numberOfCompanies(array("typeOther" => true));
$json['numberOfUnassigned'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => false,"typeSupplier" => false,"typeOther" => false));
$json['numberOfJustAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => false, "typeSupplier" => false));
$json['numberOfJustCompetitors'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => false, "typeSupplier" => false));
$json['numberOfJustSuppliers'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => false, "typeSupplier" => false));
$json['numberOfCompetitorAndAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => true, "typeSupplier" => false));
$json['numberOfCompetitorAndSuppliers'] = $cr->numberOfCompanies(array("typeAccount" => false, "typeCompetitor" => true, "typeSupplier" => true));
$json['numberOfSupplierAndAccounts'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => false, "typeSupplier" => true));
$json['numberOfCompaniesAndAccountsAndSuppliers'] = $cr->numberOfCompanies(array("typeAccount" => true, "typeCompetitor" => true, "typeSupplier" => true));
$response->setContent(json_encode($json));
return $response;
}
public function numberOfCompanies($filters = array())
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('count(c.id)');
$qb->from('BlaCoreBundle:Company', 'c');
$sizeFilters = count ($filters);
$keys = array_keys($filters);
if($sizeFilters >= 1){
$qb->where('c.' . $keys[0] . ' = ' . (int) $filters[$keys[0]]);
}
for($i = 1; $i < $sizeFilters; $i++){
$qb->andWhere('c.' . $keys[$i] . ' = ' . (int) $filters[$keys[$i]]);
}
return $qb->getQuery()->getSingleScalarResult();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T01:33:13.013",
"Id": "31982",
"Score": "1",
"body": "what specific parts are you (or your co-worker) concerned about? The response data structure? The number of queries being issued? other?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T22:51:52.803",
"Id": "32002",
"Score": "1",
"body": "Those two, really. The fact that the response data structure is quite large and the amount of queries that has to be run."
}
] |
[
{
"body": "<p>I think that what you have is probably fine. Personally, I'd move the construction of the result array to a view but this is not that big of a deal. That might help with the \"clunkiness\".</p>\n\n<p>With regards to your concern about the size of the json response: You say that all of the information in it is needed by the app. It doesn't look all that big to me. Unless you are actually experiencing problems as a result of the size, I'd leave it alone. If it were too big, you could consider implementing appropriate caching (allow the browser to cache the results and/or use etags) or pagination.</p>\n\n<p>Regarding the number of individual sql calls: I'm sure you could put it all into one query if need be.</p>\n\n<p>Both of these potential issues, response size and number of queries, seem to me to be pre-optimization concerns. In the past, I've spent lots of time pre-optimizing stuff and never realized any <em>real</em> gain. Now, I implement what is needed and only optimize when the <em>real</em> need arises. The bottom line: I don't see any problems with what you've got and unless the result is unacceptably slow or resource intensive, don't worry about it.</p>\n\n<p>Hope it helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T15:26:20.913",
"Id": "32023",
"Score": "1",
"body": "Great, thanks for the answer! It definitely helps. Any idea how a single query would work for something like this though? Since it are different counts..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T15:41:17.577",
"Id": "32024",
"Score": "1",
"body": "You might be able to use a series of sum() functions. Or simply use [sub-selects](http://stackoverflow.com/a/1775272/231774)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T04:11:18.553",
"Id": "20038",
"ParentId": "19981",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20038",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-27T22:06:51.010",
"Id": "19981",
"Score": "2",
"Tags": [
"php",
"ajax",
"json",
"doctrine"
],
"Title": "Passing a large amount of diverse information in JSON using Symfony 2.1 and Doctrine 2"
}
|
19981
|
<p>I am trying to implement Boyer Moore Algorithm for text searching and have come up with this implementation:</p>
<pre><code>public class BoyerMooreStringSearching
{
readonly Dictionary<char, LastIndexTable> _lastIndexTable = new Dictionary<char, LastIndexTable>();
public string PatternToSearch;
public List<int> GetStartingIndexsOfPatternInText(string textToSearchIn, string patternToSearch)
{
var list = new List<int>();
PatternToSearch = patternToSearch;
if (patternToSearch != null && !string.IsNullOrEmpty(textToSearchIn))
{
// Update Last Index Table
UpdateLastIndexTable(patternToSearch);
PatternToSearch = patternToSearch;
var j = patternToSearch.Length - 1;
// Main loop to iterate over whole text
while (j <= textToSearchIn.Length - 1)
{
var lastCharOfPattern = patternToSearch[patternToSearch.Length - 1];
if (textToSearchIn[j] != lastCharOfPattern)
{
// Heuristic 1
// If Last Char is not matched with the Last char in pattern and char is not present in the pattern
// Then advance pointer 'j' to the length of the pattern in textToSearch.
if (!_lastIndexTable.ContainsKey(textToSearchIn[j]))
{
j += patternToSearch.Length - 1;
}
// Heuristic 2
// Consult the lastIndex table to get the last index of current char in textToSearch
// and advance pointer 'j' to the last index in textToSearch.
if (j <= textToSearchIn.Length - 1 && _lastIndexTable.ContainsKey(textToSearchIn[j]))
{
var tempObj = _lastIndexTable[textToSearchIn[j]];
if (tempObj != null) j += tempObj.LastIndex;
}
}
int k = patternToSearch.Length - 1;
int u = j;
if (j <= textToSearchIn.Length - 1)
{
while (k >= 0)
{
// Heuristic (3a)
// If Last Char is matched with the Last char in pattern then back track in the text and pattern till
// either you got a complete match or a mismatched charecter.
// Once you got the mismatched char and mismatched char is not present in the pattern then
// advance j to the index of mismatched charecter in the pattern
if (textToSearchIn[u] == patternToSearch[k])
{
if (k == 0 && textToSearchIn[u] == patternToSearch[k])
{
list.Add(u);
j += patternToSearch.Length - 1;
}
u--;
k--;
continue;
}
if (!_lastIndexTable.ContainsKey(textToSearchIn[u]))
{
// Heuristic (3b)
// If Last Char is matched with the Last char in pattern then back track in the text till
// either you got a complete match or a mismatched charecter.
// Once you got the mismatched char and mismatched char is not present in the pattern then
// advance j to the index of mismatched charecter in the pattern plus the number to char which matched.
j += k + (j - u);
break;
}
k--;
}
}
j++;
}
}
if (!list.Any())
list.Add(-1);
return list;
}
private void UpdateLastIndexTable(string patternToSearch)
{
_lastIndexTable.Clear();
var i = patternToSearch.Length - 1;
foreach (var charToSeach in patternToSearch)
{
if (_lastIndexTable.ContainsKey(charToSeach))
{
_lastIndexTable[charToSeach].LastIndex = i;
}
else
{
_lastIndexTable.Add(charToSeach, new LastIndexTable
{
CharSearched = charToSeach,
LastIndex = i
});
}
i--;
}
}
}
public class LastIndexTable
{
public char CharSearched { get; set; }
public int LastIndex { get; set; }
}
</code></pre>
<p>Please can you review and provide feedback?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T22:02:31.597",
"Id": "31969",
"Score": "1",
"body": "The standard way to deal with indices is `v < element.Length`, which is mostly to help prevent off-by-one (fencepost) errors. Dijkstra has [some notes on this](http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html)."
}
] |
[
{
"body": "<p>I have checked your code and there are some things which I would change:</p>\n\n<ul>\n<li>Create an interface, say, <code>IStringSearcher</code> with one method <code>List<int> GetStartingIndexsOfPatternInText(string textToSearchIn, string patternToSearch)</code>. That will help you to change string searching algorithm implementation without client code changes.</li>\n<li><code>GetStartingIndexsOfPatternInText</code> method name seems to be a bit long and personally I would change the name.</li>\n<li>I would either make <code>BoyerMooreStringSearching</code> class as <strong>read-only</strong> or <strong>utility</strong> class. That change will be very beneficial if you think about multi-thread applications.\n<ul>\n<li><strong>read-only</strong> - <code>text to search</code> and <code>pattern to search</code> would be provided in the class constructor and could not be changed</li>\n<li><em>OR</em> <strong>utility class</strong>. In that case <code>BoyerMooreStringSearching</code> class and <code>GetStartingIndexsOfPatternInText</code> method would be static.</li>\n</ul></li>\n<li>I would throw some exception if provided strings do not meet your requirements (you should document your requirements in the class documentation) e.g. \n<ul>\n<li>if one of the strings is null or empty or </li>\n<li>if <code>pattern string</code> is longer than <code>text to search</code></li>\n</ul></li>\n<li><code>PatternToSearch = patternToSearch;</code> statement is used twice in your code: one before and another after the first <code>if</code> statement.</li>\n<li><code>public string PatternToSearch;</code> I do not think it needs to be there as you do not read it.</li>\n<li>I see that you use lots of variables like <code>k</code>, <code>u</code>, <code>j</code> etc. I think you should use more meaningful names. After couple of months the code will be more readable for you when you forgot what you had written. </li>\n</ul>\n\n<p>I hope that will help.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T20:14:40.560",
"Id": "20006",
"ParentId": "19988",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T07:03:00.807",
"Id": "19988",
"Score": "2",
"Tags": [
"c#",
"algorithm"
],
"Title": "Boyer Moore Implementation"
}
|
19988
|
<blockquote>
<p>Given an input string, write a function that returns the Run Length
Encoded string for the input string.</p>
<p>For example, if the input string is “wwwwaaadexxxxxx”, then the
function should return “w4a3d1e1x6″.</p>
</blockquote>
<p>The following is my implementation:</p>
<pre><code>string length_encoding(const string& s)
{
char c = ' ';
int num = 0;
string result;
string::const_iterator it = s.begin();
for(; it != s.end(); ++it)
{
if(*it!=c)
{
if(num!=0)
{
stringstream ss;
ss << num;
string num_s(ss.str());
result += num_s;
}
c = *it;
result.push_back(c);
num = 1;
}
else
{
num++;
}
}
stringstream ss;
ss << num;
string num_s(ss.str());
result += num_s;
return result;
}
</code></pre>
|
[] |
[
{
"body": "<p>I'm not a C++ guru, but for what they are worth, I have some comments:</p>\n\n<ul>\n<li>it would be better to evaluate s.end() just once (outside the loop). Correction: this won't help.</li>\n<li>the function fails if <code>s</code> starts with a space</li>\n<li><p>you have duplicate code turning an int into a string. Perhaps use C++11 <code>to_string</code> or write your own a function, such as:</p>\n\n<pre><code>template <typename T>\nstatic std::string to_string(T num)\n{\n std::stringstream ss;\n ss << num;\n return ss.str();\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T22:39:48.893",
"Id": "31973",
"Score": "0",
"body": "Calling s.end() only once will not help anything. Most implementations already cache the value so that there is no cost to multiple calls. This is also a bad idea as it makes the code hard to read (as it is not what you expect)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T00:50:37.107",
"Id": "31981",
"Score": "0",
"body": "Ah, ok. I'm learning C++ (so arguably I shouldn't be commenting on others' code) and have seen this suggestion around so I took it to be true. Thanks for the correction :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T18:25:37.197",
"Id": "20003",
"ParentId": "19990",
"Score": "1"
}
},
{
"body": "<p>There is a bug. If your input string begins with a space then you don't prefix the number with a space.</p>\n\n<pre><code>Input: \" AAAA\"\nOutput: \"4A4\"\nExpected Output: \" 4A4\"\n</code></pre>\n\n<p>This is easily fixed by outputting the character and count at the same time.</p>\n\n<p>Problems: Magic values</p>\n\n<pre><code>char c = ' ';\n</code></pre>\n\n<p>Magic values cause all sorts of problems you should really use a value that can never be a character. In this case convert to an int and make it -1</p>\n\n<pre><code>int c = -1; // This is guaranteed to be a value that will never be a character.\n</code></pre>\n\n<p>Use the ability to declare variables inside the <code>for(;;)</code> statement unless you really need the iterator after the loop.</p>\n\n<pre><code>string::const_iterator it = s.begin();\nfor(; it != s.end(); ++it)\n\n// easier to write and read as:\n\nfor(string::const_iterator it = s.begin(); it != s.end(); ++it) \n{\n // Also because `it` is scopped is does not pollute the\n // code with a variable that is not used after the loop.\n}\n</code></pre>\n\n<p>This piece of code:</p>\n\n<pre><code> stringstream ss;\n ss << num;\n string num_s(ss.str());\n result += num_s;\n</code></pre>\n\n<p>Is repeated in two places. Refactor it into its own function.<br>\nYou will also find that such a function already exists in boost <code>std::lexical_cast</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T18:27:49.730",
"Id": "20004",
"ParentId": "19990",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "20004",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T09:52:11.120",
"Id": "19990",
"Score": "3",
"Tags": [
"c++",
"strings",
"interview-questions",
"compression"
],
"Title": "Run Length Encoding"
}
|
19990
|
<p>I have this method that will give a random prime for a given range (min inclusive an max not inclusive) all comments are welcome:</p>
<pre><code>public static int randomPrime(int min, int max) {
if (min < 0)
throw new IllegalArgumentException("min must be positive.");
if (min >= max)
throw new IllegalArgumentException("min must be smaller the max.");
if (!containsPrime(min,max))
throw new IllegalArgumentException("no Primes in this interval.");
if (rand == null) {
rand = new Random();
}
int out = rand.nextInt(max - min) + min;
while (!isPrime(out)) {
out = rand.nextInt(max - min) + min;
}
return out;
}
private static boolean containsPrime(int min, int max) {
if (isPrime(min)||isPrime(max-1)){
return true;
}
if(min%2==0){
min +=1;
}
while (min<max){
if (isPrime(min)){
return true;
}
min +=2;
}
return false;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T14:51:36.520",
"Id": "31951",
"Score": "0",
"body": "Would you like to share your `isPrime` method as well?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T22:21:12.157",
"Id": "31972",
"Score": "0",
"body": "If this is for cryptography purposes (where random prime numbers are used a lot), you may want to have your random number generator be injectable (`Random` may not be good enough). You're vulnerable to integer overflow; depending on the starting values of `min`/`max` (and the implementation of `isPrime()`), you could spin through all negative numbers. There's probably at least one additional optimization for the prime range-check, something about 3 prime numbers every 100 or something (I can't remember exactly what it was, though)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T23:28:09.907",
"Id": "31976",
"Score": "0",
"body": "@Clockwork-Muse I think you missed my input validation, the code is pure for statistics, no worries about Random i am using a specialised version there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T00:17:58.467",
"Id": "31980",
"Score": "1",
"body": "Argh, I forgot that `Integer.MAX_VALUE` is odd - if it were even, you would be. Other things - the even/odd check can be performed first, before the initial check for primeness of min/max. Move `min += 2;` above the prime check in the `while (min < max)` loop - you check the 'initial' min value twice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T13:07:40.580",
"Id": "31993",
"Score": "0",
"body": "@Clockwork-Muse Integer.MAX_VALUE = 2147483647, is not just odd... it's a prime"
}
] |
[
{
"body": "<pre><code>int out = rand.nextInt(max - min) + min;\nwhile (!isPrime(out)) {\n out = rand.nextInt(max - min) + min;\n}\nreturn out;\n</code></pre>\n\n<p>This duplicate code can be replaced with a do/while loop. The rule of thumb is, if you always need to perform an action at least once, do while!</p>\n\n<pre><code>int out;\ndo {\n out = rand.nextInt(max - min) + min;\n} while(!isPrime(out));\nreturn out;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T15:39:17.100",
"Id": "19995",
"ParentId": "19993",
"Score": "4"
}
},
{
"body": "<p>First of all, use some white space. The scrunched expressions are harder to read. At a minimum, I recommend spaces around every operator.</p>\n\n<p>In <code>containsPrime</code>, if the variable <code>min</code> is odd, then it gets checked twice. You can replace the second if block with this:</p>\n\n<pre><code>if (min % 2 == 0) min += 1;\nelse min += 2;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T16:28:07.120",
"Id": "31956",
"Score": "1",
"body": "and while we're at it, `min += 1` can and should be `min++`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T20:23:55.973",
"Id": "31963",
"Score": "0",
"body": "That if-else statement can be reduced to a ternary to save a line: `min += (min % 2 == 0) ? 1 : 2;`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T21:42:37.233",
"Id": "31968",
"Score": "0",
"body": "I am not a fan of ternary's so i'll stick to the suggestion of Donald on this one, but Thx,to both of you for the constructive feedback."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T16:03:48.747",
"Id": "19996",
"ParentId": "19993",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "19996",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T12:36:11.123",
"Id": "19993",
"Score": "3",
"Tags": [
"java",
"primes"
],
"Title": "Random Prime generator"
}
|
19993
|
<p>I have written some code which will fetch contents from a resource which is actually stored in a tree format. Since it is in a tree format, there will be a parent-child relation and hence recursion.</p>
<p>I am facing lot of performance issue as tree is growing in size this particular piece of code takes up-to 25 sec which is very bad. This piece of code will basically read data stored in file system (just for example) each content has certain set of property which it has to read.</p>
<pre><code>import java.util.List;
public class Links {
private String nodeName;
private List<Links> children;
public List<Links> getChildren() {
return children;
}
public void setChildren( List<Links> children ) {
this.children = children;
}
public String getNodeName(){
return nodeName;
}
public void setNodeName( String nodeName ){
this.nodeName = nodeName;
}
}
package menu;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Utility {
/*
* IN this class NavModel,CModel,CNode are some dummy classes which help us read contents form some resources which
* are stored in dummy format as Example of tree format stored data below is the example tree child1 child2 child3
* child3-1 child:q child:r child:a child3-2 child4
*/
private static void populateLinks( NavModel navModel,
ContentModel metaDataModel, Object objectNode, Links parent,
boolean specialLinks ) throws IOException{
try{
List<Links> childLinks = new ArrayList<Links>();
// below code gets all the childrens of parent
Iterator it = navModel.getChildren( objectNode );
while( it.hasNext() ){
NavNode node = (NavNode) it.next();
ContentNode contentNode = node.getContentNode();
Links links = new Links();
MetaData data = metaDataModel.getMetaData( contentNode );
Map<String, String> paramValues = new HashMap<String, String>();
// this particular piece of
// code gets all the properties of content iterates and stores it in data structure
Iterator metaDataIterator = data.getNames().iterator();
while( metaDataIterator.hasNext() ){
String pagePropertyKey = metaDataIterator.next().toString();
String pagePropertyValue = (String) data
.getValue( pagePropertyKey );
if( pagePropertyKey.equalsIgnoreCase( "LINK_TYPE" ) ){
links.setLinkType( pagePropertyValue );
}
else if( pagePropertyKey.equalsIgnoreCase( "TCDID" ) ){
links.setTcmIdMap( pagePropertyValue );
}
else{
paramValues.put( pagePropertyKey, pagePropertyValue );
}
}
links.setParamValues( paramValues );
if( specialLinks ){
links.setNodeName( links.getParamValues().get(
"APPLICATIONNAME" ) );
}
else{
links.setNodeName( contentNode.getTitle( new Locale(
"en_US" ) ) );
}
links.setDisplayName( setAppDispName( links.getNodeName() ) );
childLinks.add( links );
if( navModel.hasChildren( node ) ){
// This is where recursion happens
populateLinks( navModel, metaDataModel, node, links,
specialLinks );
}
}
parent.setChildren( childLinks );
}
catch( Exception e ){
}
}
// THis is the method which calls the recursion function
public static Links setupLinks( String categoryLinkName, String name ){
Links categoryLinks = null;
CModel contentModel = new CModel();
NavModel navModel = new NavModel();
categoryLinks = Utility.createCategoryLinks( categoryLinkName );
Object objectNode = contentModel.getLocator().findByUniqueName( name );
if( objectNode != null ){
if( navModel.hasChildren( objectNode ) ){
populateLinks( navModel, objectNode, categoryLinks );
}
}
}
private static Object setAppDispName( String nodeName ){
// fetch value from db
return null;
}
}
</code></pre>
<p>I know code is not complete and may be in appropriate to review but I can't paste the whole of my code hence I hope you understand and review there is recursion and iteration any way I can better write this piece of code.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T14:54:26.287",
"Id": "31952",
"Score": "0",
"body": ":I think, this must belong to the StackOverflow"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T15:58:08.790",
"Id": "31955",
"Score": "0",
"body": "@Saurabh: No, improvements to working code fall under code review's domain"
}
] |
[
{
"body": "<pre><code>Iterator it = navModel.getChildren( objectNode );\nwhile( it.hasNext() ){\n NavNode node = (NavNode) it.next();\n</code></pre>\n\n<p><code>java.util.Iterator</code> has an extending class, which if you use, you don't have to manally cast back after calling <code>.next()</code>, as follows:</p>\n\n<pre><code>Iterator<NavNode> it = navModel.getChildren( objectNode );\nwhile( it.hasNext() ){\n NavNode node = it.next();\n</code></pre>\n\n<p>Furthermore, if you are using Java 7 or above, you no longer have to specify the extending type in the assignment if you use the \"diamond operand\", as in these lines:</p>\n\n<p><code>Map<String, String> paramValues = new HashMap<>();</code></p>\n\n<p><code>List<Links> childLinks = new ArrayList<>();</code></p>\n\n<p>Additionally, you are calling <code>.equalsIgnoreCase()</code> (See <code>java.lang.String</code> <a href=\"http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java#String.equalsIgnoreCase%28java.lang.String%29\" rel=\"nofollow\">source code</a>) multiple times in an if-else statement, which internally calls <code>.toUpperCase()</code> on the String, which can happen twice in a worst case scenario of your code, therefore I believe this would be more efficient:</p>\n\n<pre><code>pagePropertyKey = pagePropertyKey.toUpperCase();\nswitch(pagePropertyKey)\n{\n case \"LINK_TYPE\": links.setLinkType( pagePropertyValue );\n break;\n case \"TCDID\": links.setTcmIdMap( pagePropertyValue );\n break;\n default: paramValues.put( pagePropertyKey, pagePropertyValue );\n break;\n}\n</code></pre>\n\n<p>As then it only has to call <code>.toUpperCase()</code> once and then <code>equals()</code> alone which is more efficient.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T10:11:34.873",
"Id": "32045",
"Score": "0",
"body": "thank you, however is there any other way i can optimize this code"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T21:07:38.210",
"Id": "20007",
"ParentId": "19994",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T12:50:15.027",
"Id": "19994",
"Score": "3",
"Tags": [
"java",
"optimization",
"recursion"
],
"Title": "Recursion and iteration how can i optimize this code"
}
|
19994
|
<p>I'm working on a 3 columns photo website (responsive), and I'm parsing the <code>img src</code> from XML. I need to prepend HTML code every 3 elements so my photo wall respects my responsive class.</p>
<p>I just found a cheap solution, repeating the XML loop (<code>for</code>). Do you have an advice to give me, to do it right, to improve my code?</p>
<pre><code>$(document).ready(function(){
xmldata=new Array(); //initialise array for XML data
$.ajax({ //get the XML data
url: "xml/gallery.xml", //URL to get the data from
success: function(data) { //if we succeed, set everything up. We don't expect failure.
$(data).find("image").each(function()
{
xmldata.push($(this)); //add item into array
});
totalNum = xmldata.length;
gallery_images();
}
});
});
function gallery_images(){
for (var i = 0; i <= 2; i++) {
data=xmldata[i];
img_src=$(data).attr("src");
href=$(data).attr("href");
title1=$(data).attr("title1");
client=$(data).attr("client");
var video_gallery_html = '';
video_gallery_html += '<article class="col span_8"><div class="title_div span_24 ">';
video_gallery_html += ' <a href="#"> <img src="images/linea.png" alt="line_divisor" /></a>';
video_gallery_html += ' <h1 class="title_item col span_12 _left">DENIS ROVIRA</h1>';
video_gallery_html += ' <h3 class="title_more col span_12 _right">See all projects</h3></div><!-- title_div -->';
video_gallery_html += ' <a href="#"> <img src="'+ img_src +'" alt="image_item" /></a>';
video_gallery_html += ' <p>Nescafe Gold</p></article><!-- span_8 -->';
$(".videos_container").prepend(video_gallery_html);
};
for (var i = 3; i <= 5; i++) {
data=xmldata[i];
img_src=$(data).attr("src");
href=$(data).attr("href");
title1=$(data).attr("title1");
client=$(data).attr("client");
var video_gallery_html2 = '';
video_gallery_html2 += '<article class="col span_8"><div class="title_div span_24 ">';
video_gallery_html2 += ' <a href="#"> <img src="images/linea.png" alt="line_divisor" /></a>';
video_gallery_html2 += ' <h1 class="title_item col span_12 _left">DENIS ROVIRA</h1>';
video_gallery_html2 += ' <h3 class="title_more col span_12 _right">See all projects</h3></div><!-- title_div -->';
video_gallery_html2 += ' <a href="#"> <img src="'+ img_src +'" alt="image_item" /></a>';
video_gallery_html2 += ' <p>Nescafe Gold</p></article><!-- span_8 -->';
$(".videos_container2").prepend(video_gallery_html2);
};
}
</code></pre>
|
[] |
[
{
"body": "<p>Perhaps using a template system can help you, check <a href=\"http://handlebarsjs.com/\" rel=\"nofollow\">http://handlebarsjs.com/</a> you can integrate with jquery and reuse partial html code as a templates</p>\n\n<pre><code><script id=\"entry-template\" type=\"text/x-handlebars-template\">\n<div class=\"entry\">\n <h1>{{title}}</h1>\n <div class=\"body\">\n {{{body}}}\n </div>\n</div>\n</script>\n\n<script type=\"text/javascript\" charset=\"utf-8\">\n// Compiling template to generate function\nvar source = $(\"#entry-template\").html();\nvar template = Handlebars.compile(source);\n\n// When you receive your data content var just call this:\nvar context = {title: \"My New Post\", body: \"This is my first post!\"};\n// in your case maybe it is:\n// var context = { img_src: $(data).attr(\"src\"), href=$(data).attr(\"href\"), title1: $(data).attr(\"title1\"), client : $(data).attr(\"client\") };\nvar html = template(context);\n\n</script>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T17:58:13.977",
"Id": "20067",
"ParentId": "20001",
"Score": "1"
}
},
{
"body": "<p>First, you should avoid global variables. There is almost always other ways to use variables without making them global. Also, keep in mind that any variable that you do not declare with var is considered global.</p>\n\n<p>Your code within the loops are almost exactly the same. Copy that into a function and call the function. </p>\n\n<pre><code>$(document).ready(function(){\n var xmldata=new Array(); //initialise array for XML data\n $.ajax({ //get the XML data\n url: \"xml/gallery.xml\", //URL to get the data from\n success: function(data) { \n $(data).find(\"image\").each(function() {\n xmldata.push($(this)); //add item into array\n });\n\n gallery_images(xmldata); \n } \n }); \n});\n\nfunction addImage(data, container) {\n\n var img_src=$(data).attr(\"src\"), \n href=$(data).attr(\"href\"),\n title1=$(data).attr(\"title1\"),\n client=$(data).attr(\"client\"); // note that I am initializing all variables here.\n\n var video_gallery_html = '';\n video_gallery_html += '<article class=\"col span_8\"><div class=\"title_div span_24 \">';\n video_gallery_html += ' <a href=\"#\"> <img src=\"images/linea.png\" alt=\"line_divisor\" /></a>';\n video_gallery_html += ' <h1 class=\"title_item col span_12 _left\">DENIS ROVIRA</h1>';\n video_gallery_html += ' <h3 class=\"title_more col span_12 _right\">See all projects</h3></div><!-- title_div -->';\n video_gallery_html += ' <a href=\"#\"> <img src=\"'+ img_src +'\" alt=\"image_item\" /></a>';\n video_gallery_html += ' <p>Nescafe Gold</p></article><!-- span_8 -->';\n\n\n $(container).prepend(video_gallery_html);\n}\n\nfunction gallery_images(xmldata){\n\n for (var i = 0; i <= 2; i++) {\n addImage(xmldata[i], '.videos_container')\n }\n\n\n for (var i = 3; i <= 5; i++) {\n addImage(xmldata[i], '.videos_container2'); \n };\n\n}\n</code></pre>\n\n<p>I agree with jcmalpizar's answer in that you will probably find a template engine helpful. You could create the objects directly in the original array and use the objects within the addImage function.</p>\n\n<pre><code>$(data).find(\"image\").each(function() {\n xmldata.push({ img_src: $(this).attr(\"src\"), href: $(this).attr(\"href\"), title1: $(this).attr(\"title1\"), client: $(this).attr(\"client\") }); \n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-30T19:42:59.950",
"Id": "21074",
"ParentId": "20001",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T18:00:34.163",
"Id": "20001",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Parsing XML and prepend HTML every 3 elements"
}
|
20001
|
<p>This is my first time building anything remotely like a robust database. I'm midway through designing it and I would be grateful if you have suggestions or have found any logical errors.</p>
<p><strong>Goal:</strong> allow authenticated users to enter data for multiple hospitals.</p>
<p>My database has three tables: <code>User</code>, <code>Hospital</code>, and <code>Data</code>.</p>
<p>A <code>User</code> might have many <code>Hospital</code>s (and vice-versa). Because of this, I have created a many-to-many scheme. A <code>Hospital</code> might have many <code>Data</code>s so I created a one to many relationship.</p>
<pre><code>from petalapp import db
from datetime import datetime
ROLE_USER = 0
ROLE_ADMIN = 1
#TODO:rename?
hospitals = db.Table('hospitals',
db.Column('hospital_id', db.Integer, db.ForeignKey('hospital.id')),
db.Column('user_id', db.Integer, db.ForeignKey('user.id'))
)
# tags bmarks time
class User(db.Model):
"""User has a many-to-many relationship with Hospital"""
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), unique = True)
email = db.Column(db.String(150), unique=True)
role = db.Column(db.SmallInteger, default=ROLE_USER)
hospitals = db.relationship('Hospital', secondary=hospitals,
backref=db.backref('users', lazy='dynamic'))
def __init__(self, nickname, email, role=ROLE_USER):
self.nickname= nickname
self.role = role
self.email = email
#TODO what information to show?
def __repr__(self):
return '<Name : %r>' % (self.nickname)
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return unicode(self.id)
def add_hospital(self, hospital):
if not (hospital in self.hospitals):
self.hospitals.append(hospital)
def remove_hospital(self, hospital):
if not (hospital in self.hospital):
self.hospitals.remove(hospital)
@staticmethod
def make_unique_nickname(nickname):
if User.query.filter_by(nickname = nickname).first() == None:
return nickname
version = 2
while True:
new_nickname = nickname + str(version)
if User.query.filter_by(nickname = new_nickname).first() == None:
break
version += 1
return new_nickname
class Hospital(db.Model):
"""Hospital's has a one-to-many relationship with DATA and a
many-to-many relationship with User"""
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
data = db.relationship('Data', backref='hospital', lazy = 'dynamic')
def __init__(self, name):
self.name = name
def __repr__(self):
return '<Name %r>' % self.name
class Data(db.Model):
"""Data has a many-to-one relationship with Hospital"""
id = db.Column(db.Integer, primary_key=True)
standard_form = db.Column(db.Integer)
marketing_education = db.Column(db.Integer)
record_availability = db.Column(db.Integer)
family_centerdness = db.Column(db.Integer)
pc_networking = db.Column(db.Integer)
education_and_training = db.Column(db.Integer)
team_funding = db.Column(db.Integer)
coverage = db.Column(db.Integer)
pc_for_expired_pts = db.Column(db.Integer)
hospital_pc_screening = db.Column(db.Integer)
pc_follow_up = db.Column(db.Integer)
post_discharge_services = db.Column(db.Integer)
bereavement_contacts = db.Column(db.Integer)
certification = db.Column(db.Integer)
team_wellness = db.Column(db.Integer)
care_coordination = db.Column(db.Integer)
timestamp = db.Column(db.DateTime)
hospital_id = db.Column(db.Integer, db.ForeignKey('hospital.id'))
def __init__(self, standard_form=0,
marketing_education=0, record_availability=0, family_centerdness=0,
pc_networking=0, education_and_training=0, team_funding=0,
coverage=0, pc_for_expired_pts=0, hospital_pc_screening=0,
pc_follow_up=0, post_discharge_services=0, bereavement_contacts=0,
certification=0, team_wellness=0, care_coordination=0, timestamp=datetime.utcnow()):
self.standard_form = standard_form
self.marketing_education = marketing_education
self.record_availability = record_availability
self.family_centerdness = family_centerdness
self.pc_networking = pc_networking
self.education_and_training = education_and_training
self.team_funding = team_funding
self.coverage = coverage
self.pc_for_expired_pts = pc_for_expired_pts
self.hospital_pc_screening = hospital_pc_screening
self.pc_follow_up = pc_follow_up
self.post_discharge_services = post_discharge_services
self.bereavement_contacts = bereavement_contacts
self.certification = certification
self.team_wellness = team_wellness
self.care_coordination = care_coordination
self.timestamp = timestamp
def __repr__(self):
return """
<standard_form : %r>\n
<marketing_education : %r>\n
<record_availability : %r>\n
<family_centerdness : %r>\n
<pc_networking : %r>\n
<education_and_training : %r>\n
<team_funding : %r>\n
<coverage : %r>\n
<pc_for_expired_pts : %r>\n
<hospital_pc_screening : %r>\n
<pc_follow_up : %r>\n
<post_discharge_services : %r>\n
<bereavement_contacts : %r>\n
<certification : %r>\n
<team_wellness : %r>\n
<care_coordination : %r>\n
<datetime_utc : %r>""" % (
self.standard_form,
self.marketing_education,
self.record_availability,
self.family_centerdness,
self.pc_networking,
self.education_and_training,
self.team_funding,
self.coverage,
self.pc_for_expired_pts,
self.hospital_pc_screening ,
self.pc_follow_up,
self.post_discharge_services,
self.bereavement_contacts,
self.certification,
self.team_wellness,
self.care_coordination,
self.timestamp)
</code></pre>
<hr>
<p>Here are my tests so far:</p>
<pre><code>'''
File: db_test_many_create.py
Date: 2012-12-06
Author: Drew Verlee
Description: functions to build a many-to-many relationship
'''
import unittest
from petalapp.database.models import User, Hospital, Data, ROLE_USER
from petalapp import db
class BuildDestroyTables(unittest.TestCase):
def setUp(self):
db.drop_all()
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def test_user_setup(self):
user_test_1 = User("test_user_nickname","user_email",ROLE_USER)
db.session.add(user_test_1)
db.session.commit()
def test_data_setup(self):
data_test_1 = Data(1)
db.session.add(data_test_1)
db.session.commit()
def test_hospital_setup(self):
hospital_test_1 = Hospital("test_hospital_1")
db.session.add(hospital_test_1)
db.session.commit()
def test_make_unique_nickname(self):
u = User(nickname = 'john', email = 'john@example.com')
db.session.add(u)
db.session.commit()
nickname = User.make_unique_nickname('john')
assert nickname != 'john'
u = User(nickname = nickname, email = 'susan@example.com')
db.session.add(u)
db.session.commit()
nickname2 = User.make_unique_nickname('john')
assert nickname2 != 'john'
assert nickname2 != nickname
def test_multiple_link_table(self):
#create
drew = User(nickname= "Drew", email="Drew@gmail.com",role=ROLE_USER)
mac_hospital = Hospital("Mac_hospital")
pro_hospital = Hospital("pro_hospital")
mac_data = Data(1,2,3)
pro_data = Data(10,9,8)
#add
db.session.add(drew)
db.session.add(mac_hospital)
db.session.add(pro_hospital)
db.session.add(mac_data)
db.session.add(pro_data)
#commit
db.session.commit()
#create links
mac_hospital.data.append(mac_data)
pro_hospital.data.append(pro_data)
drew.hospitals.append(mac_hospital)
drew.hospitals.append(pro_hospital)
db.session.commit()
def functions_of_add_remove(self):
johns_hospital_data = Data('johns_hospital_data')
johns_hospital = Hospital('johns_hospital')
john = User('john', 'john@gmail.com')
db.session.add(johns_hospital_data)
db.session.add(johns_hospital)
db.session.add(john)
#TODO make a function for this?
johns_hospital.append(johns_hospital_data)
#do i need a commit?
db.session.commit()
self.assertEqual(john.remove_hospital(johns_hospital), None)
john_has_hospital = john.add_hospital(johns_hospital)
db.session.add(john_has_hospital)
db.session.commit()
self.assertEqual(john.add_hospital(johns_hospital), None)
self.assertEqual(len(john.hospitals), 1)
if __name__ == "__main__":
unittest.main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-10T05:18:10.087",
"Id": "51966",
"Score": "0",
"body": "I'm looking for exactly the same kind of best practice. If you have become confident in how to do it, could you share in a self-answer?"
}
] |
[
{
"body": "<h2>Models - General</h2>\n\n<p>The comments on the model definitions don't add much value. I could figure out the relationships from the db schema; tell me instead something about what the classes are meant to represent, any invariants they have, anything not made explicit in the code.</p>\n\n<h2>Models - User</h2>\n\n<p>When defining a backreference, as you do in <code>User</code>, I like to go to the other class and add a comment saying something along the lines of \"A backreference 'users' is created to the Users class\". With that said, I would avoid naming the variable <code>users</code>; what does the variable name 'users' tell me when reading the class? It tells me the type of the object I'm getting, but nothing about what significance those objects have. Something like <code>registered_users</code>, <code>patients</code> (or whatever makes sense) might be a better option.</p>\n\n<p>You could replace your <code>is_active</code>, <code>is_anonymous</code> methods with read only properties, but that's personal preference. The <code>get_id</code> method seems very odd, not sure I see the value.</p>\n\n<p>I question also the value of the <code>add_hospital</code> and <code>remove_hospital</code> methods, though that may be due to lack of knowledge of your use case. Regardless, the <code>remove_hospital</code> is incorrect; it should be:</p>\n\n<pre><code>def remove_hospital(self, hospital):\n if hospital in self.hospitals: # You have if not (hospital in self.hospital)\n self.hospitals.remove(hospital)\n</code></pre>\n\n<h2>Models - Data</h2>\n\n<p>Personally, any variable named <code>data</code> sets off alarm bells. As it is, the <code>Data</code> class seems to store a lot of \"stuff\", and no where do I get told why this stuff should be grouped together, what its conceptual value is, etc etc. Would something like <code>InspectionResult</code> (or whatever the data comes from) be more useful? Regardless, I can't help but feel this class does too much.</p>\n\n<p>Your <code>__init__</code> for the <code>Data</code> class is horrendous. Use the <a href=\"http://docs.sqlalchemy.org/en/rel_0_9/core/metadata.html#sqlalchemy.schema.Column.params.default\">default</a> parameter of the <code>Column</code> constructor to set defaults, and make sure to call <code>Super(Data, self).__init__()</code> if you are overriding the <code>__init__</code> of a subclass of anything you don't control.</p>\n\n<h2>Tests</h2>\n\n<p>I can't say I like the name of the test class; it calls itself <code>BuildDestroyTables</code> and then goes on to do a whole lot more than that. I've personally moved away from class based testing, but back when I used it, I would define a <code>BaseDatabaseTest</code> class that other tests could inherit from to absolve them of having to worry about database setup/cleanup while not violating the single responsibility principle.</p>\n\n<p>You use a raw sessions; I would encourage you to use a contextmanager or something to manage your session. Here's one from a project I'm currently working on:</p>\n\n<pre><code>import contextlib\n\n@contextlib.contextmanager\ndef managed_session(**kwargs):\n \"\"\"\n Provides \"proper\" session management to a block. Features:\n\n - Rollback if an exception is raised\n - Commit if no exception is raised\n - Session cleanup on exit\n \"\"\"\n session = db_session(**kwargs) # Or however you create a new session\n try:\n yield session\n except:\n session.rollback()\n raise\n else:\n session.commit()\n finally:\n session.close()\n</code></pre>\n\n<p>You can then use it like this:</p>\n\n<pre><code>with managed_session() as session:\n session.add(foo)\n raise RuntimeException(\"foobar\")\n # But it's ok, everything will get rolled back nicely and we'll have a viable session still\n</code></pre>\n\n<p>Stuff like the automatic commit is not to everyone's taste, but I think in general, the exception safety is nice. With that said, this is probably the most controversial thing I'll say in this answer; there are many approaches to session management, and this is only one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-18T22:37:33.023",
"Id": "42018",
"ParentId": "20008",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "42018",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-28T22:01:01.650",
"Id": "20008",
"Score": "15",
"Tags": [
"python",
"unit-testing",
"flask"
],
"Title": "Flask-SQLAlchemy models and unit-testing"
}
|
20008
|
<p>I've finally finished my universal query preparation function. Any suggestions on making it better? I feel it could use some tweaking, but am not sure how I would go about it.</p>
<p><strong>Variable examples/explanation</strong></p>
<ul>
<li><code>$db</code> - The database connection</li>
<li><code>$query</code> - Example: <code>$query = "SELECT * FROM users WHERE</code>username<code>=?"</code></li>
<li><code>$operation</code> - The operation you wish to perform (number of rows, insert data)</li>
<li><code>$type</code> - The variable types in <code>mysqli_stmt_bind_param</code> (example: <code>$type = "ssi"</code>)</li>
<li><code>$variables</code> - The variables to replace the question marks with</li>
</ul>
<p></p>
<pre><code>function manipulate($db, $query, $operation, $type, $variables)
{
//Check Number of Variables inputted
$numVars = (int)strlen($type);
//Seperate variables into an array
$var = explode(",",$variables);
//Handle Statement
$stmt = mysqli_stmt_init($db);
if(mysqli_stmt_prepare($stmt, $query)) {
echo "<br /> QUERY PREPARED <br />";
$x = 0;
if( $numVars == 1 ) {
mysqli_stmt_bind_param($stmt, $type, $var[0]);
} else if ( $numVars == 2 ) {
mysqli_stmt_bind_param($stmt, $type, $var[0], $var[1]);
} else if ( $numVars == 3 ) {
mysqli_stmt_bind_param($stmt, $type, $var[0], $var[1], $var[2]);
} else if ( $numVars == 4 ) {
mysqli_stmt_bind_param($stmt, $type, $var[0], $var[1], $var[2], $var[3]);
} else if ( $numVars == 5 ) {
mysqli_stmt_bind_param($stmt, $type, $var[0], $var[1], $var[2], $var[3], $var[4]);
}
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if($operation == "numRows" || $operation == "num_rows") {
$output = mysqli_stmt_num_rows($stmt);
} else {
echo "Operation not supported";
}
mysqli_stmt_close($stmt);
return $output;
} else {
echo mysqli_stmt_error($stmt);
echo "<br /> QUERY DENIED <br />";
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>This is going to sound a bit harsh, but I don't see a purpose to this function. It offers a tiny bit of a shortcut, but it cripples a lot of functionality to do so.</p>\n\n<ul>\n<li>I'm not very familiar with MySQLi (PDO seems to have a lot more advantages than MySQLi and only a few, insignificant disadvantages -- though PDO does not have a procedural API like MySQLi does), but it seems like the only thing this function ever returns is the number of rows? So this is a glorified num_rows() function?</li>\n</ul></li>\n<li><p>debugging output should be removed, and errors should either be returned or thrown as exception. Directly printing errors is bad since the calling code then doesn't know that an error occurred.</p></li>\n<li><p><code>$variables</code> is a blatant anti pattern. If you want an array, use an array. What if one of your bindings needs to have a comma in it?</p></li>\n<li><p>What if <code>numVars</code> is >= 6? Doesn't seem very flexible.</p>\n\n<ul>\n<li>If you decide to keep this function, use <a href=\"http://php.net/manual/en/function.call-user-func-array.php\" rel=\"nofollow\">call_user_func_array</a> to handle a dynamic amount of parameters.</li>\n</ul></li>\n<li><p>Supporting <code>numRows</code> and <code>numRows</code> would probably come back to be a pain. I'd stick with one or the other. </p>\n\n<ul>\n<li>Or, better yet, use constants like <code>MANIPULATE_OP_NUMROWS</code> (like built in functions do).</li>\n</ul></li>\n<li><p><code>manipulate</code> is a vague name. Manipulate what? And manipulate how?</p></li>\n<li><p><code>(int)strlen($type);</code> <code>strlen</code> already returns an int. (And even if it didn't, you're using loose comparisons anyway.)</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T04:20:13.020",
"Id": "31984",
"Score": "0",
"body": "Thanks very much for all the feedback.I understand your confusion in the 'point of this function' as it is not complete yet (I haven't added the other functionalities such as INSERT, DELETE, etc. only num_rows so far).Thus, the point of this function was so I didn't have to keep preparing statements - it gets a tad bit annoying,I'm lazy.I don't know if OOP makes it any easier; however, procedural is easy for me and gets the job done. Also, can you explain your 4th point about `$variables` and array. Oh and <3 <3 <3 <3 <3 for call_user_func_array. I am finding it troublesome on how to use it :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T23:25:15.857",
"Id": "32003",
"Score": "0",
"body": "@Wulf I mean instead of passing in something like \"a,b,c\" just pass in something like `array('a', 'b', 'c')`. Otherwise how can you represent `a,b` as an atomic piece and not `['a', 'b']`. As for call_user_func_array, it's just used to call a function with the array as unpacked args. Like: `function f($x, $y) { return $x + $y; } `$z = call_user_func_array('f', 3, 8);` That would have `$z` as `11` since `$x = 3` and `$y = 8` in the function call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T03:08:01.757",
"Id": "32006",
"Score": "0",
"body": "Thanks Corbin, i would've upvoted, but dont have the permissions currently."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T02:45:16.207",
"Id": "20012",
"ParentId": "20009",
"Score": "2"
}
},
{
"body": "<p>I agree with everything Corbin said, so +1 to him, I just had a few things I wanted to add. Corbin had a pretty good explanation of why this function is unnecessary, as well as some good general advice, but he did not mention anything about the code itself. So I will limit myself to that aspect alone.</p>\n\n<p>Type hinting will allow you to ensure that only the proper arguments are passed to your functions. In this case you could type hint the <code>$db</code> parameter as a MySQLi object and, if you take Corbin's advice, the <code>$variables</code> parameter as an array. This will then ensure that no mistakes, such as passing a PDO or MySQL object instead of a MySQLi object, can occur. If the wrong type of variable is injected, then it will fail.</p>\n\n<pre><code>function manipulate( MySQLi $db, $query, $operation, $type, Array $variables ) {\n</code></pre>\n\n<p>The internal comments should be unnecessary. If your code is self-documenting and following the core principles (DRY, Single Responsibility, etc...), then it should be obvious what is going on. Comments, such as these, merely add clutter and make your code less legible. If you need to add a comment, limit yourself to doccomments.</p>\n\n<p>Your <code>$x</code> variable seems to be unused. This can cause confusion, so you should avoid adding or keeping variables you aren't using. If it is for a feature you haven't added yet, wait until you add the feature before adding the variable. That being said, be careful of adding too many features to a function. Following the Single Responsibility Principle means that a function should do just one thing. So be careful that you don't violate it.</p>\n\n<p>First off, if you have a value that you want to apply multiple comparisons to, in this case <code>$numVars</code>, then you should use a switch statement. They are slightly faster, and a little cleaner.</p>\n\n<pre><code>switch( $numVars ) {\n case 1 :\n mysqli_stmt_bind_param($stmt, $type, $var[0]);\n break;\n\n //etc...\n}\n</code></pre>\n\n<p>Second, these if/else statements, and even the switch I mentioned above, is unnecessary and redundant. These solutions violate the \"Don't Repeat Yourself\" (DRY) Princple. As the name implies, your code should not repeat itself. There are many ways to avoid violating this principle, but in this instance you could either use a loop, I don't think it possible in this case, or you can use the <code>call_user_func_array()</code> as Corbin mentioned. If you look at the <a href=\"http://php.net/manual/en/mysqli-stmt.bind-param.php#109256\" rel=\"nofollow\">documentation for <code>bind_param()</code></a> one of the top comments shows an example of this.</p>\n\n<p>Your code is also violating the Arrow Anti-Pattern. This pattern usually illustrates code coming to points to create an arrow, but essentially it applies to any code that is heavily or unnecessarily indented. In this case you could reverse your first if statement and return early to avoid the most amount of indentation.</p>\n\n<pre><code>if( ! mysqli_stmt_prepare( $stmt, $query ) ) {\n return FALSE;//or throw error\n}\n\n//success start binding params\n</code></pre>\n\n<p>Hope this helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T18:21:18.623",
"Id": "20097",
"ParentId": "20009",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "20012",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T00:47:12.593",
"Id": "20009",
"Score": "1",
"Tags": [
"php",
"mysql",
"mysqli"
],
"Title": "Universal query preparation function"
}
|
20009
|
<p>I created some code for Minesweeper but I need help going over it. I would like if someone could go over it and point out anything (repeating code, code being called multiple times when not needed, etc).</p>
<p>This it the main class that also does a lot of other things:</p>
<pre><code>public class BoardBuild extends JFrame implements ActionListener {
static BoardBuild board = new BoardBuild();
static JPanel p1, p2, p3;
int miss = 0;
// top label
JLabel lbl1 = new JLabel("Minesweeper");
public static final int BOARD_HEIGHT = 10;
public static final int BOARD_WIDTH = 10;
public static final int NUMBER_OF_CELLS = BOARD_HEIGHT * BOARD_WIDTH;
public static final int BOMB_VALUE = 99;
public static final int NO_MINE = 0;
// all 100 of the board pieces to click
JButton[][] btn = new JButton[BOARD_WIDTH][BOARD_HEIGHT];
int mines[][] = new int[BOARD_WIDTH][BOARD_HEIGHT];// board piece values
private GenerateMines mineGen;
JButton btnReset = new JButton("Reset");
public BoardBuild() {
p1 = new JPanel();
p1.add(lbl1, BorderLayout.CENTER);
p2 = new JPanel();
p2.setLayout(new GridLayout(BOARD_WIDTH, BOARD_HEIGHT));
for (int x = 0; x < BOARD_HEIGHT; x++) {
for (int y = 0; y < BOARD_WIDTH; y++) {
btn[x][y] = new JButton("");
btn[x][y].addActionListener(this);
p2.add(btn[x][y]);
}
}
getMines();
p3 = new JPanel();
btnReset.addActionListener(this);
p3.add(btnReset, BorderLayout.CENTER);
}
public void getMines() {
mineGen = new GenerateMines();
System.out.println("New Mine Values Generated");
// sets indicator according to how many bombs around
for (int x = 0; x < BOARD_HEIGHT; x++) {
for (int y = 0; y < BOARD_WIDTH; y++) {
btn[x][y].setText("");
mines[x][y] = mineGen.getMinePos(x, y);
if (mines[x][y] >= BOMB_VALUE)
btn[x][y].setForeground(Color.RED);
else {
btn[x][y].setBackground(null);
if (mines[x][y] == 1)
btn[x][y].setForeground(Color.BLUE);
else if (mines[x][y] == 2)
btn[x][y].setForeground(Color.GREEN);
else if (mines[x][y] == 3)
btn[x][y].setForeground(Color.YELLOW);
else if (mines[x][y] == 4)
btn[x][y].setForeground(Color.ORANGE);
else if (mines[x][y] == 5)
btn[x][y].setForeground(Color.RED);
}
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
for (int x = 0; x < BOARD_HEIGHT; x++) {
for (int y = 0; y < BOARD_WIDTH; y++) {
if (e.getSource() == btn[x][y]) {
btn[x][y].removeActionListener(this);
if (mines[x][y] >= BOMB_VALUE) {
showBoard();
return;
} else if (mines[x][y] != NO_MINE) {
btn[x][y].setText("" + mines[x][y]);
btn[x][y].setBackground(Color.GRAY);
miss++;
} else if (mines[x][y] == NO_MINE)
floodFill(x, y);
checkWin();
System.out.println(miss);
}
}
}
if (e.getSource() == btnReset) {
miss = 0;
System.out.println(miss);
getMines();
for (int x = 0; x < BOARD_HEIGHT; x++) {
for (int y = 0; y < BOARD_WIDTH; y++) {
btn[x][y].addActionListener(this);
btn[x][y].setBackground(null);
}
}
}
}
public void floodFill(int x, int y) {
if (x >= 0 && x <= 9 && y >= 0 && y <= 9) {
for (int z = 1; z < 6; z++) {
if (mines[x][y] == z) {
miss++;
System.out.println(miss);
btn[x][y].setText(z + "");
btn[x][y].setBackground(Color.GRAY);
return;
}
}
if (mines[x][y] == 0 && btn[x][y].getBackground() != Color.GRAY) {
miss++;
System.out.println(miss);
btn[x][y].setBackground(Color.GRAY);
btn[x][y].removeActionListener(this);
floodFill(x - 1, y);
floodFill(x + 1, y);
floodFill(x, y - 1);
floodFill(x, y + 1);
} else {
return;
}
}
}
public void showBoard() {
System.out.println("BOOOM");
JOptionPane.showMessageDialog(this, "Unfortunately, You Lose", "",
JOptionPane.PLAIN_MESSAGE);
for (int x = 0; x < BOARD_HEIGHT; x++) {
for (int y = 0; y < BOARD_WIDTH; y++) {
btn[x][y].setBackground(Color.GRAY);
if (mines[x][y] != NO_MINE) {
if (mines[x][y] >= BOMB_VALUE)
btn[x][y].setText("B");
else
btn[x][y].setText("" + mines[x][y]);
}
}
}
miss = 0;
}
public void checkWin() {
if (miss == 90) {
System.out.println("WIN");
JOptionPane.showMessageDialog(this, "Congratulations, You Win!!",
"", JOptionPane.PLAIN_MESSAGE);
}
}
public static void main(String[] args) {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - 450) / 2);
int y = (int) ((dimension.getHeight() - 500) / 2);
board.setLocation(x, y);
board.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
board.add(p1, BorderLayout.NORTH);
board.add(p2, BorderLayout.CENTER);
board.add(p3, BorderLayout.SOUTH);
board.setSize(450, 500);
board.setVisible(true);
board.setResizable(true);
}
}
</code></pre>
<p>This is the class which generates the mine positions and the values of the "blocks" around it:</p>
<pre><code>public class GenerateMines {
// all 100 of the board pieces values (0=no bomb near 1=1 bomb near, etc)
int[][] board = new int[10][10];
public GenerateMines() {
int temp;
int row, column;
final int NO_MINE = 0;
final int BOMB_VALUE = 99;
final int NUM_OF_BLOCKS = 100;
final int NUM_OF_MINES = 10;
for (int j = 0; j < NUM_OF_MINES; j++) {
do {
temp = (int) (Math.random() * NUM_OF_BLOCKS);
row = temp / 10;
column = temp % 10;
} while (board[row][column] == BOMB_VALUE);
board[row][column] = BOMB_VALUE;
}
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
if (board[x][y] >= BOMB_VALUE) {
if (y != 9)// East
board[x][y + 1] += 1;
if (y != 0)// West
board[x][y - 1] += 1;
if (x != 0)// North
board[x - 1][y] = board[x - 1][y] + 1;
if (x != 9)// South
board[x + 1][y] = board[x + 1][y] + 1;
if (y != 9 && x != 0)// N.E.
board[x - 1][y + 1] += 1;
if (x != 0 && y != 0)// N.W.
board[x - 1][y - 1] += 1;
if (x != 9 && y != 0)// S.W.
board[x + 1][y - 1] += 1;
if (x != 9 && y != 9)// S.E.
board[x + 1][y + 1] += 1;
}
}
}
}
public int getMinePos(int r, int c) {// sends value of each piece to main
return (board[r][c]);
}
}
</code></pre>
<p>I would appreciate if someone could look over this and give me areas which I need to fix.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T17:41:54.057",
"Id": "32106",
"Score": "0",
"body": "move `10` as field dimension to a constant. This way you can easily change it in the future."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T10:48:21.323",
"Id": "64513",
"Score": "0",
"body": "The array `mine` is never used in `class GenerateMines`. Consider removing it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-10T16:24:11.540",
"Id": "137074",
"Score": "0",
"body": "My addition from the algorithm perspective - usually, in minesweeper you should generate the mines after the first user click. Why? You just don't want the user to find a mine by the first click."
}
] |
[
{
"body": "<p>In Java, primitive numeric types all default to their equivalent of <code>0</code>, therefore this block can be removed entirely from GenerateMines:</p>\n\n<pre><code>for (int x = 0; x < 10; x++) {\n for (int y = 0; y < 10; y++) {\n board[x][y] = 0;\n }\n}\n</code></pre>\n\n<p>Additionally, this <code>Boolean[][] filled = new Boolean[10][10];</code> is only ever filled as false, and then never read. Therefore these lines can be removed:</p>\n\n<pre><code>Boolean[][] filled = new Boolean[10][10];\n</code></pre>\n\n<p>and\n <code>filled[x][y] = false;</code></p>\n\n<p>And a call to <code>btn[x][y] != null</code> will produce the same result as checking <code>filled[x][y]</code> if you are using it somewhere outside the code you provided.</p>\n\n<p>The <code>actionPerformed()</code> method in <code>BoardBuild</code> should have an <code>@Override</code> annotation as it implements the method <code>ActionListener.actionPerformed()</code>.</p>\n\n<p>Your large <code>if</code> block in <code>getMines()</code> that sets the colour of the JButtons: the value of <code>mines[x][y]</code> does not change inside the block, therefore only one can be true in one iteration, and should therefore be an if/else-if block, or a switch statement to avoid checking the condition after it has already found one that is true (in a non-worst case scenario).</p>\n\n<p>The:</p>\n\n<pre><code>else {\n return;\n}\n</code></pre>\n\n<p>block in <code>BoardBuild.floodFill()</code> is unnecessary, as it is the last line in the method and would therefore happen on its own when it gets to the subsequent brace anyway.</p>\n\n<p>In the <code>BoardBuild()</code> constructor the call to <code>getMines();</code> is possibly dangerous as the method <code>getMines()</code> is overridable in a way which would stop the class from constructing properly. The simplest solution is to make the <code>getMines()</code> method <code>private</code> (if you don't need to use it outside of the class) or <code>final</code> if you do.</p>\n\n<p>Although they're more stylistic choices, I like to add <code>this.</code> when accessing member variables so you can tell the difference between them and local variables without syntax highlighting, and according to the <a href=\"http://java.about.com/od/javasyntax/a/nameconventions.htm\">Java naming conventions</a>, variables should start with a lowercase letter, so <code>BoardBuild Board</code> should be <code>BoardBuild board</code> unless you're going to make it final when it'd be <code>BoardBuild BOARD</code>.</p>\n\n<p>Additionally, these variables in GenerateMines:</p>\n\n<pre><code>int temp;\nint row, column;\n</code></pre>\n\n<p>Are only used in the constructor, but stored indefinitely because you made them member variables. They should be local to the constructor. The same is true of <code>GenerateMines mineGen;</code> in <code>BoardBuild</code> which is only used in <code>getMines()</code>. Only make them member variables if necessary to save on memory.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T16:06:33.853",
"Id": "31997",
"Score": "2",
"body": "Additionally, With the amount of time you spend iterating around mines to find out if it's the one that caused events, and changing properties in the same manner, You could cut out a lot of that if you made some kind of MineButton object which has its own ActionListener inside it with the commands to change its own properties? Then each button would work independently and you wouldn't need the global listener to manage it inside the frame."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T21:45:50.830",
"Id": "31999",
"Score": "0",
"body": "what do you mean by create a MineButton object? like all the commands that the program does when you clicks a button?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T21:52:54.550",
"Id": "32000",
"Score": "0",
"body": "@Exikle Basically what C. Ross said except also extending JButton and implementing ActionListener, with the rules for what colour to be in there as well, so each MineButton will have all the methods for what the mine does and how it reacts when you click on it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T01:06:22.670",
"Id": "32481",
"Score": "0",
"body": "nope, sorry that was by accident, i didnt know it was unaccepeted"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-10T19:29:52.113",
"Id": "32658",
"Score": "0",
"body": "\"primitive numeric types all default to their equivalent of 0\", except (method) local variables!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T14:28:34.623",
"Id": "20023",
"ParentId": "20017",
"Score": "6"
}
},
{
"body": "<p>The <code>getMines</code> method could probably be named more descriptively. A method that returns <code>void</code> with a name starting with \"get\" is misleading.</p>\n\n<p>You have many \"magic numbers\" in your code, especially <code>10</code> and <code>100</code>. This makes your code less clear, and harder to change. Consider instead creating constants for board height, board width, and number of cells:</p>\n\n<pre><code>public static final int BOARD_HEIGHT = 10;\npublic static final int BOARD_WIDTH = 10;\npublic static final int NUMBER_OF_CELLS = BOARD_HEIGHT * BOARD_WIDTH;\n</code></pre>\n\n<p>So a snippet of code like the below would change to</p>\n\n<pre><code>for (int x = 0; x < BOARD_WIDTH; x++) {\n for (int y = 0; y < BOARD_HEIGHT; y++) {\n btn[x][y].setBackground(Color.GRAY);\n if (mines[x][y] != 0) {\n</code></pre>\n\n<p>Or a declaration would change to </p>\n\n<pre><code>int board[][] = new int[BOARD_WIDTH][BOARD_HEIGHT]\n</code></pre>\n\n<p>I'm also not fond of representing the bombs as a magic number. You could create a cell class:</p>\n\n<pre><code>public class Cell { \n private int x;\n private int y;\n private boolean isBomb;\n private int adjacentBombCount;\n //TODO: Constructors, setters, etc\n}\n</code></pre>\n\n<p>Then your code would be much clearer:</p>\n\n<pre><code>if (cell.isBomb()){\n</code></pre>\n\n<p>On the other hand, if you want to leave it coded as <code>int</code>, you should at least define a constant for the bomb.</p>\n\n<pre><code>/*\n * The value to set if the cell contains a bomb\n */\npublic static final int BOMB_VALUE = 99; \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T19:13:15.107",
"Id": "20029",
"ParentId": "20017",
"Score": "4"
}
},
{
"body": "<pre><code>mines[x][y] == 0\n</code></pre>\n\n<p>seams to mean 'no mine'</p>\n\n<p>I would make a constant </p>\n\n<pre><code>final static int NO_MINES=0;\n</code></pre>\n\n<p>=></p>\n\n<pre><code>mines[x][y] == NO_MINES\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T17:44:41.243",
"Id": "20096",
"ParentId": "20017",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20023",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T09:27:10.483",
"Id": "20017",
"Score": "4",
"Tags": [
"java",
"game",
"minesweeper"
],
"Title": "Minesweeper Code"
}
|
20017
|
<p>The problem can be viewed <a href="http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36" rel="nofollow">here</a>, since it's styled. I don't think I should just copy and paste.</p>
<p>I implemented recessive function and dynamic programming to solve it. It can successfully passed UVa Judge with a score of 612ms, but it's not fast enough for <a href="http://zerojudge.tw/ShowProblem?problemid=d712" rel="nofollow">this</a> site. Which test my code against 200000 lines of input, and giving only 2s.</p>
<pre><code>#include <cstdio>
#include <iostream>
int cycleLength(long long int);
int cycleLengthResult[1000001];
int main(int argc, char *argv[])
{
int i = 0, j = 0, cur = 0, max = 0, k = 0, s = 0;
for (i = 1 ; i < 1000001 ; ++ i ) cycleLength(i);
while ( scanf("%d%d", &i, &j) != EOF )
{
printf("%d %d ", i, j);
if ( i > j )
{
s = i;
i = j;
j = s;
}
max = 0;
for ( k = i ; k <= j ; ++ k )
{
cur = cycleLengthResult[k];
if (cur > max) max = cur;
}
printf("%d\n", max);
}
return 0;
}
int cycleLength(long long int arg)
{
if ( arg > 1000000 )
{
if (!(arg & 1))
return 1 + cycleLength(arg/2);
else
return 1 + cycleLength(arg*3+1);
}
if (!cycleLengthResult[arg])
{
int valueForArg = 0;
if (arg == 1)
valueForArg = 1;
else if (!(arg & 1))
valueForArg = 1 + cycleLength(arg/2);
else
valueForArg = 1 + cycleLength(arg*3+1);
cycleLengthResult[arg] = valueForArg;
}
return cycleLengthResult[arg];
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T18:11:21.640",
"Id": "32027",
"Score": "3",
"body": "Why are you using the C standard library and C programming idioms in what is apparently supposed to be a C++ program?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T22:20:44.760",
"Id": "32035",
"Score": "0",
"body": "@Paul R I was told that scanf and printf will be faster than com and cout. And on the compiler provided by zerojudge.tw, you will need cstdlib."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T07:52:58.757",
"Id": "32076",
"Score": "0",
"body": "This is also known as the [Collatz Conjecture](http://en.wikipedia.org/wiki/Collatz_conjecture), and there's also the [XKCD](http://xkcd.com/710/) view on it too."
}
] |
[
{
"body": "<p>The only places I have found that improve <code>cycleLength</code> (by 5-10%) are </p>\n\n<ul>\n<li>reversing the (somewhat illogical) <code>if (!(arg & 1))</code> conditions (not really sure if this had an effect though, as there seems no reason for it to)</li>\n<li><p>and removing the test for <code>arg == 1</code> by initialising <code>cycleLengthResult[1]</code> to 1:</p>\n\n<p><code>int cycleLengthResult[1000001] = {0, 1, 0}</code></p></li>\n</ul>\n\n<p>It is also possible to extract the duplicated code to make the function more readable, although this does not improve the performance:</p>\n\n<pre><code>int cycleLength(long arg);\n\nstatic inline int nextLength(long arg)\n{\n long n;\n if (arg & 1) {\n n = (arg * 3) + 1;\n } else {\n n = arg / 2;\n }\n return 1 + cycleLength(n);\n}\n\nint cycleLength(long arg)\n{\n if (arg > 10000000) {\n return nextLength(arg);\n }\n if (cycleLengthResult[arg] != 0) {\n return cycleLengthResult[arg];\n }\n return cycleLengthResult[arg] = nextLength(arg);\n}\n</code></pre>\n\n<p>There might be ways to improve <code>main</code> but I didn't look at that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T14:34:02.733",
"Id": "32022",
"Score": "0",
"body": "I've read your answer, and will try it this week."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T23:47:37.807",
"Id": "20035",
"ParentId": "20020",
"Score": "2"
}
},
{
"body": "<p>I took an elective last semester in which we had to do UVa questions. Just dug up my old UVa 100 submission, and I have a few suggestions for speed (mine was accepted in 200 ms, though I suspect it could be optimized a ton more).</p>\n\n<p>The main thing I see is that you shouldn't use recursion. Due to the setup cost of calling functions, iteration is going to be way faster (in some situations the same stack frame can be reused, but I doubt that optimization is being done in your code).</p>\n\n<hr>\n\n<p>Though that is my main suggestion, there are a few very minor algorithmic optimizations that can be noted mathematically. </p>\n\n<pre><code>t(n) = 1 if n is 1\n = 3n + 1 if n is odd\n = n / 2 if n is even\n\nc(n) = number of times t(n) will happen\n(terrible math syntax here, but erm... go with it)\n</code></pre>\n\n<p>Now, the approach I took was to build a table bottom up. Basically an array like <code>int m[1000001]</code>.</p>\n\n<p>Then a loop like:</p>\n\n<pre><code>for (int i = 1; i <= 1000000; ++i) {\n if (i % 2 == 0) {\n //We know that i / 2 must already be set, so we can just do a constant time look up\n //(your code already does this implicitly through the recursion)\n m[i] = 1 + m[i / 2];\n } else {\n m[i] = cycleLength(i);\n }\n}\n</code></pre>\n\n<p>Nothing special about this loop; it's just the iterative form of your code.</p>\n\n<p>There is an odd little optimization you can make though:</p>\n\n<pre><code>if (i % 2 == 0) {\n m[i] = 1 + m[i/2];\n} else if (i % 8 == 5) {\n m[i] = 4 + m[3 * ((i - 5) / 8) + 2];\n} else {\n m[i] = cycleLength(i);\n}\n</code></pre>\n\n<p>The theory here is that for any j < i, you know that m[j] is populated. Thus, if you can do some manipulation to get <code>m[i] = c + m[f(i)]</code> such that f(i) < i you can do a constant time look up rather than the potentially enormously expensive cycleLength call.</p>\n\n<p>It's the same concept in the <code>1 + m[i / 2]</code> situation, just weirder.</p>\n\n<p>If i mod 8 = 5, then by definition, <code>i = 8j + 5</code> for some integer <code>j</code>.</p>\n\n<p><code>i = 8j + 5 = 2k + 1 with k = 4j + 2</code> thus i is odd.</p>\n\n<p>So we follow the pattern:</p>\n\n<pre><code>8j + 5 -> 24j + 16 -> 12j + 8 -> 6j + 4 -> 3j + 2\n</code></pre>\n\n<p>Note the crucial part here: 3j + 2 < 8j + 5. This means that we can define m[i] in terms of <code>4 + m[3 * ((i - 5) / 8) + 2]</code>.</p>\n\n<p>I'm too lazy to get out a pad of paper, but I suspect that more arithmetic trickery like this is possible (the weird situation of i mod 8 = 5 is something that the professor pointed out). Even without it, an iterative approach is easily fast enough to be accepted by UVa's online judge, but it does make a surprising 48 ms difference with my program.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T14:33:04.573",
"Id": "32021",
"Score": "0",
"body": "@Corbin I read your answer, and will try it next week."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T18:22:07.277",
"Id": "32028",
"Score": "0",
"body": "@WilliamMorris Whoops, yup. Double typed it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-31T02:55:15.817",
"Id": "68237",
"Score": "0",
"body": "Don't know why I didn't accept this more than a year ago. This did the trick then."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T02:43:19.927",
"Id": "20037",
"ParentId": "20020",
"Score": "10"
}
},
{
"body": "<p>I've wrote some similar code and submitted on <a href=\"http://www.programming-challenges.com/\" rel=\"nofollow\">programming challenges website</a>. If I precompute the cache array it executes in 570ms, while if I cache as I go as needed it executes in 62ms.</p>\n\n<p>I'd say then that the greatest optimisation is not to compute values that don't need to be computed. Doing a single <code>printf</code> instead of two shaved about 5 ms. A bit better, but not really significant.</p>\n\n<pre><code>#include <cstdio>\n#include <algorithm> // std::min, std::max\nusing namespace std;\n\nint cycleLength(int);\nconst int CACHE_LEN = 1000001;\nshort cache[CACHE_LEN] = {0};\n\nint main()\n{\n int leftNo, rightNo, minNo, maxNo;\n while ( scanf(\"%d%d\", &leftNo, &rightNo) != EOF )\n {\n int maxCycles = 0;\n minNo = min(leftNo, rightNo);\n maxNo = max(leftNo, rightNo);\n for (int curNo = minNo; curNo <= maxNo; ++curNo )\n {\n int curCycles = cycleLength(curNo);\n if (curCycles > maxCycles) maxCycles = curCycles;\n }\n printf(\"%d %d %d\\n\", leftNo, rightNo, maxCycles);\n }\n return 0;\n}\n\nint cycleLength(int start)\n{\n int length = cache[start];\n if (length != 0) return length;\n length++;\n long long int current = start;\n while (current != 1)\n {\n if (current % 2 == 0) current /= 2;\n else current = 3 * current + 1;\n length++;\n }\n cache[start] = length;\n return length;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-12T00:57:10.067",
"Id": "133390",
"Score": "0",
"body": "This isn't really a review of the asker's code. Posting some of your own code is okay, but you should explain how it can lead to an improvement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-12T10:13:47.103",
"Id": "133449",
"Score": "0",
"body": "thanks for pointing it out, I'm new to the site. I've said how to lead to a ten-fold improvement though: don't pre-compute everything, but only what you're asked for."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-12T00:53:06.687",
"Id": "73410",
"ParentId": "20020",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "20037",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T12:42:29.970",
"Id": "20020",
"Score": "10",
"Tags": [
"c++",
"time-limit-exceeded",
"collatz-sequence"
],
"Title": "3n + 1 problem optimization"
}
|
20020
|
<p>Here is my breadth-first search (<code>bfs</code>) and depth-first search (<code>dfs</code>) code for graph traversal. Please give me some constructive reviews on it.</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#define null 0
typedef struct node//node of a linked list
{
struct vertex* info;//info part of node
struct node* next;// next pointer of a node
}*nodeptr;
typedef struct edge
{
int weight;
struct vertex * point;
struct edge *next;
}*eptr;
typedef struct vertex
{
int degree;
int info;
int status;
struct vertex * next;
struct edge *point;
struct vertex *parent;
}* vptr;
typedef struct graph
{
struct vertex *start;
int *directed;
}Graph;
typedef struct queue
{
nodeptr front;//front pointer of a queue
nodeptr rear;//rear pointer of a queue
} *QUEUE;
QUEUE qwe;
void insert_node(Graph *g,int x)
{
vptr p=(vptr)malloc(sizeof(struct vertex));
p->degree=0;
p->info=x;
p->point=null;
p->status=1;
p->next=g->start;
g->start=p;
return;
}
vptr find(vptr p,int x)
{
while(p!=null)
{
if(p->info==x)
return p;
p=p->next;
}
return null;
}
void insert_edge(Graph *g,int a,int b,int directed)
{
vptr loca;
vptr locb;
eptr p;
eptr q;
loca=find(g->start,a);
locb=find(g->start,b);
if(loca==null||locb==null)
{
printf("void insertion");
return;
}
p=loca->point;
q=null;
while(p!=null)
{
q=p;
p=p->next;
}
p=(eptr)malloc(sizeof(struct edge));
p->point=locb;
p->next=null;
if(q!=null)
q->next=p;
else
loca->point=p;
if(directed)
return;
else
insert_edge(g,b,a,1);
}
void delete_edge(Graph *g,int a,int b,int directed)
{
vptr loca=find(g->start,a);
vptr locb=find(g->start,b);
eptr p=loca->point;
eptr q=null;
while(p->point!=locb)
{
q=p;
p=p->next;
}
if (q==null)
loca->point=null;
else
q->next=p->next;
free(p);
return;
}
void process_vertex_early(vptr x)
{
printf("%d ",x->info);
}
void process_vertex_late(vptr x)
{
}
void process_edge(vptr x,vptr y)
{
//printf("%d %d\n",x->info,y->info);
}
int empty_queue()//if queue is empty then return 1
{
if (qwe->front==null)
return 1;
else
return 0;
}
void insert_queue(vptr x)
{
nodeptr p=(nodeptr)malloc(sizeof(struct node));//allocate new memory space to be added to queue
p->next=null;
p->info=x;
if(empty_queue())//if the queue is empty,front and rear point to the new node
{
qwe->rear=p;
qwe->front=p;
return;
}
qwe->rear->next=p;
qwe->rear=p;
//rear points to the new node
return;
}
vptr delete_queue()
{
vptr x;
if(empty_queue())//if queue is empty then it is the condition for underflow
{
printf("underflow\n");
return;
}
nodeptr p=qwe->front;//p points to node to be deleted
x=p->info;//x is the info to be returned
qwe->front=p->next;
if(qwe->front==null)//if the single element present was deleted
qwe->rear=null;
free(p);
return x;
}
</code></pre>
<p><strong>BFS</strong></p>
<pre><code>void bfs(Graph *g)
{
vptr q=g->start;
vptr x;
vptr y;
eptr p;
while(q!=null)
{
q->status=1;
q=q->next;
}
g->start->status=2;
insert_queue(g->start);
while(!(empty_queue()))
{
x=delete_queue();
process_vertex_early(x);
x->status=3;
p=x->point;
while(p!=null)
{
y=p->point;
if(y->status!=3||g->directed)
process_edge(x,y);
if(y->status==1)
{
y->status=2;
y->parent=x;
insert_queue(y);
}
p=p->next;
}
process_vertex_late(x);
}
return;
}
</code></pre>
<p><strong>DFS</strong></p>
<pre><code>void dfs(Graph *g,vptr x)
{
// if(finished)return;
// x->entry_time=++time;
eptr p=x->point;
vptr y;
process_vertex_early(x);
while(p!=null)
{
y=p->point;
if(y->status==1)
{
process_edge(x,y);
y->status=2;
y->parent=x;
dfs(g,y);
}
else if((y->status==2&&x->parent!=y||g->directed))
{
process_edge(x,y);
}
// if(finished)return;
p=p->next;
}
process_vertex_late(x);
x->status=3;
//x->exit_time=++time;
return;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T20:25:33.630",
"Id": "32029",
"Score": "0",
"body": "I can understand how your graph hangs together. You will need to add comments the describe how `node/edge/vertex/graph` hang together to build a graph."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T23:26:24.683",
"Id": "32038",
"Score": "0",
"body": "Have you tested it at all? In `delete_edge` you have `if (q=null)` which your compiler should warn you about."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T06:25:34.537",
"Id": "32044",
"Score": "0",
"body": "yesyes (q=null) should be (q==null)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T17:12:24.390",
"Id": "32067",
"Score": "1",
"body": "But did you test it? I would expect that sort of error to turn up quite quickly in tests (quite apart from the compiler telling you of it)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T07:44:35.867",
"Id": "32075",
"Score": "1",
"body": "It would be easier to review this code if there was an example `main()` program that created a graph and then ran the traversal functions over it. It is a lot harder to work out what's required and expected when you don't provide an SSCCE ([Short, Self-Contained, Correct Example](http://sscce.org/))."
}
] |
[
{
"body": "<p>Some comments, in no particular order:</p>\n\n<p>You are inconsistent in spacing and in positioning of '*', which makes the code look\nrather scrappy.</p>\n\n<p>It is generally less confusing not to hide pointers behind type definitions.\nAdmittedly you use 'ptr' in the type names, so this lessens the harm. But\nwhen I compare your definition and use of <code>eptr</code>:</p>\n\n<pre><code>typedef struct edge\n{\n ...\n}*eptr;\n\n// function:\n{\n eptr p;\n</code></pre>\n\n<p>to a more normal:</p>\n\n<pre><code>typedef struct edge\n{\n ...\n} Edge;\n\n// function:\n{\n Edge *e;\n</code></pre>\n\n<p>I have no hesitation in saying the latter is more easily understood (bearing\nin mind that the function will probably not be near to (or even in the same\nfile as) the definition.</p>\n\n<p>Also on types, your <code>QUEUE</code> would be better written <code>Queue</code> as upper case\nnames are usually kept for #define constants.</p>\n\n<p>Other issues</p>\n\n<ul>\n<li><p>don't cast the return of <code>malloc</code>. This can be harmful and is never\nnecessary in C. Also check the return from <code>malloc</code> is not NULL and handle\nsuch failures.</p></li>\n<li><p>add spaces around operators ('==', '=', etc)</p></li>\n<li><p>indent the code properly</p></li>\n<li><p>using braces around single line statements avoids some common errors.</p></li>\n<li><p><code>empty_queue</code> is badly named. Prefer <code>is_empty</code> or something indicating\nthat the return is a truth value. Also <code>empty_queue</code> and <code>delete_queue</code>\nshould have a <code>void</code> parameter list.</p></li>\n<li><p><code>delete_queue</code> seems to delete on entry from the queue, not the whole queue\nas its name would suggest.</p></li>\n<li><p><code>delete_edge</code> does not use its parameter <code>directed</code>. </p></li>\n<li><p><code>process_vertex_early</code>, <code>process_vertex_late</code> and <code>process_edge</code> appear to\nbe unfinished.</p></li>\n<li><p><code>bfs</code> has three <code>while</code> loops. That is seldom necessary and indicates that\nyou could extract some of the functionality to separate helper functions\nand hence make the function more understandable.</p></li>\n<li><p>both <code>dfs</code> and <code>bfs</code> call incomplete functions <code>process_vertex_early</code> and\n<code>process_vertex_late</code>, which makes me think this code is generally\nincomplete.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-02T16:57:08.397",
"Id": "36524",
"ParentId": "20022",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T12:54:24.663",
"Id": "20022",
"Score": "2",
"Tags": [
"c",
"algorithm",
"breadth-first-search",
"depth-first-search"
],
"Title": "Breadth- and Depth-first search code"
}
|
20022
|
<p>As a Java native, I am always a little worried when doing Objective-C because of memory leaks and pointers flying at my head...</p>
<p>All comments are welcome on the <code>Category</code> below. The <code>Category</code> functions are correct.</p>
<p><a href="https://github.com/Chucky2be/iRot47" rel="nofollow">GitHub</a></p>
<pre><code>#import "NSString+r47.h"
@implementation NSString (r47)
-(NSString *) r47String
{
const char *_string = [self cStringUsingEncoding:NSASCIIStringEncoding];
int stringLength = [self length];
char newString[stringLength+1];
int x;
for( x=0; x<stringLength; x++ )
{
unsigned int aCharacter = _string[x];
if( 0x20 < aCharacter && aCharacter < 0x7F ) // from ! to ~
newString[x] = (((aCharacter - 0x21) + 0x2F) % 0x5E) + 0x21;
else // Not an r47 character
newString[x] = aCharacter;
}
newString[x] = '\0';
NSString *rotString = [NSString stringWithCString:newString encoding:NSASCIIStringEncoding];
DLog(@"%@ = %@",self,rotString);
return rotString ;
}
@end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T22:51:03.823",
"Id": "32115",
"Score": "1",
"body": "I would say it looks ok — as long as you dont use it to gain safety in real world projects. ROT is hardly obfuscating and not secure at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T21:32:58.253",
"Id": "41200",
"Score": "0",
"body": "@Frank, I'd personally avoid using the leading underscore naming on `_string` here. I think that's distracting, and potentially confusing."
}
] |
[
{
"body": "<p>This bit looks just a bit suspect:</p>\n\n<pre><code>int stringLength = [self length];\nchar newString[stringLength+1];\n</code></pre>\n\n<p>You're using the NSString \"length\" property to size the C char array allocation. This assumes that the string's \"length\" value (which reflects number of composed unicode characters) will always be equal to the ASCII encoded length, but that's not necessarily true. This is a case of using a value from one domain in another. NSString provides a method that you should use instead:</p>\n\n<pre><code>int stringLength = [self lengthOfBytesUsingEncoding:NSASCIIStringEncoding];\n</code></pre>\n\n<p>An equivalent, and probably even clearer way to handle this is to get your length from the C-native function, which makes sense since that's the string you're iterating over in the first place:</p>\n\n<pre><code>size_t stringLength = strlen(_string);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T04:16:51.460",
"Id": "20311",
"ParentId": "20025",
"Score": "4"
}
},
{
"body": "<p>The question title suggested that this would be a <code>Rot47</code> category on <code>NSString</code>, but it's not. It's an <code>r47</code> category (which tells me nothing... what's \"r47\"?).</p>\n\n<p>This is Objective-C, not C or C++ or any other language where cryptic terseness is favored. We prefer verboseness. The category should be called <code>Rot47</code>. This should be <code>@implementation NSString (Rot47)</code>. The method should be called <code>- (NSString *)rot47String;</code></p>\n\n<hr>\n\n<p>In Objective-C, we also prefer our opening braces go on the same line, not on their own line. For example:</p>\n\n<pre><code>for (;;) {\n</code></pre>\n\n<hr>\n\n<p>Braces are technically optional, but you really shouldn't think of them as such. Apple even agrees and made them non-optional in <a href=\"/questions/tagged/swift\" class=\"post-tag\" title=\"show questions tagged 'swift'\" rel=\"tag\">swift</a>. You've left them out of your <code>if</code>/<code>else</code> blocks, which is a great way to leave your code open for future bugs.</p>\n\n<hr>\n\n<p>When we implement categories on Foundation classes, we should take care to ensure their portability. The method should be designed to work no matter what project we import this file into and no matter what the contents of the string.</p>\n\n<p>The problem here is that your method doesn't do that. Your method works fine presuming a particular encoding, but for anything else it will produce incorrect results.</p>\n\n<p>Rather than a <code>char</code> array, we need a <code>unichar</code> array.</p>\n\n<pre><code>NSUInteger length = [self length];\nunichar letters[length + 1];\n\n[self getCharacters:letters range:NSMakeRange(0,length)];\n</code></pre>\n\n<p>Now <code>letters</code> is an array of <code>unichar</code>s for us to iterate over and transform correctly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-19T15:03:30.357",
"Id": "57456",
"ParentId": "20025",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "20311",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T15:58:21.707",
"Id": "20025",
"Score": "5",
"Tags": [
"strings",
"objective-c",
"ios",
"caesar-cipher",
"category"
],
"Title": "Rot47 an NSString Category"
}
|
20025
|
<p>I have multiple forms, each of which would like to send message through the network, using my <code>NetworkCommunicator</code> class's <code>SendMessage</code> method.</p>
<p>The solution I described here works, however it is ugly, and bludgeons some of the main concepts of OOP paradigm. What I'm looking for (and I'm open to any suggestions) is basically to achieve the same goal but in a more elegant, and OOP conforming solution. (maybe by events?)</p>
<p>I'm using more than these forms, but for the example, these seemed to be enough.</p>
<pre><code>//using statements
namespace examplespace
{
public delegate void ImprovedSenderDelegate(string message);
public class LoginForm :Form
{
private NetworkCommunicator ncom = new NetworkCommunicator();
public Ncom
{
get { return ncom; }
}
private void Login()
{
MainForm mf = new MainForm();
mf.Owner = this;
//other things i do etc.
this.Hide();
mf.Show();
}
}//endofLoginForm
public class MainForm :Form
{
public ImprovedSenderDelegate ISD;
private void Load ()
{
(this.Owner as LoginForm).NCom.SubscribeToSendMessage(this);
}
private void I_Want_To_send_A_Message(string message)
{
ISD(string);
}
}//endofMainForm
public class NetworkCommunicator
{
public void SubscribeToSendMessage(object sender)
{
if (sender is MainForm)
{
(sender as MainForm).ISD += new ImprovedSenderDelegate(SendMessage);
}
}
private void SendMessage(string message)
{/*magic*/}
}/endofNetworkCommunicator
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T20:30:01.303",
"Id": "32030",
"Score": "0",
"body": "Feel more complex than it should have been. Is it a two-way communication, or do forms send their message in one direction only? Also, I believe that the `MainForm` should temporarily show the `LoginForm`, and not what you have - a `LoginForm` permanently shows the `MainForm`. I would simplify things as much as possible first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T21:19:40.537",
"Id": "32032",
"Score": "0",
"body": "Forms send their messages to the server only (through one tcp connection) using delegates however each form can receive message from the server. I Think your idea about the MainForm vs Loginform is quite right, i don't know why i didn't do it that way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T23:17:27.867",
"Id": "32037",
"Score": "0",
"body": "Does the communication need to be truly asynchronous? The `LoginForm` does not need it. It should spin around and wait until the login succeeds. What about the other form? Give me an example of the type of communication that goes on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T10:28:01.977",
"Id": "32046",
"Score": "0",
"body": "Well, for the LoginForm it's not entirely necessary, however, other forms work in a manner that they need it. What the server does is, it connects to a device via serial port, and sends everything the device writes there, to the client, and writes everything to the device which the client sends using a basic protocol WRITE_DEVICE|DEVICE_ID|MESSAGE. So because of this, at least some of the client's forms have to work async. Because they have to show the message, the device sends while being able to send messages themselves. Also there could be multiple devices, which i handle on tabbed forms."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T11:08:22.393",
"Id": "32048",
"Score": "0",
"body": "Is this a freeware/opensource project?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T11:15:17.337",
"Id": "32049",
"Score": "0",
"body": "You could say that, it's not distributed anywhere. i'm perparing for my bsc thesis, and this is a proof of concept, that a free implementation of a pretty expensive program can be done, in a relatively small amount of time. Since I'm more of a network engineer, i feel I'm a bit in over my head here, hence my above question. Also after February(hopefully) the source code will be made available on some public source control site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T12:16:23.247",
"Id": "32054",
"Score": "0",
"body": "I d'like to join an open source/freeware project soon. If you wish, upload it to codeplex and we can work on it :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T13:47:48.477",
"Id": "32057",
"Score": "0",
"body": "Well since it's part of my thesis, i can't do that right now, but after February I don't see a problem doing it."
}
] |
[
{
"body": "<p>My suggestions:</p>\n\n<p>If the NetworkCommunicator exists only once per application, you should create a singelton. Code sample:</p>\n\n<pre><code> /// <summary>\n /// Provides a base class for singeltons.\n /// </summary>\n /// <typeparam name=\"T\">The class that act as a singelton.</typeparam>\n public abstract class Singleton<T>\n where T : class\n {\n protected Singleton()\n {\n }\n\n /// <summary>\n /// Gets the singelton instance.\n /// </summary>\n public static T Instance\n {\n get { return Nested._instance; }\n }\n\n private sealed class Nested\n {\n /// <summary>\n /// Creates the nested instance class.\n /// </summary>\n /// \n /// <remarks>\n /// Explicit static constructor to tell the compiler\n // not to mark type as beforefieldinit.\n /// </remarks>\n static Nested()\n {\n ConstructorInfo constructor = typeof (T).GetConstructor(Type.EmptyTypes) ??\n typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, Type.EmptyTypes, null);\n\n if (constructor == null)\n throw new InvalidOperationException(\"Class has no private nor public constructor\");\n\n _instance = (T)constructor.Invoke(null);\n }\n\n internal static readonly T _instance;\n }\n }\n</code></pre>\n\n<p>If someone has any suggestion about my singelton implementation, let me know it..</p>\n\n<p>The delegate makes the code more complex and violates the KISS OOP principle: Keep It Simple and Stupid. Make it as easy as possible first.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T12:01:09.357",
"Id": "32052",
"Score": "0",
"body": "Thank you for the suggestion. I only need one instance per application, so it seems like a good idea. I am not familiar with singletons, so i started my reading here: http://msdn.microsoft.com/en-us/library/ff650316.aspx it seems like something i could implement. If i understand it correctly, with this pattern, i could directly use that instance, and i wouldn't need a delegate to send a message(i have to make it's sendmessage method public). however, for receiving the message part, I'm not entirely sure.I'll make some changes to the code along with Leonid's suggestion, and update the question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T11:08:17.153",
"Id": "20056",
"ParentId": "20027",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20056",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T17:24:30.940",
"Id": "20027",
"Score": "1",
"Tags": [
"c#",
".net",
"delegates"
],
"Title": "Using delegates to communicate between forms and networkcommunicator class"
}
|
20027
|
<h1>Problem</h1>
<p>Disclaimer: This is my first clojure function & I'm still busy finishing the last chapters of "Programming Clojure". Thanks! :)</p>
<p>I am writing a function to randomly flood-fill parts of a game's map (i.e. this is not a traditional flood-fill that can recursively fill all available space). The idea is to create a random-shaped island, and inside that island create a random-shaped mountain. (i.e. pass the set of island points as a filter to the next flood fill function, so the mountain will be created only within the island's tiles).</p>
<p>This is what my code currently produces (You'll notice the window / drawing code stolen from the snake game in PragProg's Programming Clojure. ;))</p>
<p><img src="https://i.stack.imgur.com/SB7Y8.png" alt="Island & Mountain"></p>
<h1>Clojure Style</h1>
<p>This is my code:</p>
<pre><code>(def dirs2 '([-1 0] [1 0] [0 -1] [0 1]))
(defn neighbours [pt]
(for [dir dirs2]
(vec (map + pt dir))))
(defn flood-fill2
"start -> point to start filling from
n -> number of tiles to create
filter-fn -> a fn that must return true for new points"
([start n]
(flood-fill2 start n (fn [& _] true)))
([start n filter-fn]
(loop [result #{}
candidates #{start}
i n]
(if (or (zero? i) (empty? candidates))
result
(let [current (rand-nth (seq candidates))]
(if (and (filter-fn current) (not (result current)))
(recur
(conj result current)
(apply conj (disj candidates current) (neighbours current))
(dec i))
(recur result (disj candidates current) i)))))))
</code></pre>
<ul>
<li><p>Is this idiomatic clojure code? The loop construct in there feels like standard iterative code I learned to write in Java / C++. Do you see a shorter way to write this?</p></li>
<li><p>Could I implement this as a lazy-seq somehow? <code>(take 600 (lazy-fill [25 25] optional-src-set))</code> looks much cooler than <code>(flood-fill2 [25 25] 600 island)</code>.</p></li>
<li><p>I tried to write an anonymous function that returns true for any argument(s) using this notation <code>#()</code> but had to eventually give up and wrote it using <code>fn</code>: <code>(fn [& _] true)</code>. Could I have used <code>#()</code> somehow?</p></li>
</ul>
<h2>Performance</h2>
<p>My intial (naive) implementation looked like this:</p>
<pre><code>(defn flood-fill [filled n]
(if (zero? n)
filled
(let [start-point (rand-nth filled)
next-point (rand-nth (neighbours start-point))]
(if (contains? (set filled) next-point)
(recur filled n)
(recur (cons next-point filled) (dec n))))))
</code></pre>
<p>But:</p>
<pre><code>user=> (time (flood-fill [[25 25]] 1250))
(time (flood-fill [[25 25]] 1250))
"Elapsed time: 8430.56 msecs"
([8 18] [43 40] [23 9] [38 40] ...
</code></pre>
<p>My <code>flood-fill2</code> does much better:</p>
<pre><code>user=> (time (flood-fill2 [25 25] 1250))
(time (flood-fill2 [25 25] 1250))
"Elapsed time: 257.361 msecs"
#{[34 33] [35 34] [36 3] [36 35] [38 5] [10 9] ...
</code></pre>
<p>But using <code>(time (flood-fill2 [500 500] 500000))</code> to fill 50% of a 1000 * 1000 tiles map takes forever (@ 100% CPU). I ended up killing that REPL.</p>
<p>Any performance suggestions? I tried to avoid many conversions from Sets to Vectors/Lists, but <code>rand-nth</code> needs a sequence and I couldn't find a nice "random set element" function.</p>
<p>Thanks for reading all of this.</p>
|
[] |
[
{
"body": "<p>I am a journeyman myself in clojure, and I don't have answers for all of your questions, but I have some input.</p>\n\n<p>I am not sure I fully understand your algorithm, but it seems you really have two loops rolled in to one. You have an inner loop looking for what could be the next tile to paint (without counting i), and an outer loop actually filling pixels and counting i down from n. Maybe it could be clearer if you separated these two somehow.</p>\n\n<p>And since you choose candidates on random, it will be random how long it takes for you to fill n tiles.</p>\n\n<p>I have found that when I do:</p>\n\n<pre><code>(loop [result ()\n input input-seq]\n (let [item (computation input)]\n (recur (conj result item) (rest input)))\n</code></pre>\n\n<p>It can often be re-written as:</p>\n\n<pre><code>(reduce computation input-seq)\n</code></pre>\n\n<p>(But I can't immediately see if this applies to your function)</p>\n\n<p>Have you considered implementing this using a 2d array of tiles, instead of a list of coordinates?</p>\n\n<p>A couple of other issues:</p>\n\n<ul>\n<li>you can create a function which always returns true with: (constantly true)</li>\n<li>I really like the use of (for (map +)) for vector addition, but you can use (mapv) instead of (vector (map))</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-16T06:21:43.823",
"Id": "23980",
"ParentId": "20028",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T17:39:20.873",
"Id": "20028",
"Score": "3",
"Tags": [
"optimization",
"functional-programming",
"clojure"
],
"Title": "Idiomatic Clojure? Performant & functional enough?"
}
|
20028
|
<p>I'm currently using SciPy's mode function to find the most occurring item in different iterable objects. I like the mode function because it works on every object type I've thrown at it (strings, <code>float</code>s, <code>int</code>s).</p>
<p>While this function seems reliable, it is very slow on bigger lists:</p>
<pre><code>from scipy.stats import mode
li = range(50000)
li[1] = 0
%timeit mode(li)
1 loops, best of 3: 7.55 s per loop
</code></pre>
<p>Is there a better way to get the mode for a list? If so, would the implementation be different depending on the item type?</p>
|
[] |
[
{
"body": "<p>Originally I thought you must have been doing something wrong, but no: the <code>scipy.stats</code> implementation of <code>mode</code> scales with the number of unique elements, and so will behave very badly for your test case.</p>\n\n<p>As long as your objects are hashable (which includes your three listed object types of strings, floats, and ints), then probably the simplest approach is to use <a href=\"http://docs.python.org/2/library/collections.html#counter-objects\" rel=\"noreferrer\">collections.Counter</a> and the <code>most_common</code> method:</p>\n\n<pre><code>In [33]: import scipy.stats\n\nIn [34]: li = range(50000); li[1] = 0\n\nIn [35]: scipy.stats.mode(li)\nOut[35]: (array([ 0.]), array([ 2.]))\n\nIn [36]: timeit scipy.stats.mode(li)\n1 loops, best of 3: 10.7 s per loop\n</code></pre>\n\n<p>but</p>\n\n<pre><code>In [37]: from collections import Counter\n\nIn [38]: Counter(li).most_common(1)\nOut[38]: [(0, 2)]\n\nIn [39]: timeit Counter(li).most_common(1)\n10 loops, best of 3: 34.1 ms per loop\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T22:00:26.980",
"Id": "32001",
"Score": "1",
"body": "Wow! What an improvement!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T21:28:59.897",
"Id": "20033",
"ParentId": "20030",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "20033",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T19:33:13.343",
"Id": "20030",
"Score": "3",
"Tags": [
"python",
"python-2.x"
],
"Title": "Finding the mode of an array/iterable"
}
|
20030
|
<p>I am writing a function for a rotating navigation with JS and jQuery. I am using a plugin called jQuery transit for animating rotation. The code works, but it is very long for such a simple function. Is there any way this can be improved?</p>
<pre><code>var rotation = 0;
$('nav ul li a').bind('click', function() {
'use strict';
var item = $(this).parent();
var itemI = item.index();
var navAll = $(this).parents('ul');
var condition = rotation + '_' + itemI;
switch(condition)
{
case '0_0':
//do nothing
break;
case '0_1':
navAll.transition({rotate: '-=90deg'});
$('nav ul li a').transition({rotate:'90deg'});
rotation = 270;
break;
case '0_2':
navAll.transition({rotate: '-=180deg'});
$('nav ul li a').transition({rotate:'180deg'});
rotation = 180;
break;
case '0_3':
navAll.transition({rotate: '+=90deg'});
$('nav ul li a').transition({rotate:'-90deg'});
rotation = 90;
break;
case '90_0':
navAll.transition({rotate: '0deg'});
$('nav ul li a').transition({rotate:'0deg'});
rotation = 0;
break;
case '90_1':
navAll.transition({rotate: '-90deg'});
$('nav ul li a').transition({rotate:'90deg'});
rotation = 270;
break;
case '90_2':
navAll.transition({rotate: '+=90deg'});
$('nav ul li a').transition({rotate:'-180deg'});
rotation = 180;
break;
case '90_3':
break;
case '180_0':
navAll.transition({rotate: '0deg'});
$('nav ul li a').transition({rotate:'0deg'});
rotation = 0;
break;
case '180_1':
navAll.transition({rotate: '-90deg'});
$('nav ul li a').transition({rotate:'90deg'});
rotation = 270;
break;
case '180_2':
//do nothing
break;
case '180_3':
navAll.transition({rotate: '-=90deg'});
$('nav ul li a').transition({rotate:'-90deg'});
rotation = 90;
break;
case '270_0':
navAll.transition({rotate: '0deg'});
$('nav ul li a').transition({rotate:'0deg'});
rotation = 0;
break;
case '270_1':
//do nothing
break;
case '270_2':
navAll.transition({rotate: '-=90deg'});
$('nav ul li a').transition({rotate:'180deg'});
rotation = 180;
break;
case '270_3':
navAll.transition({rotate: '-=180deg'});
$('nav ul li a').transition({rotate:'-90deg'});
rotation = 90;
break;
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T20:39:16.333",
"Id": "31998",
"Score": "0",
"body": "Just realized that the `$('nav ul li a')` should be put in a variable. Any other suggestions?"
}
] |
[
{
"body": "<p>Instead of that complex <code>switch</code> statement, I'd just use an option object:</p>\n\n<pre><code>var allLinks = $('nav ul li a');\nvar rotation = 0;\n\n$('nav').on('click', 'ul li a', function() {\n 'use strict';\n var $this = $(this);\n var item = $this.parent();\n var navAll = $this.parents('ul');\n\n var option = {\n '0_1': {\n rotateAll: '-=90deg',\n rotateThis: '90deg',\n rotation: 270\n },\n '0_2': {\n rotateAll: '-=180deg',\n rotateThis: '180deg',\n rotation: 180\n }\n // Add them all here\n }[ rotation + '_' + item.index() ];\n\n if ( option ) {\n navAll.transition({rotate: option.rotateAll});\n allLinks.transition({rotate: option.rotateThis});\n rotation = option.rotation;\n }\n}\n</code></pre>\n\n<p>There are 2 more things to consider:</p>\n\n<ol>\n<li>Are you sure you really need that <code>nav ul li a</code> selector? Wouldn't <code>nav a</code> do the job just the same? While we're at it, why are you listening to the click on the <code>a</code> elements, and then find the <code>li</code> via <code>.parent()</code>? Can't you just listen to the <code>click</code> event on the <code>li</code>s themselves?</li>\n<li>Is there any method to that configuration? I wasn't able to deduce any algorithm from what you've provided, but I'm sure there is. You'd be better off calculating it on the fly, if possible.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T02:10:51.720",
"Id": "32039",
"Score": "0",
"body": "one methodical aspect I can see: `rotation = (3 - item.index()) * 90`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T00:47:25.377",
"Id": "20036",
"ParentId": "20031",
"Score": "2"
}
},
{
"body": "<p>You could do something like this, although there is a slight risk of making the code more cryptic than it is already.</p>\n\n<pre><code>var rotation = 0;\nvar r1Options = [[undefined, 0, 0, 0],\n [-90, -90, -90, undefined],\n [-180, 90, undefined, -180],\n [90, undefined, -90, -180]],\n r2Options = [[undefined, 0, 0, 0],\n [90, 90, 90, undefined],\n [180, -180, undefined, 180],\n [-90, undefined, -90, -90]];\n\nfunction rotateString(degs) {\n var sign = '';\n if (degs < 0) sign = '-';\n else if (degs > 0) sign = '+';\n return sign + '=' + Math.abs(degs) + 'deg';\n}\n$('nav ul li a').bind('click', function() {\n 'use strict';\n var item = $(this).parent();\n var itemI = item.index();\n var navAll = $(this).parents('ul');\n var r1 = r1Options[itemI][rotation / 90],\n r2 = r2Options[itemI][rotation / 90];\n if (r1 != undefined && r2 != undefined) {\n navAll.transition({rotate: rotateString(r1)});\n $('nav ul li a').transition({rotate: rotateString(r2)});\n rotation = (3 - itemI) * 90;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T02:59:19.390",
"Id": "20052",
"ParentId": "20031",
"Score": "1"
}
},
{
"body": "<p>I tried to deduce what it is that you're doing, and what I came up with is that you have four items arranged like a cross and you rotate it when one is clicked so that item is on top. You're also rotating each item, individually, so they continue to be upright during the rotation.</p>\n\n<p>If that's what you have, I think this code should do the same thing. It's set to work with a variable number of items, so, in theory, you should be able to add to or remove from the set and the rotations will adjust.</p>\n\n<p><a href=\"http://jsfiddle.net/WxpkG/\" rel=\"nofollow\">Here is a demo.</a></p>\n\n<p>The items in the <code><ul></code> are arranged in a circle via CSS.</p>\n\n<pre><code><ul>\n <li id=\"a\">0</li>\n <li id=\"b\">1</li>\n <li id=\"c\">2</li>\n <li id=\"d\">3</li>\n <li id=\"e\">4</li>\n <li id=\"f\">5</li>\n <li id=\"g\">6</li>\n <li id=\"h\">7</li>\n</ul>\n</code></pre>\n\n<p>The JavaScript:</p>\n\n<pre><code>var idx = 0,\n $lis = $('li'),\n len = $lis.length,\n center = (len - 1) / 2,\n halfLen = len / 2,\n degChg = 360 / len,\n $ul = $('ul');\n\n$ul.on('click', 'li', function() {\n\n var $this = $(this),\n newIdx = $this.index(),\n chg = getPositionChg(idx, newIdx) * degChg;\n\n $ul.transition({rotate: '-=' + chg + 'deg'});\n // couldnt get this to work without using\n // the .each() method\n $lis.each(function() {\n $(this).transition({rotate: '+=' + chg + 'deg'});\n });\n idx = newIdx;\n});\n\nfunction getPositionChg(curIdx, nextIdx) {\n if (curIdx < center) {\n // if curIdx is left of center and change does not\n // cross the 0 index (is clockwise)\n if (nextIdx > curIdx + halfLen) {\n return nextIdx - len - curIdx;\n } else {\n return nextIdx - curIdx;\n } \n } else {\n // if curIdx is right of center and change does\n // cross the 0 index\n if (nextIdx <= curIdx - halfLen) {\n return len - curIdx + nextIdx;\n } else {\n return nextIdx - curIdx;\n }\n }\n}\n\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T19:15:41.683",
"Id": "32222",
"Score": "0",
"body": "I'd recommend extracting the position of the list elements as well so that is dynamically generated with the script."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T10:42:16.237",
"Id": "20055",
"ParentId": "20031",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T19:35:00.387",
"Id": "20031",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"animation"
],
"Title": "Animating rotations using jQuery"
}
|
20031
|
<p>Background:</p>
<p>A synchronous grammar is a like two context-free grammars connected in parallel. It is used for translation. For example, here is a small synchronous grammar that can be used for translating between natural language text and semantic representation:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>== {verb} ==
* I offer {noun}. / OFFER({noun})
* Will you accept {noun}? / QUERY({noun})
* I offer no company car. / OFFER(Leased Car=Without leased car)
== {noun} ==
* {number} % pension / Pension Fund={number}%
* A salary of {number} NIS / Salary={number}
* A company car / Leased Car=With leased car
</code></pre>
</blockquote>
<p>The headings ({verb}, {noun}) are the nonterminals of the grammar. under each nonterminal is a list of translations enabled by this nonterminal.</p>
<p>Starting from the nonterminal {verb}, we can create, from the above grammar, the following 7 translations:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>I offer no company car. => [OFFER(Leased Car=Without leased car)]
I offer A company car. => [OFFER(Leased Car=With leased car)]
Will you accept A salary of {number} NIS? => [QUERY(Salary={number})]
I offer {number} % pension. => [OFFER(Pension Fund={number}%)]
I offer A salary of {number} NIS. => [OFFER(Salary={number})]
Will you accept A company car? => [QUERY(Leased Car=With leased car)]
Will you accept {number} % pension? => [QUERY(Pension Fund={number}%)]
</code></pre>
</blockquote>
<p>The translations are many-to-many (i.e. there can be more than one translation to each source string, and vice-versa). So, each set of translations for a specific nonterminal is represented by a multimap (we use a class <code>ValueSetMap<String, String></code> for representing a many-to-many map). An entire grammar is represented by a map of such multimaps: <code>Map<String, ValueSetMap<String, String>></code>. It maps a nonterminal to its multimap of translations.</p>
<p>Here is some Java code I wrote, for expanding a grammar into a flat multimap of translations. It works for the above example and some more complicated examples, but I wonder if it really covers all cases.</p>
<pre class="lang-java prettyprint-override"><code>public class GrammarExpander {
public GrammarExpander(Map<String, ValueSetMap<String,String>> grammarMap) {
this.grammarMap = grammarMap;
this.expandedGrammarMap = new HashMap<String,ValueSetMap<String,String>>();
}
public ValueSetMap<String, String> expand(String startNonterminal, int maxDepth) {
if (expandedGrammarMap.containsKey(startNonterminal))
return expandedGrammarMap.get(startNonterminal);
Set<String> nonterminals = grammarMap.keySet();
ValueSetMap<String, String> translationsFromStartNonterminal =
grammarMap.get(startNonterminal);
if (translationsFromStartNonterminal==null)
throw new NullPointerException("No translations from startNonterminal " +
startNonterminal);
// don't expand nonterminal anymore - prevent infinite recursion
if (maxDepth<=0)
return translationsFromStartNonterminal;
for (String nonterminal: nonterminals) { // expand each nonterminal in turn
ValueSetMap<String,String> newTranslations =
new SimpleValueSetMap<String,String>();
for (String source: translationsFromStartNonterminal.keySet()) {
for (String target: translationsFromStartNonterminal.get(source)) {
// source contains nonterminal - expand it recursively
if (source.contains(nonterminal) || target.contains(nonterminal)) {
ValueSetMap<String, String> expansions =
this.expand(nonterminal, maxDepth-1);
for (String expansionSource: expansions.keySet())
for (String expansionTarget: expansions.get(expansionSource))
newTranslations.put(
source.replace(nonterminal, expansionSource),
target.replace(nonterminal, expansionTarget));
} else {
newTranslations.put(source, target);
}
}
}
translationsFromStartNonterminal = newTranslations;
}
expandedGrammarMap.put(startNonterminal, translationsFromStartNonterminal);
return translationsFromStartNonterminal;
}
/*
* protected zone
*/
protected Map<String, ValueSetMap<String, String>> grammarMap;
protected Map<String, ValueSetMap<String, String>> expandedGrammarMap;
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>NullPointerException</p>\n\n<p>It should be IllegalArgumentException.\nConsider just returning empty collection of expansion.\nIt greatly improves composeability of your code.</p>\n\n<p>Think about making invalid states unrepresentable.\n(though I cannot think a trivial way of doing this, in this case.)</p></li>\n<li><p>In the following statement translation is recursively expanded \nif either of <code>source</code> and <code>target</code> contains <code>nonterminal</code>.\nWhereas the comment says that\nthe translation is expanded if <code>source</code> contains <code>nonterminal</code></p>\n\n<pre><code>// source contains nonterminal - expand it recursively\nif (source.contains(nonterminal) || target.contains(nonterminal)) { \n</code></pre>\n\n<p>Misleading comments are often a sign of a buggy algorithm.</p>\n\n<p>Moreover in the given examples it is observed that \n<code>source</code> contains a <code>nonterminal</code> iff <code>target</code> also contains <code>nonterminal</code></p>\n\n<p>Maybe this should be a constraint of the grammar.</p></li>\n<li><p>Moreover <code>source.contains(nonterminal)</code> suggest that\nyou implicitly assume <code>nonterminal</code>s, that is the keys of <code>grammarMap</code>\nstart and end with \"{\", \"}\". and nonterminal names do not contain \"{}\", \nand there may be more constraints. \nConsider keys: <code>noun, pronoun, {pronoun}, {{noun}}</code>. See the looming trouble?\nThe keys should be validated in the creation of the <code>grammar</code>.\nAnd some javadoc etc comments will also be helpful if not sufficient.\nEven if you will be the only <strong>user</strong> ever of this code, \nyou will forget these implicit assumptions <strong>in no time</strong>.</p></li>\n<li><p>In according with above advice consider using abstract data types\ninstead of meaningless primitive types (java.util.Collection, String, etc.)\nsuch that your multilevel loops read more something like</p>\n\n<pre><code>for (Translation translation : translations) {\n grammar.substituteOneLevel(translation)\n}\n\n// in grammar.substituteOneLevel(translation)\n for (Nonterminal nonterminal : translation.getNonterminals()) {\n for (Expansion expansion : grammar.getExpansions(nonterminal)) { \n result.add(translation.substitute(nonterminal, expansion);\n }\n }\n</code></pre>\n\n<p>or some such..</p>\n\n<p>Apart from improved readability and clarity of you business(academic) logic \nby using language (nouns and verbs) of from your domain;\nyou can also disallow a <code>grammar</code> to have <code>expansion</code>s \nthat contain <code>nonterminal</code>s that the <code>grammar</code> itself does not contain.\n(your NullPointerException..)</p></li>\n<li><p>Efficiency-wise, one of my objections is the:</p>\n\n<pre><code>for (String nonterminal: nonterminals) { // expand each nonterminal in turn\n</code></pre>\n\n<p>why try to expand terminals that is not contained in any of the \ncurrent translations?</p></li>\n<li><p>Expanding a non-terminal for a fixed number of steps \ndoes not seem very useful.\nWhat is your use case? \nDo you have a running test case, that demonstrates \nthe setup of the grammar and the manner it will be used?</p></li>\n<li><p>Even if <em>Expanding a non-terminal for a fixed number of steps</em> is what you want,\nyou probably will also want some indication of whether you have exhausted \nall possible expansions. (whether none of your expansions contain nonterminals)</p></li>\n<li><p>Of course possibly more useful queries with a these kind of grammars are:</p>\n\n<ul>\n<li>What are possible translations of this input?</li>\n<li>What are possible inputs that translate to this output?</li>\n<li>Is this grammar finite?</li>\n</ul></li>\n<li><p>Why don't you use a prolog or lisp variant? \nHave a look at Clojure. It is a lisp variant that runs on JVM. \nIt has a logic library, which I believe can be more useful than java.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T07:24:01.183",
"Id": "32093",
"Score": "0",
"body": "Wow, what a keen eye! 1-3 accepted. 4 true, although I am a Javascript guy, I am used to creating objects on the fly without having to define their class in advance. 5 True, I can check before expanding a nonterminal whether it actually appears somewhere. 6-7 I don't mean to expand a fixed number of steps - but a maximum number of steps. The maximum is to prevent infinite recursion in case the grammar is recursive, i.e. \"== {noun} == very {noun} -> very {noun}\", which will generate \"very very {noun} -> very very {noun}\", etc. 8-9 Thanks, I will look."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T09:55:50.210",
"Id": "20054",
"ParentId": "20041",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20054",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T10:12:35.347",
"Id": "20041",
"Score": "2",
"Tags": [
"java",
"grammar"
],
"Title": "Expanding a synchronous grammar"
}
|
20041
|
<p>In chapter 45 of <em>Learn Python the Hard Way</em>, the author basically says: "Ok, go figure out how to make a text based game"</p>
<p>Before I get too far in this I just want to be sure I'm not doing anything stupid. The code as it is is fairly functional just not too many rooms.</p>
<p>I am running this under Windows:</p>
<pre><code>from sys import exit
from random import randint
import curses,random
screen = curses.initscr()
screen.border(0)
width = screen.getmaxyx()[1]
height = screen.getmaxyx()[0]
size = width*height
char = [" ", ".", ":", "^", "*", "x", "s", "S", "#", "$"]
b = []
curses.start_color()
curses.init_pair(1,0,0)
curses.init_pair(2,1,0)
curses.init_pair(3,3,0)
curses.init_pair(4,4,0)
global x
x = 1
def cls():
screen.clear()
screen.border(0)
screen.addstr(20,1,">")
screen.refresh()
def info_special(message,message2):
screen.move(19,x)
screen.clrtoeol()
screen.addstr(19,x,message,curses.A_BOLD)
screen.addstr(message2)
screen.move(20,3)
screen.clrtoeol()
screen.border(0)
screen.refresh()
def info(message):
screen.move(19,x)
screen.clrtoeol()
screen.addstr(19,x,message)
screen.move(20,3)
screen.clrtoeol()
screen.border(0)
screen.refresh()
def help():
screen.move(19,x)
screen.clrtoeol()
string = "Commands:"
for j in commands:
string = "%s\n\t %s" % (string,j)
screen.addstr(10,x,string)
screen.move(20,3)
screen.clrtoeol()
screen.border(0)
screen.refresh()
def intro():
curses.curs_set(0)
screen.clear
welcome = """_ _ ____ __ ___ __ _ _ ____
/ )( \( __)( ) / __)/ \ ( \/ )( __)
\ /\ / ) _) / (_/\( (__( O )/ \/ \ ) _)
(_/\_)(____)\____/ \___)\__/ \_)(_/(____)
"""
dragon = """ ______________
,===:'., `-._
`:.`---.__ `-._
`:. `--. `.
\. `. `.
(,,(, \. `. ____,-`.,
(,' `/ \. ,--.___`.'
, ,' ,--. `, \.;' `
`{D, { \ : \;
V,,' / / //
j;; / ,' ,-//. ,---. ,
\;' / ,' / _ \ / _ \ ,'/
\ `' / \ `' / \ `.' /
`.___,' `.__,' `.__,'
"""
for i in range(size+width+1): b.append(0)
while 1:
for i in range(int(width/9)): b[int((random.random()*width)+width*(height-1))]=65
for i in range(size):
b[i]=int((b[i]+b[i+1]+b[i+width]+b[i+width+1])/4)
color=(4 if b[i]>15 else (3 if b[i]>9 else (2 if b[i]>4 else 1)))
if(i<size-1): screen.addstr( int(i/width),
i%width,
char[(9 if b[i]>9 else b[i])],
curses.color_pair(color) | curses.A_BOLD )
screen.addstr(0,1,welcome,curses.color_pair(3))
screen.addstr(dragon,curses.color_pair(4))
screen.refresh()
screen.timeout(30)
if (screen.getch()!=-1): break
screen.timeout(0)
curses.curs_set(1)
class Monster(object):
def __init__(self,name,strength,location):
self.sname = name.split(' ')[0]
self.name = name
self.strength = strength
self.location = location
class Weapon(object):
def __init__(self,name,strength, location):
self.sname = name.split(' ')[0]
self.name = name
self.strength = strength
self.location = location
class Character(object):
def __init__(self,name,location):
self.name = name
self.location = location
self.inv = []
def look(self):
cls()
place = self.location
string = "Current Room:"
screen.addstr(1,x,string,curses.A_REVERSE)
string = " %s" % place.name
screen.addstr(string)
description = place.description.split('\n')
i = 2 # starting line
for line in description:
screen.addstr(i,x,line)
i += 1
try:
items = place.items
for item in items:
string = "The %s is %s" % (item.name,item.location)
screen.addstr(i+1,x,string)
except:
pass
def inventory(self):
i = 10
while i <= 18:
screen.move(i,x)
screen.clrtoeol()
i += 1
screen.move(19,x)
screen.clrtoeol()
screen.addstr(9,x,"Your inventory contains:")
i = 10 #starting line for list
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
if not len(self.inv):
string = '\tNOTHING!'
screen.addstr(i,x,string,curses.color_pair(1))
else:
for item in self.inv:
string2 = item.name.split(' ')
string1 = "\t%s " % string2.pop(0)
string2 = ' '.join(string2)
screen.addstr(i,x,string1,curses.color_pair(1))
screen.addstr(string2)
i += 1
screen.move(20,3)
screen.clrtoeol()
screen.border(0)
screen.refresh()
class Room(object):
def __init__(self,name,description):
self.name = name
self.description = description
self.paths = []
self.items = []
Start = Room('Start',"""
You are in a dark room.
There is a door to the West and East.
""")
BearRoom = Room('Bear Room',"""
There is a bear!
""")
TreasureRoom = Room('Treasure Room',"""
Treasure has Been Stolen.
The room is empty!
""")
Sword = Weapon('Sword of Truth',5, 'Propped up against the wall')
Lantern = Weapon('Lantern',100, 'In Inventory')
#[n,w,s,e]
Start.paths = [0,BearRoom,0,TreasureRoom]
Start.items = []
BearRoom.paths = [0,0,0,Start]
BearRoom.items = [Sword]
TreasureRoom.paths = [0,Start,0,0]
TreasureRoom.items = []
character = Character('Bob Loblaw',Start)
character.inv = [Lantern] #starting items
commands = ['go north,west,south, or east','take item','attack creature','drop item','(l)ook = Examine room','(i)nventory = get inventory','help = this list']
intro()
character.look()
while True:
command = screen.getstr(20,3,80)
command = command.split(' ')
if command[0] == "go":
try:
if command[1] == "north":
if character.location.paths[0] == 0:
string = "You cannot go that way."
info(string)
else:
character.location = character.location.paths[0]
character.look()
elif command[1] == "west":
if character.location.paths[1] == 0:
string = "You cannot go that way."
info(string)
else:
character.location = character.location.paths[1]
character.look()
elif command[1] == "south":
if character.location.paths[2] == 0:
string = "You cannot go that way."
info(string)
else:
character.location = character.location.paths[2]
character.look()
elif command[1] == "east":
if character.location.paths[3] == 0:
string = "You cannot go that way."
info(string)
else:
character.location = character.location.paths[3]
character.look()
else:
string = "I Don't Understand the direction: %s" % command[1]
info(string)
except:
string = "I need a direction such as north,east,south or west."
info(string)
elif command[0] == "take":
try:
if command[1]:
if character.location.items:
i = 0
for item in character.location.items:
if command[1] in (item.sname,item.sname.lower()):
character.inv.append(item)
del character.location.items[i]
string = "%s " % item.name
string2 = "added to inventory"
info_special(string,string2)
else:
string = "Can't Find item: %s" % command[1]
info(string)
i += 1
else:
string = "There are no items to take in this room."
info(string)
except:
string = "Take What?"
info(string)
elif command[0] == "drop":
try:
if command[1]:
i = 0
for item in character.inv:
if command[1] in (item.sname,item.sname.lower()):
del character.inv[i]
character.location.items.append(item)
item.location = "On the floor."
string = "%s " % item.name
string2 = "dropped"
info_special(string,string2)
else:
string = "Can't Find item: %s" % command[1]
info(string)
i += 1
except:
string = "Drop What?"
info(string)
elif command[0] in ('inv','inventory','i'):
character.inventory()
elif command[0] in ("look","l"):
character.look()
elif command[0] in ('help','commands'):
help()
elif command[0] == "attack":
try:
pass
except:
pass
elif command[0] in ("end","quit","exit","q"):
screen.clear()
screen.refresh()
curses.endwin()
print "Sorry to see you go so soon."
exit(0)
else:
string = "I Dont Understand the command: %s" % command[0]
info(string)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T09:38:46.133",
"Id": "32011",
"Score": "0",
"body": "Comments are always nice. `color=(4 if b[i]>15 else (3 if b[i]>9 else (2 if b[i]>4 else 1)))` isn't nice, nor are `try` and `if` statements that are nested to a depth of five. Try condensing your repetitive code with functions and add some comments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T11:05:10.707",
"Id": "32012",
"Score": "0",
"body": "Trying to get your code reviewed as you start out is hardly learning Python the hard way. It's essential that you made some mistakes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T11:44:18.173",
"Id": "32013",
"Score": "0",
"body": "@Blender Yea im always bad at commenting code.. trying to improve appreciate you pointing it out to remind myself yet again\n\nas far as the code in intro goes its a ANSI animation so its going to look messy no matter how its written lol"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T13:59:12.863",
"Id": "32020",
"Score": "0",
"body": "if you are going to use ascii art in your code, you should probably consider using a library of text documents you can read from instead of placing the directly into your code. actually, you should do that anyway, and have parts of the dialogue or game information on text documents that are read by the game when needed."
}
] |
[
{
"body": "<p>I don't think having <a href=\"http://docs.python.org/2/reference/simple_stmts.html#the-global-statement\" rel=\"nofollow\"><code>global</code></a> at the module level makes sense.</p>\n\n<p>You should have it in a function/method if you need, but I would advise against having global variables at all, especially undocumented and called <code>x</code>.</p>\n\n<p>Also try to avoid <code>except:</code> without specifying an exception class: it can suppress much more exceptions than you think can occur. Specify the kind of exception you actually are processing, like: <code>except AttributeError:</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T11:55:20.733",
"Id": "32014",
"Score": "0",
"body": "there was no need for the global not sure what I was thinking at the time, thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T12:00:07.003",
"Id": "32015",
"Score": "0",
"body": "I will definitely lookup more info on try and except I was mainly using try as a way to make sure that commands where entered is there a better way to do this? for example\n try:\n if command[1]:\nonly exists to make sure that command[1] exists without crashing the program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T12:09:43.400",
"Id": "32016",
"Score": "0",
"body": "don't know why I didnt do this before but I removed the try/except and replaced with if len(command) > 1: to check for enough parameters... makes a lot more sense :p"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T12:40:38.670",
"Id": "32018",
"Score": "0",
"body": "@Dreded Both make sense, it's a viable use of `try`, but you need to avoid catching _all_ exceptions if you don't mean it. `except IndexError` is fine for the case of retrieving a list item."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T09:46:15.080",
"Id": "20043",
"ParentId": "20042",
"Score": "3"
}
},
{
"body": "<p>My main pointers are that the whole game should be a class, so you can have members (<code>self.VARIABLE</code>) and not have to pass them on to too many functions.</p>\n\n<p>You should restructure your <code>commands</code> to be a dictionary, where the key is the command (as the user inputs it) and then a list or another dict (or class) which would have the displayed command, and then a pointer to its method of what it does.</p>\n\n<p>This way when you modify commands dynamically based on location, you do not need a function for each location. It also lets you make a more robust game.</p>\n\n<p>There are a few other minor concerns, but they are mostly opinions, and not \"mistakes\" that you are making or anything. Try to read about making things more generic, and about class inheritance.</p>\n\n<p>You requested an example:</p>\n\n<pre><code>def attack(args):\n print \"recieved attack command with args: %s\" % args\n\ndef move(args):\n print \"recieved move command with args: %s\" % args\n\ndef inspect(args):\n print \"recieved inspect command with args: %s\" % args\n\ncommands = {\n 'attack': {'description': \"makes an attack\", 'display': 'Attack', 'function': attack},\n 'move': {'description': \"moves somewhere\", 'display': 'Move', 'function': move},\n 'inspect': {'description': \"inspect something\", 'display': 'Inspect', 'function': inspect}}\n\n\n\ndef show_commands():\n for command, specs in commands.items():\n print \"%s: %s, %s\" % (command, specs['display'], specs['description'])\n\ndef get_command():\n user_input = raw_input('choose a command: ')\n command, args = user_input.split(' ', 1)\n if command in commands:\n commands[command]['function'](args)\n else:\n print 'command not recognized'\n</code></pre>\n\n<p>Simple usage:</p>\n\n<pre><code>>>> show_commands()\nattack: Attack, makes an attack\nmove: Move, moves somewhere\ninspect: Inspect, inspect something\n>>> get_command()\nchoose a command: attack monster\nrecieved attack command with args: monster\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T11:53:13.463",
"Id": "32017",
"Score": "0",
"body": "if its not to much bother could you expand on what you mean about the commands?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T10:02:36.363",
"Id": "20044",
"ParentId": "20042",
"Score": "4"
}
},
{
"body": "<p>Well regarding the calling of all the different commands you might want to first of all wrap the whole thing into a class and then define the commands in different methods like this:</p>\n\n<pre><code>def command_go(self, direction, *args):\n # do something here\n # ...\n\ndef command_take(self, item, *args):\n # take the item or whatever\n\n# And so on ...\n</code></pre>\n\n<p>And then when they need to be called do something like the following:</p>\n\n<pre><code>command = screen.getstr(20,3,80)\ncommand = command.split(' ')\nmethod = \"command_\" + command[0] # name of the method to be called for this command\nif hasattr(self, method):\n # The method does exist, so call it using the command's args\n getattr(self, method)(*command[1:])\n\nelse:\n string = \"I Dont Understand the command: %s\" % command[0]\n info(string)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T17:41:47.737",
"Id": "20047",
"ParentId": "20042",
"Score": "1"
}
},
{
"body": "<p>First off, I love the animation at the start!</p>\n\n<ul>\n<li><p>char and b don't need to be global, they're only used in the flame animation. You also need to pick better names, say <code>flame_animation_parts</code>, <code>top_line</code>.</p></li>\n<li><p>Use lowercase letters for the start of variables/functions (Lantern, Start etc), Uppercase for classes.</p></li>\n<li><p>The entire main loop of the program is in the global namespace - it's a <strong>very</strong> good idea to separate this out in a function (say, <code>playgame</code>) and use the following idiom:</p>\n\n<pre><code>if __name__ == \"__main__\":\n playgame()\n</code></pre>\n\n<p>If nothing else, it will stop the program running if you import it. It also highlights that you have relevant code both at the start and the end of the file.</p></li>\n<li><p>I'm also going to suggest wrapping the <code>playgame</code> call into an try...except block so the screen can be cleaned up if an error occurs. Note that I'm catching everything, which shouldn't be done normally (as Lev's advice), but I'm reraising it afterwards.</p>\n\n<pre><code>if __name__ == \"__main__\":\n try:\n playgame()\n except:\n curses.endwin()\n raise\n</code></pre></li>\n<li><p>The main loop runs continually, without pausing for any input!!!! This suggests that you haven't actually run it... You may want to have a look at the <a href=\"http://docs.python.org/dev/library/curses.html#module-curses.textpad\" rel=\"nofollow\">curses.textpad</a> module and use this for input (turn echoing off!).</p></li>\n<li><p>The command should be 'normalised' to lowercase, to avoid checking against uppercase forms.</p></li>\n<li><p>Since your commands are (mostly) <code>verb noun</code>, rather than checking against command<a href=\"http://docs.python.org/dev/library/curses.html#module-curses.textpad\" rel=\"nofollow\">1</a> in a try block, try something like:</p>\n\n<pre><code>verb = command[0] if len(command) > 0 else \"\"\nnoun = command[1] if len(command) > 1 else \"\"\n</code></pre></li>\n<li><p>The 'go' command uses repeated code for each direction. you might want to consider either having a dictionary translating word to direction, </p>\n\n<pre><code>NORTH = 0\nWEST = 1\nSOUTH = 2\nEAST = 3\n\ndir_to_offset['west'] = WEST # etc\n</code></pre>\n\n<p>or (preferably, imho) having the location.paths as a dictionary itself. This can then be referenced directly by the command.</p>\n\n<pre><code>start.paths = { 'west': BearRoom, 'east': TreasureRoom }\n</code></pre></li>\n<li><p>You may want to add paths and items parameters to the Room constructor, to avoid adding them in later. But the paths in particular will mean changing how you deal with them (can't use objects directly).</p></li>\n<li><p>When you start, you have a blank screen without any description!</p></li>\n<li><p>There are lots of other \"magic numbers\" around - these need to be minimised, otherwise it's likely you'll cause a very hard to track error. Most of these are coordinates, so define constants and reference rows as offsets from these:</p>\n\n<pre><code>ROOM_LINE = 2\nINVENTORY_START_LINE = 9\nINFO_LINE = 19\nCOMMAND_LINE = 20\n</code></pre>\n\n<p>Alternatively, you could look at using derwin and subwin to split the screen up into sections (command section, room description section etc), so after that all your coordinates are (0,0)</p></li>\n<li><p>Once you've got it working and tidied up, try creating a class that will wrap around curses, so that your main program isn't cluttered up so much with curses calls.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T17:03:28.600",
"Id": "20066",
"ParentId": "20042",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20044",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T09:34:30.697",
"Id": "20042",
"Score": "4",
"Tags": [
"python",
"adventure-game"
],
"Title": "\"You are in a dark room; learn how to make a text based game\""
}
|
20042
|
<p>Would you have any suggestions improvements for the below functions classes ?</p>
<p>Ok here how do i make a registered member login</p>
<pre><code> HttpCookie LoginInfo = new HttpCookie("LoginInfo");
LoginInfo.Values["UserName"] = srUserName;
LoginInfo.Values["Password"] = srPassword;
LoginInfo.Values["selectedLanguage"] = srSelectedLanguage;
Response.Cookies.Add(LoginInfo);
</code></pre>
<p>Here how do i check visitor is logged in or not</p>
<pre><code>public static void controlOfLoginStatus()
{
string srQuery = "";
string srUserName = "";
string srPassword = "";
string srLang = "";
if (HttpContext.Current.Session["UserId"] == null)
{
if (HttpContext.Current.Request.Cookies["LoginInfo"] != null)
{
try
{
srUserName = HttpContext.Current.Request.Cookies["LoginInfo"]["UserName"].ToString();
srPassword = HttpContext.Current.Request.Cookies["LoginInfo"]["Password"].ToString();
srLang = HttpContext.Current.Request.Cookies["LoginInfo"]["selectedLanguage"].ToString();
}
catch
{
}
}
string srUserIdTemp = csPublicFunctions.ReturnUserIdUsernamePassword(srUserName, srPassword);
if (srUserIdTemp == "0")
{
HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Redirect("Login");
}
else
{
csPublicFunctions.insertIntoOnlineUsers(srUserIdTemp, HttpContext.Current.Session.SessionID);
HttpContext.Current.Session["UserId"] = srUserIdTemp;
if (HttpContext.Current.Session["lang"] == null)
HttpContext.Current.Session["lang"] = srLang;
}
}
srQuery = "SELECT UserId " +
" FROM BannedUsers" +
" WHERE UserId = " + HttpContext.Current.Session["UserId"].ToString();
using (DataTable dtTemp = DbConnection.db_Select_DataTable(srQuery))
{
if (dtTemp.Rows.Count > 0)
{
HttpContext.Current.Response.Redirect("exit.aspx");
}
}
}
</code></pre>
<p>Here how do i log-out</p>
<pre><code>public static void exitLogout()
{
string srQuery = "delete from OnlineUsers where UserId=" + HttpContext.Current.Session["UserId"].ToString();
DbConnection.db_Update_Delete_Query(srQuery);
try
{
HttpContext.Current.Session["UserId"] = "0";
HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
}
catch
{
}
try
{
HttpCookie LoginInfo = new HttpCookie("LoginInfo");
LoginInfo.Values["UserName"] = "21412zxcvzxc343245243vvc";
LoginInfo.Values["Password"] = "21412zxcvzxc343245243vvc";
LoginInfo.Values["selectedLanguage"] = "en";
HttpContext.Current.Response.Cookies.Add(LoginInfo);
}
catch
{
}
}
</code></pre>
<p><code>csPublicFunctions.ReturnUserIdUsernamePassword</code> uses parametrized queries so no possible risk of SQL injection</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T02:11:35.630",
"Id": "32040",
"Score": "1",
"body": "Lose the \"Hungarian Notation\" variable names: http://msdn.microsoft.com/en-us/library/vstudio/ms229045.aspx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-04T15:10:59.657",
"Id": "34159",
"Score": "0",
"body": "Does `ReturnUserIdUsernamePassword` use proper salted and expensive password hashing?"
}
] |
[
{
"body": "<p>In addition to losing the hungarian notation there are a few things worth mentioning:</p>\n\n<ol>\n<li>Don't use try-catch construction with empty 'catch' clause. It is almost always a bad idea to hide an exception if it was thrown. </li>\n<li>It would be better to check explicitly if the key is in the collection using appropriate methods. BTW exception handling is quite expensive speedwise and explicit checking will work faster.</li>\n<li>Try to refactor your controlOfLoginStatus() method into several distinct functions with more meaningful purpose.</li>\n<li>Refactor your database code into separate class.</li>\n<li>Use parameterized queries while working with database. It will save you from sql injections and it will make your queries run faster.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T00:07:20.220",
"Id": "20072",
"ParentId": "20048",
"Score": "4"
}
},
{
"body": "<p>Don't store the users password in a cookie. That's an unnecessary security risk.</p>\n\n<p>Create a new random session id to put there instead. That session id needs to be invalidated on the server on logout. Or if you want auto-login that crosses sessions, you still should create a token that doesn't depend on the user password.</p>\n\n<p>Additionally you should set the <code>Secure</code> and <code>HttpOnly</code> flags.</p>\n\n<ul>\n<li><code>Secure</code> prevents sending of the cookie over unencrypted connections i.e. it enforces <code>https</code> over <code>http</code>. This flag is essential to prevent an attacker on your network from sniffing the cookie.</li>\n<li><code>HttpOnly</code> prevents javascript from reading the cookie value. This reduces the impact of XSS vulnerabilities a bit.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-04T15:05:43.630",
"Id": "21295",
"ParentId": "20048",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T23:57:48.857",
"Id": "20048",
"Score": "0",
"Tags": [
"c#",
"asp.net",
"logging",
"session"
],
"Title": "ASP.net proper login - logout classes - control login status"
}
|
20048
|
<p>I have a dataframe with several columns. One of them is an user ID column, in this column, I have several ids that can be repeated several times.</p>
<p>What I want to do is remove the first ID, for instance:</p>
<pre><code>1,2,3,4,3,4,2,1,3,4,6,7,7
</code></pre>
<p>I would like to have an output like this:</p>
<pre><code>3,4,2,1,3,4,7
</code></pre>
<p>Where is what I have done:</p>
<pre><code>#find first duplicated of the each user
dup <- duplicated(results$user)
#create other data frame, every time vector is TRUE add the row to new dataframe
results1 <- NULL
for(i in 1:length(results$user)){
if (dup[i] == TRUE) {
rbind(results1, results[i,]) -> results1
}
}
</code></pre>
<p>Since I'm more used to think in Python, I have a feeling this is a very ugly solution for R. I would like to have some feedback, as well as some pointers on how to improve this piece of code.</p>
|
[] |
[
{
"body": "<p>Well after reading some stuffs, I've come to the conclusion that I could eliminate several lines and do this instead:</p>\n\n<pre><code>rbind(results1, results[dup,]) -> results1\n</code></pre>\n\n<p>It is much quicker and seems more efficient.</p>\n\n<p>However any suggestions or recommendations are welcome :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T10:45:32.993",
"Id": "20207",
"ParentId": "20053",
"Score": "0"
}
},
{
"body": "<p>Here's a more efficient solution:</p>\n\n<pre><code># an example data frame\nresults <- data.frame(user = c(1,2,3,4,3,4,2,1,3,4,6,7,7), a = 1)\n\n# the solution\nresults[duplicated(results$user), ]\n</code></pre>\n\n<p><em>How it works</em>: <code>duplicated</code> returns a logical vector indicating whether a value was also present at a preceding position in the vector (for each value of <code>results$user</code>).</p>\n\n<p>This logical index is used to choose the appropriate lines of the orginal data frame. This is achieved by using this vector as the first argument for <code>[</code> and using an empty second argument (to select all columns).</p>\n\n<p>The result:</p>\n\n<pre><code> user a\n5 3 1\n6 4 1\n7 2 1\n8 1 1\n9 3 1\n10 4 1\n13 7 1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-11T11:24:42.503",
"Id": "32693",
"Score": "0",
"body": "you're right! It is better. With R I have some tendency to do more complicated stuff.. Thank you for your response"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-10T13:29:23.767",
"Id": "20378",
"ParentId": "20053",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20378",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T09:46:59.753",
"Id": "20053",
"Score": "1",
"Tags": [
"r"
],
"Title": "Removing first duplicate dataframe"
}
|
20053
|
<p>This is a polymorphic wrapper capable of holding any type. (It is loosely based on <code>boost::any</code>)</p>
<p>In particular, this is useful when you want to store a heterogeneous collection, such as <code>vector<Any></code>.</p>
<h2>Synopsis</h2>
<pre><code>string s = ...;
int i = ...;
Any a1 = s;
Any a2 = i;
int j = a2; // ok j now equals i
string t = a1; // ok t now equals s
int k = a1; // runtime exception bad_cast
vector<Any> v;
v.push_back("foo");
v.push_back(42);
const char* s = v[0];
int l = v[1];
</code></pre>
<h2>Implementation</h2>
<pre><code>#include <type_traits>
#include <utility>
#include <typeinfo>
#include <string>
#include <cassert>
using namespace std;
template<class T>
using StorageType = typename decay<typename remove_reference<T>::type>::type;
struct Any
{
bool is_null() const { return !ptr; }
bool not_null() const { return ptr; }
template<typename U> Any(U&& value)
: ptr(new Derived<StorageType<U>>(forward<U>(value)))
{
}
template<class U> bool is() const
{
typedef StorageType<U> T;
auto derived = dynamic_cast<Derived<T>*> (ptr);
return derived;
}
template<class U>
StorageType<U>& as()
{
typedef StorageType<U> T;
auto derived = dynamic_cast<Derived<T>*> (ptr);
if (!derived)
throw bad_cast();
return derived->value;
}
template<class U>
operator U()
{
return as<StorageType<U>>();
}
Any()
: ptr(nullptr)
{
}
Any(Any& that)
: ptr(that.clone())
{
}
Any(Any&& that)
: ptr(that.ptr)
{
that.ptr = nullptr;
}
Any(const Any& that)
: ptr(that.clone())
{
}
Any(const Any&& that)
: ptr(that.clone())
{
}
Any& operator=(const Any& a)
{
if (ptr == a.ptr)
return *this;
auto old_ptr = ptr;
ptr = a.clone();
if (old_ptr)
delete old_ptr;
return *this;
}
Any& operator=(Any&& a)
{
if (ptr == a.ptr)
return *this;
swap(ptr, a.ptr);
return *this;
}
~Any()
{
if (ptr)
delete ptr;
}
private:
struct Base
{
virtual ~Base() {}
virtual Base* clone() const = 0;
};
template<typename T>
struct Derived : Base
{
template<typename U> Derived(U&& value) : value(forward<U>(value)) { }
T value;
Base* clone() const { return new Derived<T>(value); }
};
Base* clone() const
{
if (ptr)
return ptr->clone();
else
return nullptr;
}
Base* ptr;
};
</code></pre>
<h2>Test</h2>
<pre><code>int main()
{
Any n;
assert(n.is_null());
string s1 = "foo";
Any a1 = s1;
assert(a1.not_null());
assert(a1.is<string>());
assert(!a1.is<int>());
Any a2(a1);
assert(a2.not_null());
assert(a2.is<string>());
assert(!a2.is<int>());
string s2 = a2;
assert(s1 == s2);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T08:36:22.207",
"Id": "47648",
"Score": "1",
"body": "This seems not compiling on Visual Studio 2010... anybody tried on VS 2010?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T13:07:35.453",
"Id": "47649",
"Score": "2",
"body": "@DanNiero The C++11 support in Visual Studio (especially the 2010 version) is incomplete. It lacks various features including template aliases (which, I think, the 2012 version lacks as well), so you won't get this code to compile in Visual Studio."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T14:54:51.777",
"Id": "58343",
"Score": "0",
"body": "Does it compile with VS2012? At least, not on my side. I've received a lot of compilation errors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T06:34:25.230",
"Id": "83712",
"Score": "0",
"body": "What's your license on this code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T06:39:33.770",
"Id": "83713",
"Score": "2",
"body": "@DigitalArchitect: Public domain. You may use it any way you like without attribution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T06:41:51.757",
"Id": "83714",
"Score": "0",
"body": "@user1131146accountabandoned, Thanks a lot! If you care at all, I'm including it in an open source project of mine. :) Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T06:43:43.660",
"Id": "83715",
"Score": "0",
"body": "@DigitalArchitect: Which open source project out of interest?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T06:48:10.340",
"Id": "83716",
"Score": "0",
"body": "@user1131146accountabandoned it's unpublished. I'm basically writing out the capabilities of Adobe Flash/AIR in C++, keeping the API exactly the same, then porting over all kinds of stuff like Away3D (which will be basically automated once the framework is finished). Basically something like openframeworks but with an API instantly familiar to many and easy to pick up for others, complete with all the tools/plugins/etc to make any game/app."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T06:48:41.513",
"Id": "83717",
"Score": "0",
"body": "I needed something like boost::any to replace the \"*\" any type in AS3, but don't want to have any external deps."
}
] |
[
{
"body": "<pre><code>template<class T>\nusing StorageType = typename decay<typename remove_reference<T>::type>::type;\n</code></pre>\n\n<p>This appears unnecessarily complex: 'decay' already removes a reference. Consider using:</p>\n\n<pre><code>template <class T>\nusing StorageType = typename decay<T>::type; \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T11:53:09.187",
"Id": "20059",
"ParentId": "20058",
"Score": "15"
}
},
{
"body": "<blockquote>\n<pre><code>~Any()\n{\n if (ptr)\n delete ptr;\n}\n</code></pre>\n</blockquote>\n\n<p>No need to check for nullptr here because <code>delete</code> ignores null pointers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-17T18:44:52.140",
"Id": "87243",
"ParentId": "20058",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20059",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T11:42:08.127",
"Id": "20058",
"Score": "27",
"Tags": [
"c++",
"c++11",
"variant-type"
],
"Title": "C++11 Any class"
}
|
20058
|
<blockquote>
<p>Write an efficient function to find the first non-repeated character
in a string. For example, the first non-repeated character in "total"
is 'o' and the first non-repeated character in "teeter" is 'r'.</p>
</blockquote>
<p>Please see my solution and give me some feedback and suggestions for improving and optimizing it if needed.</p>
<pre><code>#include <stdio.h>
#define SIZE 100 /* max size of input string */
#define LIM 5 /* max number of inputs */
char repeat_ch(const char *); /* return first non-repeated character */
int main(void)
{
char line[SIZE];
int i = 0;
char ch;
while(i < LIM && gets(line))
{
ch = repeat_ch(line);
if(ch != NULL)
printf("1st non-repeated character: %c\n", ch);
else
printf("There is no unique character in a string: %s\n", line);
i++;
}
}
char repeat_ch(const char *string)
{
char array[130] = {0};
char *p = string;
/* store each character in array, use ascii code as an index for character
* increment each time the same character appears in a string
*/
while(*p) // stop when '\0' encountered
{
array[*p]+=1;
p++;
}
while(*string)
{
if(array[*string] == 1)
return *string; // stop when unique character found
string++;
}
return *string;
}
</code></pre>
|
[] |
[
{
"body": "<p>Alex, it looks quite efficient. There are some issues that I see:</p>\n\n<ul>\n<li><p><code>gets</code> should never be used. Use <code>fgets</code> (but note that you will have to strip the trailing <code>\\n</code>)</p></li>\n<li><p>define <code>main</code> at the end to avoid the need for a prototype for <code>repeat_ch</code></p></li>\n<li><p>declare <code>repeat_ch</code> as static</p></li>\n<li><p>your limit does not work as <code>i</code> is not incremented. But why not stop on\nreading an empty string rather than limit the number of loops?</p></li>\n<li><p>NULL is normally defined as <code>(void *) 0</code> so comparing a char with NULL is\nwrong. The compiler will warn you of that. Just use 0 or better '\\0'</p></li>\n</ul>\n\n<p>In <code>repeat_ch</code></p>\n\n<ul>\n<li><p>function name is inaccurate - function looks for a <strong>non</strong>-repeated char.</p></li>\n<li><p>the two // comments are noisy (ie. don't tell reader anything)</p></li>\n<li><p><code>array</code> would be better sized 256</p></li>\n<li><p><code>p</code> should be <code>const</code></p></li>\n<li><p>for-loops would be better</p>\n\n<pre><code>for (const char *p=string; *p; ++p) {\n array[*p] += 1;\n}\nfor (const char *p=string; *p; ++p) {\n if (array[*p] == 1) {\n return *p;\n }\n}\nreturn '\\0';\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T15:20:48.423",
"Id": "32066",
"Score": "0",
"body": "thanks for feedback was really useful. Have added \"i\" as it was my copy-paste typo."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T07:16:28.243",
"Id": "32073",
"Score": "0",
"body": "+1: Very good analysis. The only things I can see that you didn't mention are trivia: (1) erratic indentation in `main()` and (2) use of `if(...)` etc instead of `if (...)`. The omitted `return 0;` from `main()` is OK in C99 or later, though personally I think that rule was a mistake and always include it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T13:51:31.707",
"Id": "20063",
"ParentId": "20060",
"Score": "6"
}
},
{
"body": "<p>1) This is good enough for small scale string, but in practical life, this problem needs to deal with string having length in millions eg DNA string etc.</p>\n\n<p>2) You can improve it by not traversing over the string for the second time, but maintain the first occurrence of the each character with the number of its occurrence.\nSorting like structure - </p>\n\n<pre><code>typedef struct charStruct {\n int count;\n int index;\n}cStruct;\n\n//...\n\ncStruct *count = (cStruct *)calloc(sizeof(cStruct),256);\n</code></pre>\n\n<p>malloc for 256 characters (if dealing with ASCII) and use this structure, that will give you huge improvement in practical solution.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-05T10:54:45.010",
"Id": "127565",
"ParentId": "20060",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "20063",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T12:06:51.250",
"Id": "20060",
"Score": "1",
"Tags": [
"optimization",
"c",
"strings",
"array"
],
"Title": "First non-repeated character in a string in c"
}
|
20060
|
<p>I quite often need to implement collection-like classes and - to make using them more comfortable - would like to take advantage of a constructor with variable arguments.</p>
<p>The following implementation does not work, though.</p>
<pre><code>class FruitsStore
{
private List<String> availableFruits;
public FruitsStore(String... fruits)
{
this.availableFruits = Arrays.asList(fruits);
}
public void add(String fruit)
{
this.availableFruits.add(fruit);
}
...
}
</code></pre>
<p>The following code snippet</p>
<pre><code>FruitsStore store = new FruitsStore("banana", "melon");
store.add("orange");
</code></pre>
<p>throws the following exception</p>
<pre><code>Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
at cz.dusanrychnovsky.FruitsStore.add(FruitsStore.java:26)
at cz.dusanrychnovsky.FruitsStore.main(FruitsStore.java:12)
</code></pre>
<p>To overcome this issue, I use a constructor like this:</p>
<pre><code>public FruitsStore(String... fruits)
{
this.availableFruits = new LinkedList<String>(Arrays.asList(fruits));
}
</code></pre>
<p>This compiles and works fine.</p>
<p><strong>Is this a good coding practice? Does it have any drawbacks? What implementation would you suggest?</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T14:35:25.877",
"Id": "32063",
"Score": "0",
"body": "http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#asList%28T...%29\nreturns a **fixed-size** list. No `add` no `remove`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T14:53:16.600",
"Id": "32064",
"Score": "0",
"body": "But what is the correct way to get around this issue?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T11:03:20.243",
"Id": "32081",
"Score": "0",
"body": "I don't see why you would need to define a new class just to represent a (crippled) collection of objects and do nothing else with it when you could just use a plain list assigned to an appropriately named variable. What you've shown here doesn't justify the need."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T12:23:14.033",
"Id": "32083",
"Score": "0",
"body": "The code was only meant to illustrate the problem. The classes always contain other (domain specific) methods to operate on the list, which are not provided by any standard collection classes. I edited the post to make this more obvious (three dots at the end of the class definition)."
}
] |
[
{
"body": "<p>You have found the <em>natural</em> solution to this situation. <code>Arrays.asList</code> will give you a <code>List</code> with specific features - <code>new xxList(Arrays.asList(...))</code> will give you a list with attributes you require.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T09:24:03.797",
"Id": "32077",
"Score": "0",
"body": "Does it have any drawbacks, such as low performance? Is there a better solution?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T11:31:29.010",
"Id": "32082",
"Score": "1",
"body": "No and no.\n\nWhat you should really consider is how your collection-like class will be used. \nFor example LinkedList is slower than arraylist on indexed access and is not synchronized."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T01:32:25.553",
"Id": "20073",
"ParentId": "20062",
"Score": "2"
}
},
{
"body": "<p>Arrays.asList does not create a new collection, rather it provides a List-like interface to the original Array. As an Array can't grow in size, the add() method is unsupported.\nEven when a fixed size List is acceptable, creating a new list from the original array does use a bit more memory, but may be the safer way to go if you don't need the side affect of changes to the original Array.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T18:29:08.480",
"Id": "20077",
"ParentId": "20062",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20073",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T12:49:26.067",
"Id": "20062",
"Score": "1",
"Tags": [
"java"
],
"Title": "Collection-like classes in Java - taking advantage of varargs"
}
|
20062
|
<p>I've been trying to get a relatively optimized version of base64 encoding that works against files. However, I've made several attempts and haven't gotten anything much faster than what I have here. On the posted implementation, I started from what was posted on <a href="http://www.swissdelphicenter.ch/torry/showcode.php?id=1524" rel="nofollow">http://www.swissdelphicenter.ch/torry/showcode.php?id=1524</a> . I have to think there's a way to do it without tossing values around in a, so I tried that by processing three bytes at a time and then processing the rest, but I didn't end up with anything faster. So, does anyone have any ideas on how to improve it any more from a speed perspective?</p>
<p>(Relevant code below, I slid some global definitions into the first procedure so people could see those. Codes64 is the string I'm using to encode the data
with, not reproduced here for brevity)</p>
<pre><code>procedure TMyMimeEncoder.Enc64Buffer(inbuf, outbuf: pointer; inbufsize: longint;
var outbufsize: longint);
// run on the buffer read in by the file (inbuf). Outbuf is the output.
type
PByteArray1 = ^TByteArray1;
TByteArray1 = array[1..buffersize] of Byte;
var
a, b: longint;
inproc: PByteArray1 absolute inbuf;
outproc: PChar;
i: longint;
begin
outproc := outbuf;
outbufsize := 0;
for i := 1 to inbufsize do
begin
b := (b shl 8) + inproc^[i];
a := a + 8;
if a = 12 then
begin
a := a - 6;
outproc^ := Codes64[(b shr a)];
b := b and ((1 shl a) - 1);
inc(outproc, 1);
inc(outbufsize, 1);
end;
a := a - 6;
outproc^ := Codes64[(b shr a)];
b := b and ((1 shl a) - 1);
inc(outproc, 1);
inc(outbufsize, 1);
end;
end;
function TMyMimeEncoder.Enc64Final: String;
// run at the end of file to finish the encoding.
begin
Result := '';
if a = 4 then
Result := Codes64[(b shl 2) + 1] + '='
else
if a = 2 then
Result := Codes64[(b shl 4) + 1] + '==';
end;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T00:16:17.237",
"Id": "32088",
"Score": "0",
"body": "I have a different version of this now with much smaller numbers of instructions. I figured out the main issue is with the output buffer assigns (my guess about 20% of the total run when I comment those lines out). If anyone has any ideas in that realm, I'd appreciate them."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T14:41:43.327",
"Id": "20064",
"Score": "2",
"Tags": [
"delphi",
"base64"
],
"Title": "Performance Tuning Base64 encoding"
}
|
20064
|
<p>I am trying to wrap my arms around all the digital files we have, so I thought I would organize all of our pictures and videos into folders named after dates. I'm learning F#, and this felt like a good chance for me to exercise that muscle.</p>
<p>Please review the code. I'm open to any criticisms, but I also have some specific areas of interest:</p>
<ol>
<li><p>I feel like the filtering out of the thumbs.db file should be inside the sequence expression. What's a good way to do that?</p></li>
<li><p>In getNewFilename, that function and its internal incrementFilename function each have an expression checking for the existence of the file. I think that check could be cleanly put into a single check, but I can't think quite how.</p></li>
<li><p>It took 1 hour and 10 minutes to copy 120GB in over 28,000 files. This is on a quad-core laptop with a 7,200 RPM drive. Realizing that the drive is the limiting factor for this work, and there could be clashes in filenames, what might be some good concurrent processing techniques to possibly have this code finish sooner?</p></li>
</ol>
<pre><code>open System
open System.Drawing
open System.IO
open System.Text
open System.Text.RegularExpressions
let rec getAllFiles baseDir =
seq {
yield! Directory.EnumerateFiles(baseDir)
for dir in Directory.EnumerateDirectories(baseDir) do
yield! getAllFiles dir
}
let dateTakenFromExif file =
let r = new Regex(":")
use fs = new FileStream(file, FileMode.Open, FileAccess.Read)
use myImage = Image.FromStream(fs, false, false)
let propItem = myImage.GetPropertyItem(36867)
let dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2)
DateTime.Parse(dateTaken)
let getDateTaken file =
try
dateTakenFromExif file
with
| :? Exception ->
File.GetLastWriteTime(file) //Use the last write time in the event that the file was moved/copied
let addToFile file n =
match n with
| 2 ->
let fileDir = Path.GetDirectoryName(file)
let nextFile = Path.GetFileNameWithoutExtension(file) + "-" + n.ToString() + Path.GetExtension(file)
Path.Combine(fileDir, nextFile)
| _ ->
let prev = n-1
file.Replace("-" + prev.ToString(), "-" + n.ToString())
let getNewFilename newFilePath =
let rec incrementFilename file n =
let filenameIncremented = addToFile file n
match File.Exists(filenameIncremented) with
| false -> filenameIncremented
| true -> incrementFilename filenameIncremented (n+1)
match File.Exists(newFilePath) with
| false -> newFilePath
| true -> incrementFilename newFilePath 2
let move destinationRoot files =
let moveHelper file =
let dateTaken = getDateTaken file
let finalPath = Path.Combine(destinationRoot, dateTaken.Year.ToString(), dateTaken.ToString("yyyy-MM-dd"))
if not(Directory.Exists(finalPath)) then Directory.CreateDirectory(finalPath) |> ignore
let newFile = getNewFilename (Path.Combine(finalPath, Path.GetFileName(file)))
try
File.Copy(file, newFile)
with
| :? Exception as e ->
failwith (sprintf "error renaming %s to %s\n%s" file newFile e.Message)
files |> Seq.iter moveHelper
let moveFrom source =
getAllFiles source
|> Seq.filter (fun f -> Path.GetExtension(f).ToLower() <> ".db") //exlcude the thumbs.db files
|> move """C:\_EXTERNAL_DRIVE\_Camera"""
printfn "Done"
#time
moveFrom """C:\Users\Mike\Pictures\To Network"""
moveFrom """C:\_EXTERNAL_DRIVE\Camera"""
</code></pre>
|
[] |
[
{
"body": "<p>A few things:</p>\n\n<p>There's already a recursive overload of <code>EnumerateFiles</code> so you don't need <code>getAllFiles</code>. Your top level function would be:</p>\n\n<pre><code>let moveFrom source =\n Directory.EnumerateFiles(source, \"*\", SearchOption.AllDirectories)\n |> Seq.filter (fun f -> Path.GetExtension(f).ToLower() <> \".db\") //exlcude the thumbs.db files\n |> move \"\"\"C:\\_EXTERNAL_DRIVE\\_Camera\"\"\"\n printfn \"Done\"\n</code></pre>\n\n<p><code>:? Exception</code> is a type test pattern match, which is unnecessary in a <code>try/with</code> because <code>with</code> only fires for exceptions anyway. You could do this:</p>\n\n<pre><code>let getDateTaken file =\n try dateTakenFromExif file\n with _ -> File.GetLastWriteTime(file)\n</code></pre>\n\n<p>and this:</p>\n\n<pre><code>try File.Copy(file, newFile)\nwith e -> failwith (sprintf \"error renaming %s to %s\\n%s\" file newFile e.Message)\n</code></pre>\n\n<p>instead.</p>\n\n<p><code>addToFile</code> could be merged into <code>getNewFileName</code> to form a simpler function without repetition:</p>\n\n<pre><code>let getNewFilename newFilePath =\n let rec loop file n =\n if File.Exists(file) then \n let fileDir = Path.GetDirectoryName(file)\n let nextFile = Path.GetFileNameWithoutExtension(file) + \"-\" + n.ToString() + Path.GetExtension(file)\n loop (Path.Combine(fileDir, nextFile)) (n+1)\n else file\n loop newFilePath 2\n</code></pre>\n\n<p>For easy parallelization you might try using <code>PSeq</code> (\"parallel sequence\") from the F# PowerPack. You might see some gains from simply doing this:</p>\n\n<pre><code>files |> PSeq.iter moveHelper\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T00:17:20.530",
"Id": "32181",
"Score": "0",
"body": "Hi, @Daniel. Thanks for taking the time to review the code. Those are exactly the kind of readability suggestions I was looking for - simple and straightforward. As for the concurrency, `PSeq.iter` made it take almost a half hour _longer_. There may have been drive/environmental differences, I don't know. I'm going to dig into the concurrency aspect specifically, and probably post another question in the near future. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T03:11:09.613",
"Id": "32185",
"Score": "1",
"body": "Hmm, I wonder if you're IO bound. If that's the case, `PSeq` would only add overhead (although I'm surprised to hear it was _so much_ slower)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T03:36:58.877",
"Id": "20083",
"ParentId": "20068",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20083",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T19:59:43.707",
"Id": "20068",
"Score": "0",
"Tags": [
"asynchronous",
"f#"
],
"Title": "Perfomance and Other Improvements"
}
|
20068
|
<p>This question is related to <a href="http://expressjs.com" rel="nofollow">Express</a> under <a href="http://nodejs.org" rel="nofollow">Node.js</a>.</p>
<h1>Background</h1>
<p>With Express, you stack up several "middleware" modules to handle a specific HTTP request.</p>
<pre><code>app.use(express.logger());
app.use(express.favicon()));
app.use(express.cookieParser());
app.use(express.session());
app.use(app.router);
</code></pre>
<p>When a request comes in, Express goes through all of the functions in the stack until a module handles the request. Specifically, each middleware module is a <code>function (req, res, next)</code>, and that function will call <code>next()</code> to call the next module in the stack. Functions can modify data in the <code>req</code> or <code>res</code> objects if they choose.</p>
<h1>The Problem</h1>
<p>I was interested in making custom log middleware modules for my Express application, and I needed to use more than one module at a time. The data I need to log cannot be logged until the response has been sent to the client. (I am tracking bytes sent, and the amount of time a connection was established.) Unfortunately, Node.js's HTTP response object <a href="http://nodejs.org/api/http.html#http_class_http_serverresponse" rel="nofollow">does not raise an <code>end</code> event</a>. Presumably, this is because it is up to the application to do any "end" work prior to calling <code>.end()</code> on the response object in the first place. Express does not expose a hook prior to <code>.end()</code> being called.</p>
<p>Express/Connect's built-in logger middleware is able to track how long a request was running, so I decided to see what method they use. They actually <a href="https://github.com/senchalabs/connect/blob/master/lib/middleware/logger.js" rel="nofollow">replace the <code>res.end</code> function</a> with their own. When their own <code>res.end</code> function is called, it swaps the old <code>res.end</code> back in place, finishes logging, then calls <code>res.end</code> with the parameters that their own <code>res.end</code> was called with. Their method works, but can be problematic when a handful of modules try to do this. (The order in which <code>res.end</code> function replacement occurs becomes critical.)</p>
<h1>My Solution</h1>
<p>I have used their method to patch <code>res</code> to fire <code>end</code> events so that any module in the chain can subscribe to that event in the usual way.</p>
<pre><code>function (req, res, next) {
var end = res.end;
res.end = function () {
res.end = end;
res.emit('end');
res.end.apply(this, arguments);
}
next();
}
</code></pre>
<p>Then, all my logger module has to do is:</p>
<pre><code>res.on('end', function () { /* log here */ });
</code></pre>
<p>Is there any problem with what I have done? Is there a better way to do it?</p>
|
[] |
[
{
"body": "<p>I did the following for something similar. This uses the closure to create a chain-of-command pattern.</p>\n\n<pre><code>function (req, res, next) {\n var realEnd = res.end;\n res.end = function () {\n var realEndArgs = arguments;\n req.log.info (\"HTTP RESPONSE CODE \" + res.statusCode);\n realEnd.apply (res, realEndArguments);\n }\n next();\n}\n</code></pre>\n\n<p>You could instead of logging the status code, do res.emit('end') as you described, or anything else, before returning control to the original res.end (which may itself be a replacement). Or, you could do directly in this function whatever you want to do in response to the end event.</p>\n\n<p>Note: I explicitly store res.end's arguments in realEndArguments in case I later add anything asynchronous, because arguments would then refer to the asynchronous action's callback's arguments instead of res.end's arguments. A subtle bug I ran into at first.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T19:21:38.000",
"Id": "29407",
"ParentId": "20069",
"Score": "3"
}
},
{
"body": "<p>I had similar problem and published the package <a href=\"https://www.npmjs.com/package/express-end\" rel=\"nofollow noreferrer\">express-end</a> to solve this limitation.\nThe code is quite similar to <a href=\"https://codereview.stackexchange.com/users/12199/brad\">Brad</a>'s solution with additional check.</p>\n\n<pre><code>var endMw = function(req, res, next) {\n\n if (!res._orig_end_handler) {\n\n res._orig_end_handler = res.end;\n\n res.end = function () {\n res.end = res._orig_end_handler;\n res.emit('end');\n res.end.apply(this, arguments);\n };\n\n } else {\n debug('Warning: res.end() function is already overridden');\n }\n\n next();\n\n};\n</code></pre>\n\n<p>Hope, the package will save some time to somebody else.</p>\n\n<p>Upd:\nAs this code is utility, to be used in the package and may be reused by other packages, I assume the check is needed to prevent double patching of <code>res.end()</code> if the middleware is applied twice. In order to do that, I store original handler in property of <code>res</code> object, not in the closure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-10T09:13:27.667",
"Id": "228141",
"Score": "1",
"body": "Please add some explanation to explain how your code is an improvement over the original solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-10T08:45:50.690",
"Id": "122453",
"ParentId": "20069",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T20:06:51.283",
"Id": "20069",
"Score": "4",
"Tags": [
"javascript",
"node.js"
],
"Title": "Monkey patching extra events in Node.js HTTP/Express"
}
|
20069
|
<p>I started off with a simple dispatch class, but it's grown and I'm sure it could be simplified in the very least. In fact, I'm doing way too much in the <code>__construct()</code> method</p>
<p>It it being called as such:</p>
<pre><code>$router = new router($_SERVER['REQUEST_URI'], $database);
$router->dispatch();
</code></pre>
<p>Yep, I'm pushing my database object into it.</p>
<p>Here's the class:</p>
<pre><code>class router
{
/**
* @var array Request URL
* @var array|string Controller Class Name
* @var array|string Method Name
* @var array|string Parameters
* @var array|bool|string Route Validity
* @var array|bool|string Primary Source
* @var \Zend\Db\Adapter\Adapter Database Adapter
*/
protected $url,
$controller,
$method,
$params,
$validRoute,
$primary,
$database;
/**
* Constructs the router class with routing paramters
* and database to inject into dispatched controller.
* Construct also sets the appropriate controller, method
* based in routing params, then checks if route is valid.
* @param $params
* @param $database
*/
public function __construct($params, \Zend\Db\Adapter\Adapter $database)
{
$this->database = $database;
$this->url = explode('/', trim($_SERVER['REQUEST_URI'], '/'));
$this->validRoute = true;
$requestParams = $_REQUEST;
unset($requestParams['url']);
$this->controller = !empty($this->url[0]) ? 'controller\\' . $this->url[0] : 'controller\\home';
if ($this->url[0] != 'ajax') {
$this->method = !empty($this->url[1]) ? $this->url[1] . "View" : 'indexView';
$this->params = !empty($this->url[2]) ? $_REQUEST : $_REQUEST;
$GLOBALS['url'] = array();
$GLOBALS['url'][] = !empty($this->url[0]) ? $this->url[0] : 'home';
$GLOBALS['url'][] = !empty($this->url[1]) ? $this->url[1] : '';
$GLOBALS['url'][] = !empty($this->url[2]) ? $this->url[2] : '';
} else {
$this->controller = 'catalina\\ajax';
$this->method = 'handleRequest';
$this->params = array (
'url' => $this->url,
'controller' => !empty($this->url[1])
? 'controller\\' . $this->url[1] : 'controller\\home',
'method' => !empty($this->url[2]) ? $this->url[2] . "Ajax" : '',
'params' => $requestParams,
'database' => $this->database,
);
$this->primary = 'ajax';
}
return self::checkRoute();
}
/**
* Checks to see if a given route is valid
* @return bool
*/
private function checkRoute()
{
if ($this->controller != 'controller\ajax') {
if (preg_match("#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*#", $this->controller)) {
try {
class_exists($this->controller);
} catch (Exception $e) {
$error = new ErrorHandler($this->database);
$error->invalidDispatch(debug_backtrace(), $this->controller);
$this->validRoute = false;
return false;
}
$reflection = new \ReflectionClass($this->controller);
if (!class_exists($this->controller) || (!($reflection->hasMethod($this->method)))) {
$error = new ErrorHandler($this->database);
$error->invalidDispatch(debug_backtrace(), $this->controller, $this->method);
$this->validRoute = false;
return false;
}
} else {
$error = new ErrorHandler($this->database);
$error->invalidDispatch(debug_backtrace(), $this->controller);
$this->validRoute = false;
}
}
return true;
}
/**
* Dispatches the route to the requested controller
* and method.
* @return bool
*/
public function dispatch()
{
if ($this->validRoute == true) {
$dispatchedController = new $this->controller($this->database);
$method = $this->method;
return $dispatchedController->$method($this->params);
} else {
return false;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T14:01:40.067",
"Id": "40832",
"Score": "0",
"body": "Your AJAX requests should be treated the same as normal requests, as in they go to the relevant controller / action. In the relevant **controller method** is where you make sure that it's an AJAX request, and prepare / return the response."
}
] |
[
{
"body": "<p>Your property doccomments are wrong. As they are you will only get that one long list of <code>@var</code>s for <code>$url</code> and the rest will remain empty. This defeats the purpose of the doccomments. The proper way is to put each doccomment above its respective property, like so:</p>\n\n<pre><code>protected\n /** @var array Request URL */\n $url,\n\n /** @var array|string Controller Class Name */\n $controller,\n\n //etc...\n;\n</code></pre>\n\n<p>You may also want to revisit those properties. First, unless this class is being extended, then these properties should be private, not protected. Second, most of these properties are doing entirely too much. Its not uncommon for a method to return multiple types, usually just one or two similar types; But a property should normally have just one. The way these are makes me think they are trying to do too much. For instance, <code>$validRoute</code> should probably only be a boolean, especially given the name.</p>\n\n<p>Using whitespace to your advantage is good practice, especially if it helps with legibility. However, there is such a thing as too much. When aligning variable definitions, you should do so in groups and only to the extreme of the longest. I'm not sure what you were extending to, but it appeared to be beyond your longest definition. You should also be consistent. While scanning your code I at first didn't realize that <code>$requestParams</code> was a variable because it was not aligned with the others. This is usually the main reason for such an alignment, to easily tell at a glance where your variables are.</p>\n\n<pre><code>$this->database = $database;\n\n$this->url = explode('/', trim($_SERVER['REQUEST_URI'], '/'));\n$this->validRoute = true;\n\n$requestParams = $_REQUEST;\n</code></pre>\n\n<p>Now, the idea behind injecting parameters into your methods is to avoid tight coupling and allow for sharing information. This goes hand in hand with the Law of Demeter (LoD), which states that functions/methods should only know as much as is necessary to get its job done. However, all of the <code>$_SERVER, $_REQUEST</code> and <code>$GLOBALS</code> arrays are going against this. Especially since you have injected <code>$_SERVER[ 'REQUEST_URI' ]</code> as the <code>$params</code> parameter already, though you're not using it. Avoid tight coupling and just inject what you need.</p>\n\n<p>You can define the default value for <code>$validRoute</code> when you initially declare the property. Since it has a static value and is unused in the constructor there is no need to assign a value to it there. You wont even have to change the format of your properties. You can assign values to your properties while listing them.</p>\n\n<pre><code>protected\n $url,\n //etc...\n $validRoute = TRUE,\n $primary,\n //etc...\n;\n</code></pre>\n\n<p>If you have an array, whose individual parts make up different elements, you can use <code>list()</code> to define each part and avoid having to manually declare individual array elements. This is especially helpful because it avoids the use of magic numbers, which can be very confusing and detrimental to your code's health. To ensure that you don't get any \"out of bounds\" errors, you should pad your array before trying to list its elements.</p>\n\n<pre><code>array_pad( $this->url, 3, FALSE );\nlist( $request, $method, $params ) = $this->url;\n\nif( $request != 'ajax' ) {\n</code></pre>\n\n<p>If you can avoid using \"not\" in your arguments, you should do so. Reverse the logic if necessary. This helps with legibility.</p>\n\n<pre><code>if( $this->url[ 0 ] == 'ajax' ) {\n//etc...\n$this->controller = empty( $this->url[ 0 ] ) ? 'controller\\\\home' : 'controller\\\\' . $this->url[ 0 ];\n</code></pre>\n\n<p>Ternary statements are nice, but you should only use them when they don't hinder legibility. This means they should be short (less than 80 characters, including indentation), and simple (not nested or overly complex). If it violates either of these rules of thumb, you should probably consider using a regular if/else statement. Sometimes ternary statements aren't even necessary. For example:</p>\n\n<pre><code>$var = $true ? TRUE : FALSE;//unnecessary\n$var = $true;\n\n//or\n\n$this->params = empty( $this->url[ 2 ] ) ? $_REQUEST : $_REQUEST;//redundant\n$this->params = $_REQUEST;\n</code></pre>\n\n<p>So, I'm assuming this <code>$GLOBALS</code> array is somehow associated with an actual global. It isn't returned or used as far as I can tell, so this seems to suggest my assumption is correct. Globals are evil. Especially in a OOP environment where properties accomplish the same thing. You should never, and I DO mean NEVER, need a global. They are completely and utterly useless, no matter the circumstances. If you forgot what they were right now, you would never notice. I strongly urge you to remove this from your code.</p>\n\n<p>Let's look at one of the key OOP Principles: \"Don't Repeat Yourself\" (DRY). As the name implies, your code should not repeat itself. This can even be as simple as reusing a value for a variable. For example:</p>\n\n<pre><code>$this->controller = 'controller\\\\';\n//etc...\n$this->controller .= empty( $this->url[ 0 ] ) ? 'home' : $this->url[ 0 ];\n</code></pre>\n\n<p>There are only two reasons I can think of to use <code>self::*</code> instead of <code>$this->*</code>. The first is if your class is static, which you should avoid and doesn't appear to be the case here. The second is if you are wanting to use a specific version of an inherited method. If the method is private, then it can't be inherited and therefore will always be the same. Neither of these appears to be the case here, so, unless I'm missing something, you should just use <code>$this->*</code>.</p>\n\n<pre><code>return $this->checkRoute();\n</code></pre>\n\n<p>Besides the improvements I mentioned above your constructor is only very slightly violating the Single Responsibility Principle. This principle states that your functions/methods should do just one thing and not be concerned with anything else. Usually this principle is also combined with LoD so that the task can be reused without being tightly coupled. At most I think there are three things being done here. The first is instantiating the class, which is fine, this is the constructor after all. The second is breaking down the URL, which should probably be moved into its own method. And the third is checking the route, which is already in its own method. Just moving that second task to its own method is a good start, but you might also consider separating the last two tasks from the constructor by manually calling on them. Having your constructor do this automatically is fine if this will ALWAYS be necessary, but if you can think of even a single reason why it might not, then manually doing these tasks might be better.</p>\n\n<p>So, next method. There are two key principles being violated here. The easiest to see is the Arrow Anti-Pattern. This principle illustrates code that is heavily indented to come to points, though just the heavy or unnecessary indentation is necessary for a violation, not the shape. The easiest way to avoid violating this principle is to return early whenever possible. This usually makes else and nested if/else statements unnecessary. For example:</p>\n\n<pre><code>if( $this->controller == 'controller\\ajax' ) {\n return TRUE;\n}\n\n//etc...\n</code></pre>\n\n<p>The second principle is DRY again. Above I showed a very simple, but subtle, violation. This one is a bit more standard. You have chunks of code that are being repeated. In this case we can incorporate the use of a new method to report our errors. I'm using FALSE as the default value for our method, but you can use whatever you currently are.</p>\n\n<pre><code>private function reportError( $backtrace, $method = FALSE ) {\n $error = new ErrorHandler( $this->database );\n $error->invalidDispatch( $backtrace, $this->controller, $method );\n\n $this->validRoute = FALSE;\n}\n</code></pre>\n\n<p>The return value appears to be very closely linked to the <code>$validRoute</code>, so you can just return <code>$validRoute</code> to avoid the repetition.</p>\n\n<pre><code>return $this->validRoute = FALSE;\n</code></pre>\n\n<p>There is no need to explicitly check for a specific value unless you are specifically looking for that value, in which case you should then use the absolute <code>===</code> comparison rather than a loose <code>==</code> one. PHP automatically converts types for comparison.</p>\n\n<pre><code>if( $this->validRoute == TRUE ) {//redundant\nif( $this->validRoute ) {//best option in this situation\n\n//only true if $validRoute is a boolean true\n//only necessary if specifically looking for this value\n//unnecessary here as we are checking a protected boolean property\n//we can assume its either TRUE/FALSE and use the above method instead\nif( $this->validRoute === TRUE ) {\n</code></pre>\n\n<p>Since you have returned early, there is no need for the else statement. This just forces unnecessary indentation.</p>\n\n<pre><code> return $dispatchedController->$method($this->params);\n} //else {//unnecessary\n\nreturn false;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T22:26:15.733",
"Id": "20107",
"ParentId": "20071",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-31T23:44:43.753",
"Id": "20071",
"Score": "0",
"Tags": [
"php",
"mvc"
],
"Title": "Simplifying my dispatch and routing class"
}
|
20071
|
<p>Following code helps me to automatically map the query result with Entity properties. For example, result of the following query “ReportTypeCode“ is mapped with Report object’s ReportTypeCode property.</p>
<pre><code>SELECT R.report_type_code AS ReportTypeCode FROM Report_Type R
</code></pre>
<p><strong>QUESTIONS</strong></p>
<ol>
<li>Is there any datatype or scenario that it will not be able to handle?</li>
<li>Is there any improvement suggestions?</li>
</ol>
<p><strong>CODE</strong></p>
<pre><code>public static class EntityDataMappingHelper
{
/// <summary>
/// Method for filling entity from data
/// </summary>
public static void FillEntityFromRecord(Object entity, Dictionary<string, object> record)
{
if (entity != null && record != null)
{
PropertyInfo[] propertyInfoArray = entity.GetType().GetProperties();
foreach (PropertyInfo prop in propertyInfoArray)
{
if (record.ContainsKey(prop.Name))
{
if (String.Equals(prop.PropertyType.FullName, "System.String"))
{
prop.SetValue(entity, DBNull.Value.Equals(record[prop.Name]) ? null : Convert.ToString(record[prop.Name], CultureInfo.InvariantCulture), null);
}
else if (String.Equals(prop.PropertyType.FullName, "System.Decimal"))
{
prop.SetValue(entity, DBNull.Value.Equals(record[prop.Name]) ? 0 :
Convert.ToDecimal(record[prop.Name], CultureInfo.InvariantCulture), null);
}
else
{
prop.SetValue(entity, DBNull.Value.Equals(record[prop.Name]) ? null : record[prop.Name], null);
}
}
}
}
}
/// <summary>
/// Method for selecting records from Data Reader
/// </summary>
public static ArrayList SelectRecords(Collection<Object> entityList, IDataReader reader)
{
ArrayList resultList = new ArrayList();
if (entityList != null && reader != null)
{
List<string> propertiesOfAllEntities = new List<string>();
foreach (Object entity in entityList)
{
PropertyInfo[] propertyInfo = entity.GetType().GetProperties();
foreach (PropertyInfo prop in propertyInfo)
{
propertiesOfAllEntities.Add(prop.Name);
}
}
while (reader.Read())
{
Dictionary<string, object> record = MapPropertiesToReaderValues(propertiesOfAllEntities, reader);
resultList.Add(record);
}
}
return resultList;
}
/// <summary>
/// Helper method for mapping properties with reader values
/// </summary>
private static Dictionary<string, object> MapPropertiesToReaderValues(List<string> propertiesOfAllEntities, IDataReader reader)
{
Dictionary<string, object> propertyResultList = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < reader.FieldCount; i++)
{
string readerFieldName = reader.GetName(i);
//Whether propertiesOfAllEntities.Contains the property
if (propertiesOfAllEntities.FindIndex(x => x.Equals(readerFieldName, StringComparison.OrdinalIgnoreCase)) != -1)
{
propertyResultList.Add(readerFieldName, reader[i]);
}
}
return propertyResultList;
}
}
</code></pre>
<p><strong>Client to Test</strong></p>
<pre><code>static void Main(string[] args)
{
Collection<Report> reports = new Collection<Report>();
string connectionString = "Data Source=myserver;Initial Catalog=mydatabase;Integrated Security=SSPI";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = @"SELECT R.report_type_code AS ReportTypeCode
FROM Report_Type R";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
Collection<Object> entityList = new Collection<Object>();
entityList.Add(new Report());
ArrayList records = EntityDataMappingHelper.SelectRecords(entityList, reader);
for (int i = 0; i < records.Count; i++)
{
Report report = new Report();
Dictionary<string, object> currentRecord = (Dictionary<string, object>)records[i];
EntityDataMappingHelper.FillEntityFromRecord(report, currentRecord);
reports.Add(report);
}
}
}
}
}
Console.ReadLine();
}
</code></pre>
<p><strong>DTO/Entity</strong></p>
<pre><code>public class Report
{
public Int16? ReportTypeCode { get; set; }
public string ReportName { get; set; }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T23:20:09.567",
"Id": "32087",
"Score": "3",
"body": "One idea is have you considered using existing ORM's such as EF or LinqSQL?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-21T11:58:24.893",
"Id": "33271",
"Score": "0",
"body": "@dreza My application is intensive data read only (to be displayed as tabular data). Hence ORM will be an unwanted performance hit here."
}
] |
[
{
"body": "<h3>Observations</h3>\n\n<ul>\n<li><p><strong>You are reinventing the wheel</strong>. Yes, an Object/Relational Mapper such as Entity Framework adds an overhead, but if your queries are <code>select abc from xyz</code> I don't see it being an issue.</p></li>\n<li><p>Using reflection has an overhead and performance hit, too.</p></li>\n<li><p>Projecting <code>R.report_type_code</code> into a full-fledged <code>Report</code> instance makes no sense. <strong>If you want to select report type codes, return report type codes</strong>, not a bunch of reports without a description.</p></li>\n<li><p><strong>If a command needed a parameter</strong>, would you concatenate it into a <code>WHERE</code> statement within the command text, or use an <code>SqlParameter</code>? <strong>Would it be the client code's responsibility</strong>? Your code isn't crystal-clear about this.</p></li>\n<li><p>A <code>static</code> class called <code>EntityDataMappingHelper</code> <a href=\"https://stackoverflow.com/questions/2446376/is-the-word-helper-in-a-class-name-a-code-smell\">can be considered a code smell</a>. From <a href=\"https://softwareengineering.stackexchange.com/a/111940/68834\">this Programmers.SE answer</a> (emphasis mine):</p>\n\n<blockquote>\n <p>if a helper method has any external dependency (e.g. a DB) which makes it - thus its callers - <strong>hard to unit test</strong>, it is better to declare it non-static. This allows dependency injection, thus making the method's callers easier to unit test.</p>\n</blockquote></li>\n</ul>\n\n<hr>\n\n<h3>Recommendations</h3>\n\n<ul>\n<li><p>The <code>SelectRecords</code> method doesn't need an <em>instance</em>, it needs a <em>type</em> - <strong>make your method <em>generic</em></strong>, substitute that <code>Collection<object></code> for a <code><TEntity></code> type parameter with some <code>where TEntity : class, new()</code> type constraint.</p></li>\n<li><p>You shouldn't be calling your strongly-typed return value <code>records</code> - call it <code>reports</code> instead, it's less confusing. Or call it <code>entities</code> if you prefer a more generic name; a \"record\" is a low-level thing that a \"report\" doesn't even know/care about.</p></li>\n<li><p>If the database schema is all yours, I think your <code>Report</code> entity wants an <code>Id</code> property. Just in case there's <em>eventually</em> another \"entity\" that wants to refer to a specific report. Much better than indexing the <code>ReportName</code> column.</p></li>\n<li><p>Use <code>List<T></code> over the obsolete <code>ArrayList</code>:</p>\n\n<blockquote>\n <ul>\n <li>from <a href=\"https://stackoverflow.com/a/2309699/1188513\">StackOverflow</a>: ArrayList <strong>belongs to the days that C# didn't have generics</strong>. It's deprecated in favor of List. You shouldn't use ArrayList in new code that targets .NET >= 2.0 unless you have to interface with an old API that uses it.</li>\n </ul>\n</blockquote></li>\n</ul>\n\n<hr>\n\n<h3>Alternatives</h3>\n\n<ul>\n<li><p>Give Entity Framework (Code-First) a try. I'm sure you won't even notice the \"performance hit\" (given your current code it might actually be a <em>performance increase</em>), and <strong>your client code will be much, much simpler</strong>. How about this:</p>\n\n<pre><code>IEnumerable<Report> reports;\nIEnumerable<Int16> reportTypeCodes;\nusing (var context = new MyEntityFrameworkContext())\n{\n reports = context.Reports.ToList();\n reportTypeCodes = context.Reports\n .Where(report => report.ReportTypeCode != null)\n .GroupBy(report => report.ReportTypeCode)\n .Select(grouping => grouping.Key)\n .ToList();\n}\n</code></pre></li>\n<li><p>If you really don't want to use EF, you might actually fall in love with <a href=\"https://stackoverflow.com/tags/dapper/info\">Dapper.NET</a>, a micro-ORM - from the SO tag wiki:</p>\n\n<blockquote>\n <p>it focuses on making the materialization as fast as possible, with no overheads from things like identity managers - just \"run this query and give me the (typed) data\". [...] Quite possibly the fastest materializer available for .NET.</p>\n</blockquote></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T02:33:19.877",
"Id": "35271",
"ParentId": "20075",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T11:21:02.137",
"Id": "20075",
"Score": "3",
"Tags": [
"c#",
"entity-framework"
],
"Title": "Mapping Query Result with Entity Properties"
}
|
20075
|
<p>I'm asking for suggestions on a random accessed vector with allocated elements sorted by its key obtained from its member function.</p>
<p>I use it with Qt tree view where the access, add and deletion of tree items is implemented via its index or row number. And I want all the tree items are automatically sorted under a tree node.</p>
<p>If I use <code>std::set</code>, I need to calculate the index first (such as using distance function) when adding an item under a tree node and need a binary search when deleting and accessing an item.</p>
<p>Sorted pointer vectors can access items quickly but require moving pointers when adding and deleting an item. Compare all the advantages and disadvantages, I think this can give better performance</p>
<p>Am I right? Does anyone have experience on it or better suggestions?</p>
<pre><code>#pragma once
#include <vector>
#include <memory>
#include <algorithm>
//! A random accessed vector with allocated elements sorted by
//! its key obtained from its member function.
//! - Duplicate elements are not allowed.
template<class T, class K, K (T::*MemFun)() const>
class SortedPtrVector
{
public:
SortedPtrVector() {}
//! Add an element, return its index.
bool Add(std::unique_ptr<T> element, int& index)
{
if (!Find((element.get()->*MemFun)(), index))
{
m_vector.insert(m_vector.begin() + index, std::move(element));
return true;
}
return false;
}
//! Find the element with a key.
//! - Return true when found and record its index;
//! - Return false when not found and record its lower bound.
bool Find(const K& key, int& index) const
{
if (m_vector.empty())
{
index = 0;
return false;
}
index = LowerBound(key);
if (index >= m_vector.size())
return false;
if ((m_vector[index].get()->*MemFun)() == key)
return true;
return false;
}
//! Return an index to the first element which does not compare less than the key.
int LowerBound(const K& key) const
{
int first = 0;
int count = m_vector.size();
while (count > 0)
{
int i = first;
int step = count / 2;
i += step;
if ((m_vector[i].get()->*MemFun)() < key)
{
first = ++i;
count -= step + 1;
}
else
{
count = step;
}
}
return first;
}
//! Delete an element at an index.
void DeleteAt(int index)
{
m_vector.erase(m_vector.begin() + index);
}
//! Delete an element with a key.
void Delete(const K& key)
{
int index;
if (Find(key, index))
DeletaAt(index);
}
//! Clear.
void Clear()
{
m_vector.clear();
}
unsigned Size() {return m_vector.size();}
const T& operator [](unsigned i) const {return *m_vector[i];}
private:
std::vector<std::unique_ptr<T>> m_vector;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T04:31:56.350",
"Id": "32091",
"Score": "1",
"body": "This looks a lot like an _associative ordered container_, but fails to expose the interface we expect from _associative ordered containers_ in **C++**."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T04:50:13.533",
"Id": "32092",
"Score": "0",
"body": "It seems like there would be a weirdly specific use-case for this class? But interesting, nonetheless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T23:31:29.127",
"Id": "89504",
"Score": "1",
"body": "What's with the C# (TitleCase) method naming?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-27T00:02:37.437",
"Id": "89515",
"Score": "2",
"body": "Can you add a 10-20 line example using it? Nothing fancy."
}
] |
[
{
"body": "<p>There's probably much that can be done here, but I'll point out some things I've noticed:</p>\n\n<ul>\n<li><p>As @David Harkness has mentioned in the comments, the method-naming looks like C# naming (uppercase, or PascalCase). While this isn't necessarily a bad thing as C++ is more flexible with naming, one problem here is that your types (particularly the class) and functions use the same naming convention, which may cause confusion for others.</p>\n\n<p>I would use separate naming for both of them, such as by changing the functions to camelCase or snake_case, while keeping the types as is.</p></li>\n<li><p>Since you're not overloading the default constructor, you don't have to include it. The compiler will make a default one for you.</p>\n\n<p>However, with C++11, you can now use <a href=\"http://en.cppreference.com/w/cpp/language/default_constructor\" rel=\"nofollow\"><code>default</code> constructors</a>:</p>\n\n<pre><code>SortedPtrVector() = default;\n</code></pre></li>\n<li><p>It looks like <code>Add()</code> is doing too many things:</p>\n\n<ol>\n<li>the actual adding</li>\n<li>updating a reference</li>\n<li>returning a <code>bool</code></li>\n</ol>\n\n<p>Based on the name, it should just attempt to add something. But if it's still necessary to update the index, then it should just return that. You could instead return an <code>std::pair<iterator, bool></code> as done with <a href=\"http://en.cppreference.com/w/cpp/container/map/insert\" rel=\"nofollow\"><code>std::map::insert</code></a>, but that may not be what you want here.</p></li>\n<li><p><code>Find()</code> shouldn't set <code>index</code> to <code>0</code> if the vector is empty. An index of <code>0</code> <em>is</em> a valid position for a non-empty container (the first position). Instead, it could return <code>-1</code>, which is an out-of-bounds value commonly used with not found (this is also the same value as the constant <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/npos\" rel=\"nofollow\"><code>std::string::npos</code></a>).</p>\n\n<p>It may also be better to have <code>Find()</code> return an index instead of a <code>bool</code>. Assuming this is to somewhat resemble <a href=\"http://en.cppreference.com/w/cpp/container/map/find\" rel=\"nofollow\"><code>std::map::find</code></a>, it can return a past-the-end value (an iterator) if the key isn't found.</p></li>\n<li><p><code>DeleteAt()</code> may do something problematic if the argument isn't checked prior to calling <code>erase()</code> (an invalid index can cause <code>erase()</code> to attempt access to some other location, leading to undefined behavior).</p></li>\n<li><p><code>Size()</code> should be <code>const</code> as it's not modifying any data members. You could also make it <a href=\"http://en.cppreference.com/w/cpp/keyword/noexcept\" rel=\"nofollow\"><code>noexcept</code></a> (also C++11) since it's guaranteed not to throw.</p>\n\n<p>Also, <code>unsigned</code> is not quite the <em>specific</em> return type of <code>std::size()</code>. It should either return an <code>std::size_t</code> (usually assumed), <code>std::vector<std::unique_ptr<T>>::size_type</code> (very lengthy), or even better and shorter with C++14 (if your compiler also supports it): the type deduced by <a href=\"http://en.cppreference.com/w/cpp/language/auto\" rel=\"nofollow\"><code>auto</code></a>.</p>\n\n<pre><code>auto Size() const noexcept { return m_vector.size(); }\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T23:35:25.000",
"Id": "89506",
"Score": "0",
"body": "`Find` sets `index` to the result of `LowerBound` which for an empty list is the first position, `0`, where the missing item would be inserted. I agree `Find` should return the found item's index and `-1` when not found and drop the `index` reference, but the code is internally consistent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T23:37:28.657",
"Id": "89507",
"Score": "0",
"body": "@DavidHarkness: So, you're saying that `Find()` is (generally) okay, with the exception of the `-1`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T23:51:46.373",
"Id": "89511",
"Score": "0",
"body": "No, I'm saying given the current implementation, setting `index` to `0` is consistent. Changing it to use `-1` *and nothing else* would break `Add`. But I wholeheartedly agree with your suggestion of rewriting `And` and `Find` completely. Yes, that pretty much makes my comment moot. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T23:59:33.770",
"Id": "89514",
"Score": "0",
"body": "@DavidHarkness: Ah, okay. To me, it does make sense to change `Find()` as mentioned, at least if this is supposed to closely resemble an associative container."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-26T23:21:51.670",
"Id": "51786",
"ParentId": "20079",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T00:20:09.993",
"Id": "20079",
"Score": "7",
"Tags": [
"c++",
"c++11",
"vectors",
"smart-pointers"
],
"Title": "A pointer vector sorted by its member function"
}
|
20079
|
<p>I am working on a little browsergame project written in PHP and using PostgreSQL as DBMS. Now I'm not really lucky with the process started after a userlogin was successful.</p>
<p>Some info:</p>
<ul>
<li>There are 3 different kinds of properties a game character can have:
<ul>
<li>Attributes</li>
<li>Skills</li>
<li>Talents</li>
</ul></li>
<li>Each of these properties is a table in my database</li>
<li>Each of these properties is related to the character table in an extra table</li>
<li>After the login was successful I want to store both <em>general information</em> about these properties and the <em>character-related values</em> of them in the session (the first in 'game' and the second in 'user').</li>
</ul>
<p>How I currently get the data:</p>
<pre><code>[...]
$this->getIngameInfo();
//one account can have up to 4 characters
//each of the characters can have different values
foreach($_SESSION['user']['character'] as $key => $data){
$_SESSION['user']['character'][$key]['attribute'] = $this->getAttributes($data['id']);
$_SESSION['user']['character'][$key]['skill'] = $this->getSkills($data['id']);
$_SESSION['user']['character'][$key]['talent'] = $this->getTalents($data['id']);
}
[...]
private function getIngameInfo(){
$sql = "SELECT id,
name,
tag,
description
FROM attribute";
if($this->db->query($sql, array())){
while($row = $this->db->fetchAssoc()){
$_SESSION['game']['attribute'][] = $row;
}
}
$sql = "SELECT id,
name,
tag,
description
FROM skill";
if($this->db->query($sql, array())){
while($row = $this->db->fetchAssoc()){
$_SESSION['game']['skill'][] = $row;
}
}
$sql = "SELECT id,
name,
description
FROM talent";
if($this->db->query($sql, array())){
while($row = $this->db->fetchAssoc()){
$_SESSION['game']['talent'][] = $row;
}
}
}
private function getAttributes($charid){
$sql = "
SELECT attributeid,
value
FROM character_attribute
WHERE characterid = $1
ORDER BY attributeid ASC
";
$attributes = array();
if($this->db->query($sql, array($charid))){
while($row = $this->db->fetchAssoc()){
$attributes[] = $row;
}
}
return $attributes;
}
private function getSkills($charid){
$sql = "
SELECT skillid,
value
FROM character_skill
WHERE characterid = $1
ORDER BY skillid ASC
";
$skills = array();
if($this->db->query($sql, array($charid))){
while($row = $this->db->fetchAssoc()){
$skills[] = $row;
}
}
return $skills;
}
private function getTalents($charid){
$sql = "
SELECT talentid,
value
FROM character_talent
WHERE characterid = $1
ORDER BY talentid ASC
";
$talents = array();
if($this->db->query($sql, array($charid))){
while($row = $this->db->fetchAssoc()){
$talents[] = $row;
}
}
return $talents;
}
</code></pre>
<p>I now wonder how I could merge these quite similar queries, because I'll need to fetch more information after that and I don't like firing so much queries in one process.</p>
<p>I thought about using prepared statements (I use a self-written pgsql-PDO-class), but I am not calling the same table multiple times (and table 'talent' does not have exactly the same columns as the other both).<br />
I also mentioned creating one or two stored procedures which return all the needed data. But in this case I would not know how to assign such a bunch of data to the different named sessionarrays.</p>
<p>The methods shown belong to a loginmodel and are called only one time. I used the sessionarray because the properties of a character should be shown in different ways (which would lead to caching) and used for calculations in different ways. As I don't like firing queries against the db to calculate with values that maybe did not change I didn't see a real alternative to sessions.</p>
<p>Think about that:</p>
<ul>
<li>Fetch character properties once after login</li>
<li>Depending on user's interactions, show (cached if not changed) or calculate (? if not changed) with these properties</li>
<li>Depending on user's interactions, change these properties, update db and update session</li>
</ul>
<p>TODO:</p>
<ul>
<li>Encapsulate sessiondata in another model</li>
<li>Use prepared queries for <code>getAttributes</code>, <code>getSkills</code> and <code>getTalents</code> </li>
<li>Sum them to one method </li>
<li>Move it to another model, as it will be not only needed when logging in, but when chars interact with other chars (wasn't away of)</li>
</ul>
<p>I would like to know how I can reduce the queries and simplify the code/improve performance of the script.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T07:29:24.320",
"Id": "32243",
"Score": "0",
"body": "I'm too lazy to write out a full answer, and this was hinted at by the answers below, but a little note: storing the data in a session has a major problem that wasn't made explicit. What if the data changes while it's in a session? Suddenly you've stored stale data. This gets even more complicated if it's possible for someone other than the session holder to alter the data. There's no clean way to 'invalidate' session data across all sessions. $_SESSION is not a magical cache. Using it as a cache is typically a sign of premature optimization (what I think it mostly is here) or flawed design"
}
] |
[
{
"body": "<p>Here's how I would write this:</p>\n\n<pre><code>[...]\n$this->getIngameInfo();\n\n//one account can have up to 4 characters\n//each of the characters can have different values \nforeach($_SESSION['user']['character'] as $key => $data){\n $_SESSION['user']['character'][$key]['attribute'] = $this->getAttributes($data['id']);\n $_SESSION['user']['character'][$key]['skill'] = $this->getSkills($data['id']);\n $_SESSION['user']['character'][$key]['talent'] = $this->getTalents($data['id']);\n}\n[...]\n\nprivate function getIngameInfo(){\n if ($this->db->query('SELECT \"id\", \"name\", \"tag\", \"description\" FROM \"attribute\";', array())){\n while($row = $this->db->fetchAssoc()) $_SESSION['game']['attribute'][] = $row;\n }\n\n if($this->db->query('SELECT \"id, \"name\", \"tag\", \"description\" FROM \"skill\";', array())){\n while($row = $this->db->fetchAssoc()) $_SESSION['game']['skill'][] = $row;\n }\n\n if($this->db->query('SELECT \"id\", \"name\", \"description\" FROM \"talent\";', array())){\n while($row = $this->db->fetchAssoc()) $_SESSION['game']['talent'][] = $row;\n }\n}\n\nprivate function getAttributes($charid){\n if (is_set($this->attributes_array)) return $this->attributes_array;\n\n $attributes = array();\n\n if($this->db->query('SELECT \"attributeid\", \"value\" FROM \"character_attribute\" WHERE \"characterid\" = $1 ORDER BY \"attributeid\" ASC;', array($charid))){\n while($row = $this->db->fetchAssoc()) $attributes[] = $row;\n }\n $this->attributes_array = $attributes;\n return $attributes_array;\n}\n\nprivate function getSkills($charid){\n $skills = array();\n\n if($this->db->query('SELECT \"skillid\", \"value\" FROM \"character_skill\" WHERE \"characterid\" = $1 ORDER BY \"skillid\" ASC;', array($charid))){\n while($row = $this->db->fetchAssoc()) $skills[] = $row;\n }\n return $skills;\n}\n\nprivate function getTalents($charid){\n $talents = array();\n\n if($this->db->query('SELECT \"talentid\", \"value\" FROM \"character_talent\" WHERE \"characterid\" = $1 ORDER BY \"talentid\" ASC;', array($charid))){\n while($row = $this->db->fetchAssoc()) $talents[] = $row;\n }\n return $talents;\n}\n</code></pre>\n\n<p>If your if or while statements only include 1 operation, I prefer to have it after the operation without using {}. But, since your if statements are really long, I think it's fine to user {} and break those up then.</p>\n\n<p>I would get away from putting everything into $_SESSION, especially information that doesn't need to belong there like game configuration. It doesn't seem (and I wouldn't think) you read-in from the $_SESSION (are you going to read 'talent' type?). Only session information should be there. Create a \"$gameConfiguration\" array where you store the same as $_SESSION['game'].</p>\n\n<p>getIngameInfo() seems to just be configuration information. Could this be cached? Take the $_SESSION['game'] array, serialize it and store it in a (.gz) file. This would save 3 db calls per page.</p>\n\n<p>Under getAttributes, if there's a chance that this gets called more than once, I would store a <code>$getAttributes</code> array under each class and check if it's already set. This would save duplicate work (though increase memory usage).</p>\n\n<p>I would prepare the queries under \"getAttributes\", \"getSkills\" and \"getTalents\". While they are only going to run at most 4 times per load (4 characters), you are most of the way there with your custom PDO since your queries are already in that style.</p>\n\n<p>PHP processes \"\" for variables and more. Switching to '', PHP doesn't process the string for variables, it's just takes it at its value.</p>\n\n<p>Don't store $sql query if you don't need that variable. There are times your query needs conditionals so you need to have a variable, and during debugging it's nice to have it so you can display the variable to see if it's working right, but otherwise there's no need.</p>\n\n<p>Does your custom PDO need an empty array passed? Could you use NULL for greater clarity (and less brackets)?</p>\n\n<p>Using quotes on your query for system identifiers is better for the db.</p>\n\n<p>I don't like having conditionals on non-conditional items. That is:\n<code>if ($this->db->query('SELECT \"id\", \"name\", \"tag\", \"description\" FROM \"attribute\";', array())){</code> where instead you do:</p>\n\n<pre><code>$result = $this->db->query('SELECT \"id\", \"name\", \"tag\", \"description\" FROM \"attribute\", array());'\nif ($result -> numRows() > 0){\n while($result = $this->db->fetchAssoc()) $_SESSION['game']['attribute'][] = $row;\n}\n</code></pre>\n\n<p>though this depends on how your custom returns/handles queries/results.</p>\n\n<p>Generally, all relatively minor improvements though. Posting the whole class and you might get more useful help.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T14:42:59.427",
"Id": "32157",
"Score": "0",
"body": "You should really avoid the braceless syntax. Someone never having seen it before could easily add more than one operation after such a statement and not understand why it doesn't work. Even for those familiar with it it is still really easy to do. Additionally it is inconsistent with the style for the rest of the application. Consistency in style ensures that the code can more easily be read and scanned. Finally, the syntax itself is usually less legible, though this could be argued. I'd keep those braces unless forced (legacy code base, etc...)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T00:28:21.643",
"Id": "32235",
"Score": "0",
"body": "Many thanks for the help! I hope some of your questions could be answered in my questionedit. My db-class indeed does not need to get an empty array, I can leave this parameter."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T15:59:55.270",
"Id": "20093",
"ParentId": "20082",
"Score": "1"
}
},
{
"body": "<p>I agree with MECU about not storing everything in the session. Caching is probably the best way to go. Sessions are typically used for continuity between page loads. Meaning you can store information like the character ID or login status, but the rest should be done differently. So, even though I'm about to start explaining how to better do what you are trying to accomplish with your sessions, I hope you will apply it to whatever new method you come up with.</p>\n\n<p>Speaking of sessions. Using an outside resource, such as sessions or cookies or post, is a violation of the Law of Demeter (LoD). Simply put, this law suggests that your code, either method/function or class, not know more than is necessary to accomplish its task. Right now you have your entire class tightly coupled with the session. What if, as both MECU and I suggested, you wanted to move away from using the session? Then you'd have to rewrite this entire class. The better thing to do would be to write this class in such a way as to not be dependent upon it in the first place. You could instead return these same arrays to your main application to then apply them to the session array or even a cache. You could also inject any outside parameters you needed into your method's arguments to share initial values. Always try to write your code so that it is as reusable as possible.</p>\n\n<p>Now, you can more easily get the character stats by following the \"Don't Repeat Yourself\" (DRY) Principle. As the name implies, your code should not repeat itself. So, instead of writing out that long array pointer multiple times, you can more easily, and cleanly, create a new array and merge the two when you are done. Additionally, you can abstract the <code>$data[ 'id' ]</code> to its own variable as well to make this even easier.</p>\n\n<pre><code>$stats = array();\nforeach( $_SESSION[ 'user' ] [ 'character' ] AS $key => $data ) {\n $id = $data[ 'id' ];\n\n $stats[ $key ] = array(\n 'attribute' => $this->getAttributes( $id ),\n 'skill' => $this->getSkills( $id ),\n 'talent' => $this->getTalents( $id )\n );\n}\n\n//use array_merge_recursive if you want to keep original $data array\narray_merge(\n $_SESSION[ 'user' ] [ 'character' ],\n $stats\n);\n</code></pre>\n\n<p>Seen as how you use the same \"id\" to access the attributes, skills, and talents, it would make more sense to create a new method to get all three and return the results in an array, similar to the one above. This follows two core OOP principles, the first I already mentioned, DRY, and Single Responsibility. This new principle means that our methods should be responsible for just one thing. If our methods are responsible for more than one task, then that makes them harder to reuse and we typically end up repeating code to accomplish similar tasks, which violates the first principle again. Its a vicious cycle.</p>\n\n<pre><code>private function getStats( $id ) {\n return array(\n 'attribute' => $this->getAttributes( $id ),\n 'skill' => $this->getSkills( $id ),\n 'talent' => $this->getTalents( $id )\n );\n}\n</code></pre>\n\n<p>MECU mentioned something similar, but I think it should be elaborated. He expressed a dislike for using non-conditionals as a conditional statement. This is a good thing to be adverse to. Complex conditionals should also be avoided. Complex meaning nested parenthesis, or long lists of conditionals, or even just a long condition. I don't see any of the latter, so I'll just cover the first. Both of these types of statements tend to cause issues with legibility, thus the need for abstracting the conditional to a variable. At first glance the first statement is hard to read because the parenthesis tend to run together. The second statement is a little better, but only because I added whitespace around the parenthesis, this just happens to be my style for this very reason. The third abstracts this to avoid excessive nesting, making it even easier to read than the second and allows for potential expansion should you want to use the <code>$result</code> later.</p>\n\n<pre><code>//a complex conditional\nif($this->db->query($sql, array())){\n//a complex conditional using whitespace\nif( $this->db->query( $sql, array() ) ) {\n\n//compared to...\n$result = $this->db->query( $sql, array() );\nif( $result ) {\n</code></pre>\n\n<p>I demonstrated DRY a couple of times above, so I'll leave this one to you. Your <code>getIngameInfo()</code> shows a more standard violation of DRY. It queries the database three times in a very similar method. The only thing that really changes is the SQL used and the portion of the session \"game\" array. I would suggest creating a new method to accomplish this for you. In fact, that new method can probably be reused for the <code>getAttributes()</code>, <code>getSkills()</code>, and <code>getTalents()</code> methods as well. I would use those later 3 methods as a template and use the returned array to populate your session.</p>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T00:37:42.707",
"Id": "32236",
"Score": "0",
"body": "That helps a lot ;) thanks for pointing out the principles, I will keep them in mind. Instead of copying values like $id = $data[ 'id' ] I would prefere using references - do you see problems here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T15:13:25.183",
"Id": "32353",
"Score": "0",
"body": "@32bitfloat: What do you mean by references? [These are references](http://php.net/manual/en/language.references.whatdo.php) and they don't seem to fit with your question nor do I even see how using them would help."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T16:01:32.203",
"Id": "20127",
"ParentId": "20082",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20127",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-01T22:12:40.607",
"Id": "20082",
"Score": "2",
"Tags": [
"php",
"performance",
"session",
"postgresql"
],
"Title": "Browser game project"
}
|
20082
|
<p>I have this code that converts audio to different file formats:</p>
<pre><code>import java.io.File;
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;
/* required jars(jave-1.0.2.jar)
* Handles Encoding and Decoding
* Audio to different file formats
*/
public class AudioEncoderDecoder {
private static final Integer bitrate = 256000;//Minimal bitrate only
private static final Integer channels = 2; //2 for stereo, 1 for mono
private static final Integer samplingRate = 44100;//For good quality.
/* Data structures for the audio
* and Encoding attributes
*/
private AudioAttributes audioAttr = new AudioAttributes();
private EncodingAttributes encoAttrs = new EncodingAttributes();
private Encoder encoder = new Encoder();
/*
* File formats that will be converted
* Please Don't change!
*/
private String oggFormat = "ogg";
private String mp3Format = "mp3";
private String wavFormat = "wav";
/*
* Codecs to be used
*/
private String oggCodec = "vorbis";
/* Set the default attributes
* for encoding
*/
public AudioEncoderDecoder(){
audioAttr.setBitRate(bitrate);
audioAttr.setChannels(channels);
audioAttr.setSamplingRate(samplingRate);
}
public void encodeAudio(File source, File target, String mimeType){
//Change the hardcoded mime type later on
if(mimeType.equals("audio/mp3")){
this.mp3ToOgg(source, target);
}
}
private void mp3ToOgg(File source, File target){
//ADD CODE FOR CHANGING THE EXTENSION OF THE FILE
encoAttrs.setFormat(oggFormat);
audioAttr.setCodec(oggCodec);
encoAttrs.setAudioAttributes(audioAttr);
try{
encoder.encode(source, target, encoAttrs);
}catch(Exception e){
System.out.println("Encoding Failed");
}
}
private void oggToMp3(){
//ADD CODE FOR CHANGING THE EXTENSION OF THE FILE
encoAttrs.setFormat(mp3Format);
audioAttr.setCodec(mp3Codec);
encoAttrs.setAudioAttributes(audioAttr);
try{
encoder.encode(source, target, encoAttrs);
}catch(Exception e){
System.out.println("Encoding Failed");
}
}
public static void main(String[] args){
AudioEncoderDecoder aed = new AudioEncoderDecoder();
File source = new File("singelementsmp3.mp3");
File target = new File("test.ogg");
//Test Mp3 To Ogg Convertion
String mimeType = "audio/mp3";
aed.encodeAudio(source, target, mimeType);
//Test Ogg To Mp3 Convertion
}
}
</code></pre>
<p>Now, the xToX conversion basically the same throughout the whole code implementation. The only thing will change is the codec.</p>
<p>What is another way to make this code cleaner? From my point of view it repeats itself. What should I change? Or are there any design patterns I should implement?</p>
|
[] |
[
{
"body": "<h2>Overall</h2>\n\n<p>Design first.</p>\n\n<h2>Name and semantic of your class</h2>\n\n<blockquote>\n <p>I have this code that converts audio to different file formats.</p>\n</blockquote>\n\n<p>Not exactly, your code is a client to an <code>Encoder</code>, that converts audio to different file formats.\nIn design, it is very important to be certain about the reason and semantic of an object. So first, the name <code>AudioEncoderDecoder</code> is bad. It says nothing about the sematic of the object. I would call it <code>AudioFormatConverter</code> as it converts one audio file format to another.</p>\n\n<h2>Public methods</h2>\n\n<pre><code>public void encodeAudio(File source, File target, String mimeType);\n</code></pre>\n\n<p>a) Naming <code>encodeAudio()</code> is not clear, <code>convert()</code> would be clear and consistent with the classname.</p>\n\n<p>b) Parameters: source, target file seems good. But why would I pass in the mimeType? And how can I specify which target format I choose?</p>\n\n<p>Expected method signature:</p>\n\n<pre><code>public void convert(File source, File target) throws AudioConversionException();\n</code></pre>\n\n<p>One conversion method in the public interface, source and target file, the mime type is guessed by the file extension. You could add another public method, where you take in the mimetype, as needed. But keep the interface of your class as simple, logic, consistent and understandable as possible.</p>\n\n<p>I would declare an checked exception for error handling, formats not avail or whatever.</p>\n\n<h2>Design Patterns</h2>\n\n<p>If there will be more formats, codecs, mimetypes you could take a look at <a href=\"http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern\" rel=\"noreferrer\">Chain of responsibility</a> or Dispatcher/<a href=\"http://en.wikipedia.org/wiki/Command_pattern\" rel=\"noreferrer\">Command</a> pattern. \nThese patterns also add flexibility to easily support more mimetypes at runtime.\nWithout those patterns, you may get a mid-to-big if/then/else block.</p>\n\n<p>Possible Design with Command, Strategy pattern applied:\n<img src=\"https://i.stack.imgur.com/F9uCy.png\" alt=\"Possible design of AudioFormatConverter\"></p>\n\n<ul>\n<li><code>AudioFormatConverter</code>s interface is format-agnostic, this means it is possible to implement a converter, that doesn't use Files but only InputStreams or byte[] arrays.</li>\n<li>Concrete <code>AudioFileFormatConverter</code> converts from and to <code>File</code>s, and holds a list of supported <code>ConversionCommand</code>s</li>\n<li><code>ConversionCommand</code> encapsulates logic to convert things, a client can check via <code>isSupported(source, target)</code> if the source-format and target-format is supported by this command (handler would by a common name, too)</li>\n<li><code>Mp3ToOggConversionCommand</code> Every conversion is a command, one can decide that this is too much, but with that you can save state in the command, like executation duration, error states, sizes, redo, undo, execute asynchronous...</li>\n<li><code>ConversionStrategy</code> with Impl <code>EncoderConversionStrategy</code> encapsulates the concrete implementation of conversion, that is your duplicate code, this strategy how to convert 2 files by using the Encoder</li>\n</ul>\n\n<p>Note that ConversionCommands should be prototypes, so that each execute happens in its own Command instance.</p>\n\n<p>Now in code, you would setup the AudioFileFormatConverter and add the supported ConversionCommands to it.</p>\n\n<h2>Existing code</h2>\n\n<p>Obey the basic OO principles. </p>\n\n<ul>\n<li>DRY - Don't repeat yourself. If you find code is duplicate, introduce\nabstractions or extract methods. </li>\n<li>Use interfaces</li>\n</ul>\n\n<p>In your case you can easily improve the code if you generalize the <code>mp3ToOgg</code> and <code>oggToMp3</code> methods.</p>\n\n<p>So that you have only one general method for converting with the signature:</p>\n\n<pre><code>private void convert(File source, File target, String format, String codec);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T04:13:02.443",
"Id": "32123",
"Score": "0",
"body": "What if I have other conversions? wavtOmp3, mp3ToWav, oggToWav, WavToOgg, what is the preferreable approach?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T04:46:31.650",
"Id": "32127",
"Score": "0",
"body": "Also why would I use the Command Pattern? I can see the reason for chain of responsibility but not for command pattern"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T07:08:05.360",
"Id": "32130",
"Score": "0",
"body": "edited answer, chain and command relate a bit in this as you see"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T07:10:32.477",
"Id": "32131",
"Score": "0",
"body": "Also, I have implemented the Command Pattern in my case, please look at this also what do you mean by prototype http://codereview.stackexchange.com/questions/20114/have-i-implemented-the-command-pattern-correctly"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T15:20:57.087",
"Id": "20090",
"ParentId": "20084",
"Score": "7"
}
},
{
"body": "<p>Have you considered using a single method?</p>\n\n<pre><code>private void XToY(format,codec,source, target){ \n //ADD CODE FOR CHANGING THE EXTENSION OF THE FILE\n encoAttrs.setFormat(format);\n audioAttr.setCodec(codec);\n encoAttrs.setAudioAttributes(audioAttr);\n try{\n encoder.encode(source, target, encoAttrs);\n }catch(Exception e){\n System.out.println(\"Encoding Failed\");\n }\n}\n</code></pre>\n\n<p>You can theoretically use this one method to convert any source type to any target type.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T07:00:38.423",
"Id": "32129",
"Score": "0",
"body": "I do not change the extension, I literraly convert the file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T12:58:50.823",
"Id": "32149",
"Score": "0",
"body": "I simply generalized your own code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T06:59:26.270",
"Id": "20112",
"ParentId": "20084",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20090",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T08:57:43.233",
"Id": "20084",
"Score": "5",
"Tags": [
"java",
"performance",
"converting",
"interface",
"audio"
],
"Title": "Converting audio to different file formats"
}
|
20084
|
<p>Here is the code: <a href="https://github.com/EarlGray/haskell-snippets/blob/master/ext2hs/Ext2.hs" rel="nofollow">https://github.com/EarlGray/haskell-snippets/blob/master/ext2hs/Ext2.hs</a></p>
<p>My problem is that it is quite painful to make large Haskell "records" and deserialize a binary layout with <code>Data.Binary.Get</code> manually like this:</p>
<pre><code>instance Binary Superblock where
get = binGetSuperblock
binGetSuperblock = do
uint13 <- replicateM 13 getWord32le
ushort6 <- replicateM 6 getWord16le
uint4 <- replicateM 4 getWord32le
ushort2 <- replicateM 2 getWord16le
return Superblock {
sInodesCount = uint13 !! 0, sBlocksCount = uint13 !! 1,
sReservedBlocksCount = uint13 !! 2, sFreeBlocksCount = uint13 !! 3,
sFreeInodesCount = uint13 !! 4, sFirstDataBlock = uint13 !! 5,
sLogBlockSize = uint13 !! 6, sLogClusterSize = uint13 !! 7,
sBlocksPerGroup = uint13 !! 8, sClustersPerGroup = uint13 !! 9,
sInodesPerGroup = uint13 !! 10, sMountTime = uint13 !! 11,
sWriteTime = uint13 !! 12,
sMountsCount = ushort6 !! 0, sMaxMountsCount = int (ushort6 !! 1),
sMagic = ushort6 !! 2, sState = ushort6 !! 3,
sErrors = ushort6 !! 4,
sLastCheckTime = uint4 !! 0, sCheckInterval = uint4 !! 1,
sCreatorOS = uint4 !! 2, sRevLevel = (uint4 !! 3, ushort6 !! 5),
sDefaultResUID = ushort2 !! 0, sDefaultResGID = ushort2 !! 1,
sDynRev = Nothing,
sPrealloc = Nothing,
sJournaling = Nothing
}
</code></pre>
<p>(this is ext2fs superblock structure).</p>
<p>First of all, I would like to make binary layout as much declarative as possible, abstracting away those ugly sequences of <code>getWord32le</code> in <code>Get</code> monad with temporary fields. I want something like my python code, where <a href="https://github.com/EarlGray/ext2py/blob/master/ext2.py" rel="nofollow">binary fields are unpacked to a map according to a <code>struct</code> format string</a></p>
<p>The second thing I need is a more concise and more clear way for initializing a large Haskell record (creating a lot of temporary named values in the monad is pain).</p>
<p>One way I think of is to read binary fields into a heterogeneous map <code>forall a. BinaryField a => Map String a</code>, accessing each value by its name and pre-extracting most used ones to Haskell.
Perhaps Template Haskell and code generation from a declarative format may help, but I have no experience with TH yet. </p>
<p>I would be glad to hear any suggestions or hints about a more idiomatic way (are there any relevant tools?) or about the code in general (though it's just my learning code and it's very incomplete at the moment).</p>
|
[] |
[
{
"body": "<p>A way to avoid those temporary values and (!!) operators, at the cost perhaps of some obscurity, would be something like the following:</p>\n\n<pre><code>import Control.Applicative ((<$>),(<*>),pure)\n\nbinGetSuperblock' = do \n partiallyAppliedConstructor <- Superblock \n <$> getWord32le\n <*> getWord32le\n <*> getWord32le\n <*> getWord32le\n <*> getWord32le\n <*> getWord32le\n <*> getWord32le\n <*> getWord32le\n <*> getWord32le\n <*> getWord32le\n <*> getWord32le\n <*> getWord32le\n <*> getWord32le\n <*> getWord16le\n <*> (int <$> getWord16le)\n <*> getWord16le\n <*> getWord16le\n outOfPlace16 <- getWord16le\n partiallyAppliedConstructor \n <$> getWord16le\n <*> getWord32le\n <*> getWord32le\n <*> (OSEnum <$> getWord32le)\n <*> ((,) <$> getWord32le <*> pure outOfPlace16)\n <*> getWord16le\n <*> getWord16le\n <*> pure Nothing\n <*> pure Nothing\n <*> pure Nothing\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T00:35:05.243",
"Id": "32182",
"Score": "0",
"body": "Looks good. Do you have any suggestions how to fold this with a heterogeneous list of operations (assuming that there are no out-of-place fields)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T00:51:33.337",
"Id": "32183",
"Score": "0",
"body": "But now I see that the ordinary `foldl` won't work here: its type is `(a -> b -> a) -> a -> [b] -> a`; since application of `<*>` changes the type of partially constructed record, `(a0 -> b -> a1)` must be used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T07:35:33.623",
"Id": "32189",
"Score": "0",
"body": "@EarlGray: I take you mean to reduce repetition in those \"getWord32le\" by supplying a list of them and \"filling them\" in the record, in order. I suspect you would need Template Haskell for that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T23:02:28.877",
"Id": "20135",
"ParentId": "20086",
"Score": "1"
}
},
{
"body": "<p>To add one more suggestion - building records can be simplified quite a bit by using the <code>RecordWildCards</code> extension, which automatically populates fields from visible names (see <a href=\"http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#record-wildcards\" rel=\"nofollow\">GHC docs</a>). Personally, I consider it borderline essential for dealing with large records. I would probably write this like follows:</p>\n\n<pre><code>{-# LANGUAGE RecordWildCards #-}\n-- ...\nbinGetSuperblock = do\n [sInodesCount, sBlocksCount,\n sReservedBlocksCount, sFreeBlocksCount,\n sFreeInodesCount, sFirstDataBlock,\n sLogBlockSize, sLogClusterSize,\n sBlocksPerGroup, sClustersPerGroup,\n sInodesPerGroup, sMountTime,\n sWriteTime] <- replicateM 13 getWord32le\n [sMountsCount, sMaxMountsCount,\n sMagic, sState,\n sErrors, sRevLevel2] <- replicateM 6 getWord16le\n [sLastCheckTime, sCheckInterval,\n sCreatorOS, sRevLevel1] <- replicateM 4 getWord32le\n [sDefaultResUID, sDefaultResGID] <- replicateM 2 getWord16le\n return Superblock {\n sMaxMountsCount = int sMaxMountsCount,\n sRevLevel = (sRevLevel1, sRevLevel2),\n sDynRev = Nothing,\n sPrealloc = Nothing,\n sJournaling = Nothing,\n ..\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-14T13:57:02.410",
"Id": "20508",
"ParentId": "20086",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20135",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T10:53:15.443",
"Id": "20086",
"Score": "2",
"Tags": [
"haskell"
],
"Title": "Reducing boilerplate of binary layout handling in Haskell"
}
|
20086
|
<p>I have a list of pointers to objects where some of the objects contain a pointer to another object. When I remove an object in the list which has a linked object I need to remove them BOTH. I also want to position the next iterator at a convenient position which will usually be just after the object in the list which is to be deleted. Or if the linked item is next it will have to be just after the linked item.</p>
<p>There are peripheral issues such as why not using smart pointers etc. But this is just a simple demo - so please ignore lifecycle issues. I am looking for comments on the RemoveAllAssociated function.</p>
<pre><code> #include <iostream>
#include <list>
#include <algorithm>
using namespace std;
class A
{
public:
A(int timestamp) : m_timestamp(timestamp), m_red(false), m_linkedmsg(0) {}
virtual ~A() {}
int gettimestamp() const { return m_timestamp; }
A* getLinkedMsg() const { return m_linkedmsg; }
void setLinkedMsg(A* linked) { m_linkedmsg = linked; }
bool IsRed() const { return m_red; }
void setRed(bool col = true) { m_red = col; }
protected:
int m_timestamp;
bool m_red;
A* m_linkedmsg;
};
class B : public A
{
public:
B(int timestamp) : A(timestamp) { setRed(true); }
virtual ~B() {}
};
//erase item and linked iterator if available and return next iterator
std::list<A*>::iterator RemoveAllAssociated(std::list<A*>& thelist, A* item) {
std::list<A*>::iterator it = find(thelist.begin(), thelist.end(), item);
if(it != thelist.end()) {
cout << "found original item in list with timestamp=" << (*it)->gettimestamp() << "\n";
//we now want to delete linked as well as original
//first delete linked
A* linked = (*it)->getLinkedMsg();
std::list<A*>::iterator found_it = find(thelist.begin(), thelist.end(), linked);
if(found_it != thelist.end()) {
cout << "found linked item with timestamp=" << (*found_it)->gettimestamp() << "\n";
delete *found_it;
std::list<A*>::iterator after_linked_it = thelist.erase(found_it);
}
//now erase item in list
//Need to return next iterator. Usually will be just after item
//check a valid iterator returned
//We want iterator to be positioned either just after
delete *it; //or could have done: delete item;
return thelist.erase(it);
} else
cout << "original item not found in list\n";
return thelist.end();
}
int main() {
A* a1 = new B(0);
A* a2 = new B(1);
A* a3 = new B(2);
A* a4 = new B(3);
A* a5 = new B(4);
A* a6 = new B(5);
a2->setLinkedMsg(a1);
//put them in a list
std::list<A*> alist;
alist.push_back(a5);
alist.push_back(a6);
alist.push_back(a1);
alist.push_back(a2);
alist.push_back(a3);
alist.push_back(a4);
std::list<A*>::iterator it = RemoveAllAssociated(alist, a2);
if(it != alist.end())
cout << "next item in list is " << (*it)->gettimestamp() << endl;
//print out what is left to check correct items erased
for(it = alist.begin(); it != alist.end(); ++it) {
cout << "address=" << *it << " ts=" << (*it)->gettimestamp() << endl;
}
//cleanup
it = alist.begin();
while(it != alist.end()) {
delete *it;
it = alist.erase(it);
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>OK. This is <strong>NOT</strong> C++ code. This is C that happens to use a few C++ features like std::list. I would call this \"C with classes\".</p>\n\n<p>What you have failed to do is define the ownership of the pointers. Without ownership calling delete is a pain (because you don't know if calling delete is a good idea because you don't know the ownership).</p>\n\n<p>There is no point in reviewing further until you define ownership semantics.<br>\nWho owns the pointer.</p>\n\n<ul>\n<li>Is it shared ownership.</li>\n<li>Is it exclusive ownership.</li>\n<li>Are there cycles?</li>\n</ul>\n\n<p>This looks really awful:</p>\n\n<pre><code> A* a1 = new B(0);\n A* a2 = new B(1);\n A* a3 = new B(2);\n A* a4 = new B(3);\n A* a5 = new B(4);\n A* a6 = new B(5);\n</code></pre>\n\n<p>You have 6 RAW pointers. What happens if the constructor to <code>B(3)</code> throws an exception. Then you have just leaked <code>a1/a2/a3</code>. In modern C++ it is very rare to see RAW pointers. Pointers are usually contained inside an object (usually a smart pointer).</p>\n\n<p>Now you are passing the pointers to a list. </p>\n\n<pre><code> //put them in a list\n std::list<A*> alist;\n alist.push_back(a5);\n alist.push_back(a6);\n alist.push_back(a1);\n alist.push_back(a2);\n alist.push_back(a3);\n alist.push_back(a4);\n</code></pre>\n\n<p>So now you have two people pointing at each object. So who is supposed to destroy them? You have not defined the ownership semantics thus we do not know who is responsible for deleting the pointers. Even worse if they are deleted via one method the other pointer points at an invalid location (as there is no feedback) between the pointers.</p>\n\n<p>boost::ptr_list would hold and take ownership of the pointers very nicely.</p>\n\n<p>Cleanup outside a destructor!!!</p>\n\n<pre><code> //cleanup\n it = alist.begin();\n while(it != alist.end()) { \n delete *it;\n it = alist.erase(it);\n }\n</code></pre>\n\n<p>This is not exception safe. You need to use RAII to make sure you can never leak resources even in the presence of pointers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T18:54:45.483",
"Id": "20099",
"ParentId": "20087",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T11:51:07.380",
"Id": "20087",
"Score": "2",
"Tags": [
"c++"
],
"Title": "Function to erase original element but also linked"
}
|
20087
|
<p>The new <a href="http://html5bones.com/" rel="nofollow">HTML5 Bones</a> template uses the following example for the main content (I removed some parts (like ARIA, comments, <code>aside</code>, …) not relevant for this question):</p>
<pre><code><!-- The <section> element can be used to enclose content that comes under a related heading.
NOTE: The <section> element can contain <article> elements and vice versa, if you think the content warrants it. -->
<section>
<header>
<h2>Getting Started</h2>
<nav>
…
</nav>
</header>
<!-- The <article> element can be used to enclose content that still makes sense on its own and is therefore "reusable" -->
<article id="introduction">
<h3>Introduction</h3>
<p>Welcome to <abbr title="HyperText Markup Language 5">HTML5</abbr> Bones. This is a template that contains comments to aid you with setting up your <abbr title="HyperText Markup Language 5">HTML5</abbr> document.</p>
</article>
<!-- The <article> element can be used to enclose content that still makes sense on its own and is therefore "reusable" -->
<article id="instructions">
<h3>Instructions</h3>
<ol>
<li>Read the comments in this template</li>
<li>Decide how you think your content may fit into the template</li>
<li>Start building your document</li>
</ol>
</article>
</section>
</code></pre>
<p>The <a href="https://github.com/iandevlin/html5bones/blob/master/index.html" rel="nofollow">whole document</a> has the following outline:</p>
<blockquote>
<ol><li>HTML5 Bones<ol><li><i>Untitled Section</i></li><li>Getting Started<ol><li><i>Untitled Section</i></li><li>Introduction</li><li>Instructions</li><li>Did you know?</li></ol></li></ol></li></ol>
</blockquote>
<p>This outline is correct for the document. But I wonder if the use of the <code>section</code> element and the <code>article</code> elements is correct.</p>
|
[] |
[
{
"body": "<p>I think the <code>section</code> element should be an <code>article</code> element, and the two <code>article</code> elements should be <code>section</code> elements:</p>\n\n<pre><code><article>\n\n <h2>Getting Started</h2>\n\n <section id=\"introduction\">\n <h3>Introduction</h3>\n </section>\n\n <section id=\"instructions\">\n <h3>Instructions</h3>\n </section>\n\n</article>\n</code></pre>\n\n<p>While there are, of course, valid cases where a <code>section</code> element contains <code>article</code> elements, I think this not the case in this example.</p>\n\n<p>The \"Getting started\" content is without question the main content for this document. The <code>section</code> element <em>can</em> be used for that purpose, but the <code>article</code> element would fit, too. A simple question to ask: Could this <em>whole</em> \"Getting started\" article be an entry in a feed? If yes, use <code>article</code>.</p>\n\n<p>\"Introduction\" and \"Instructions\" are \"sub-chapters\" for \"Getting started\". Would it make sense to create separate entries for them in a feed? I don't think so.</p>\n\n<p>However, as this document is meant as a boilerplate and therefor doesn't contain much content, it is hard to decide here. If \"Introdcution\" and \"Instructions\" would contain more content, so that these chapters could stand on their own, the current sectioning element choice would be correct.</p>\n\n<p>But then there is the question: What would make more sense for the \"typical site\" the users of the <em>HTML5 Bones</em> template would create?</p>\n\n<p>I guess you find more documents that need \"<code>article > section</code>\" than \"<code>section > article</code>\".</p>\n\n<p>Examples:</p>\n\n<ul>\n<li>a blog: only the front page and the tag pages need <code>section > article</code>, but each blog entry needs <code>article > section</code>.</li>\n<li>an \"About us\" page on a company site: <code>article > section</code> (or <code>section > section</code>)</li>\n<li>a shop: only the product listings need <code>section > article</code>, but each product needs <code>article > section</code></li>\n</ul>\n\n<p>Of course, a template can't make the choice for all users/sites. The users need to know what is right for their content. But I feel like it's dangerous to \"default\" to this sectioning element choice. If in doubt, one should use rather <code>section</code> than <code>article</code>, because <code>section</code> is what you get <em>anyway</em> (simply by using headings), while <code>article</code> has special meaning.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T15:34:29.523",
"Id": "20092",
"ParentId": "20091",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T15:34:29.523",
"Id": "20091",
"Score": "1",
"Tags": [
"html5"
],
"Title": "Sectioning element choice for main content in HTML5 Bones"
}
|
20091
|
<p>The same view (a layout) used for all pages in Kohana3.3 project. That's why it could be placed in before() method instead of every action. Right?</p>
<p>Is there any better way to optimize the code below so you shouldn't use so many <code>$this-></code>? Are there any other improvements of this code so it looks really good?</p>
<pre><code>public function before()
{ //shows layout for all pages
$this->view = View::factory('layout');
$this->view->left_column='pass this string to layout';
}
public function action_index()
{ //index section on the page
$this->view->content = View::factory('index');
$this->view->content->text = 'some index text';
$this->response->body($this->view);
}
public function action_about()
{
//about section on the page
$this->view->content = View::factory('about');
$this->view->content->text = 'some about text';
$this->response->body($this->view);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T19:15:41.007",
"Id": "32103",
"Score": "1",
"body": "I don't get the question, your code is good. And $this refers to the object that it's in so why would you use less of it? Code is good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-30T10:05:59.983",
"Id": "32104",
"Score": "0",
"body": "Thank you for your comment! Now I'm sure I'm on the right track!"
}
] |
[
{
"body": "<p>Your code is violating the \"Don't Repeat Yourself\" (DRY) Principle, which is why it seems like you have \"too many\" <code>$this->*</code> lines. As the name implies, your code should not repeat. Usually, in an instance such as this, I would say to use the constructor and inject those values you need; However, I don't know for sure if the class you provided is also a factory, in which case you would use a wrapper method.</p>\n\n<pre><code>//non-factory method\npublic function __construct( $view, $text ) {\n $this->view->content = View::factory( $view );\n $this->view->content->text = $text;\n $this->response->body( $this->view );\n}\n\n//no other methods need, simply inject while instantiating\n\n//factory method\npublic function render( $view, $text ) {\n $this->view->content = View::factory( $view );\n $this->view->content->text = $text;\n $this->response->body( $this->view );\n}\n\npublic function action_index() {\n $this->render( 'index', 'some index text' );\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T20:16:17.013",
"Id": "20101",
"ParentId": "20095",
"Score": "1"
}
},
{
"body": "<p>You need extends from Controller Template like this</p>\n\n<pre><code>class Controller_Main extends Controller_Template {\n //This it the main html container i suggest use html5boilerplaite\n public function $_template = 'layout'; \n\n public function action_index() {\n $data = array();\n $this->template->content = View::factory('frontend/home',$data);\n }\n}\n\nclass Controller_Profile extends Controller_Main{\n\n public function action_index() {\n $data = array();\n $this->template->content = View::factory('frontend/profile',$data);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-11T20:40:59.157",
"Id": "20447",
"ParentId": "20095",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20101",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-29T08:54:54.427",
"Id": "20095",
"Score": "0",
"Tags": [
"php"
],
"Title": "Kohana newbie: setting a layout view and variables for layout in before()"
}
|
20095
|
<p>This is a little yet unfinished RPG I made with C#. It runs well but I'm wondering if there are things I could improve to make it more clear or optimal. I'm basically asking for some feedback and suggestions.</p>
<p>The program is obviously not finished but I'm asking now before I move on so I know if I got some serious design or logic issues there. I'm a beginner in programming so keep that in mind when answering.</p>
<pre><code>class Main
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("1. New Game\n" +
"2. Load Game\n" +
"3. Exit Game\n");
string choice = Console.ReadLine();
bool correctChoice = false;
Hero newHero = new Hero();
while (correctChoice == false)
{
switch (choice)
{
case "1":
CharacterCreation.createChar(newHero);
correctChoice = true;
break;
case "2":
Console.WriteLine("This feature is not yet implemented.");
correctChoice = false;
break;
case "3":
Environment.Exit(0);
break;
default:
Console.WriteLine("Please enter a correct value.");
break;
}
if (correctChoice == true)
break;
else
choice = Console.ReadLine();
}
Console.WriteLine("\n Your character is {0}, a {1}.", newHero.heroName, newHero.heroClass);
Console.ReadLine();
}
}
class CharacterCreation
{
public static void createChar(Hero newHero)
{
Console.WriteLine("\n We will proceed in character creation.");
Console.WriteLine("Please enter your character name:");
newHero.heroName = Console.ReadLine();
Console.WriteLine("\nNow choose your character's class: \n" +
"Warrior......1\n" +
"Mage........2\n" +
"Rogue........3");
string classChoice = Console.ReadLine();
bool correctChoice = false;
while (correctChoice == false)
{
switch (classChoice)
{
case "1":
newHero.heroClass = "Warrior";
correctChoice = true;
break;
case "2":
newHero.heroClass = "Mage";
correctChoice = true;
break;
case "3":
newHero.heroClass = "Rogue";
correctChoice = true;
break;
default:
Console.WriteLine("Please enter a correct value.");
break;
}
if (correctChoice == false)
classChoice = Console.ReadLine();
else break;
}
Hero.ClassSelect(newHero);
}
}
class Character
{
public int charHealth, charMaxHealth, charStr, charInt, charAgi;
}
class Hero : Character
{
public string heroName, heroClass;
public int level, experience, gold;
public static void ClassSelect(Hero newHero)
{
newHero.charAgi = 10;
newHero.charInt = 10;
newHero.charMaxHealth = 100;
newHero.experience = 0;
newHero.gold = 0;
newHero.level = 1;
switch (newHero.heroClass)
{
case "Warrior":
newHero.charMaxHealth = newHero.charMaxHealth * 115 / 100;
newHero.charStr = newHero.charStr * 12 / 100;
break;
case "Mage":
newHero.charInt = newHero.charInt * 12 / 100;
break;
case "Rogue":
newHero.charAgi = newHero.charAgi * 12 / 100;
break;
}
newHero.charHealth = newHero.charMaxHealth;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T22:01:54.567",
"Id": "32111",
"Score": "0",
"body": "What do you mean by \"optimal\"? There doesn't seem to be any performance-sesitive code in your game, so trying to make it faster doesn't make much sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T22:08:25.583",
"Id": "32112",
"Score": "0",
"body": "Wel I was wondering if there are probably better ways to write this code, or looking for some serious problems that I wouldn't be aware of."
}
] |
[
{
"body": "<p>Your code is \"incorrect\" in quite a few ways, from naming conventions, to separation of concerns (UI vs. object creation) to bedrock principles (such as principle of least privilege - <code>public</code> member variables being a big no-no). All that being said, I've taken a quick stab at addressing some of those I've listed above:</p>\n\n<pre><code>using System;\n\ninternal static class Program\n{\n private static void Main()\n {\n Console.ForegroundColor = ConsoleColor.White;\n Console.WriteLine(\"1. New Game\\n\" +\n \"2. Load Game\\n\" +\n \"3. Exit Game\\n\");\n var choice = Console.ReadLine();\n var correctChoice = false;\n Hero newHero = null;\n while (!correctChoice)\n {\n switch (choice)\n {\n case \"1\":\n newHero = CharacterCreation.CreateCharacter();\n correctChoice = true;\n break;\n case \"2\":\n Console.WriteLine(\"This feature is not yet implemented.\");\n break;\n case \"3\":\n return;\n default:\n Console.WriteLine(\"Please enter a correct value.\");\n break;\n }\n\n if (!correctChoice)\n {\n choice = Console.ReadLine();\n }\n }\n\n Console.WriteLine(\"\\n Your character is {0}, a {1}.\", newHero.HeroName, newHero.HeroClass);\n\n Console.ReadLine();\n }\n}\n\ninternal enum HeroClass\n{\n Unknown,\n\n Warrior,\n\n Mage,\n\n Rogue\n}\n\ninternal static class CharacterCreation\n{\n public static Hero CreateCharacter()\n {\n Console.WriteLine(\"\\n We will proceed in character creation.\");\n Console.WriteLine(\"Please enter your character name:\");\n\n var heroName = Console.ReadLine();\n\n Console.WriteLine(\"\\nNow choose your character's class: \\n\" +\n \"Warrior......1\\n\" +\n \"Mage........2\\n\" +\n \"Rogue........3\");\n\n var classChoice = Console.ReadLine();\n var correctChoice = false;\n var heroClass = HeroClass.Unknown;\n\n while (!correctChoice)\n {\n switch (classChoice)\n {\n case \"1\":\n heroClass = HeroClass.Warrior;\n correctChoice = true;\n break;\n case \"2\":\n heroClass = HeroClass.Mage;\n correctChoice = true;\n break;\n case \"3\":\n heroClass = HeroClass.Rogue;\n correctChoice = true;\n break;\n default:\n Console.WriteLine(\"Please enter a correct value.\");\n break;\n }\n\n if (!correctChoice)\n {\n classChoice = Console.ReadLine();\n }\n }\n\n return Hero.ClassSelect(heroName, heroClass);\n }\n}\n\ninternal class Character\n{\n private readonly int health;\n\n private readonly int maxHealth;\n\n private readonly int strength;\n\n private readonly int intelligence;\n\n private readonly int agility;\n\n protected Character(int health, int MaxHealth, int strength, int intelligence, int agility)\n {\n this.health = health;\n this.maxHealth = MaxHealth;\n this.strength = strength;\n this.intelligence = intelligence;\n this.agility = agility;\n }\n\n public int Health\n {\n get\n {\n return this.health;\n }\n }\n\n public int MaxHealth\n {\n get\n {\n return this.maxHealth;\n }\n }\n\n public int Strength\n {\n get\n {\n return this.strength;\n }\n }\n\n public int Intelligence\n {\n get\n {\n return this.intelligence;\n }\n }\n\n public int Agility\n {\n get\n {\n return this.agility;\n }\n }\n}\n\ninternal sealed class Hero : Character\n{\n private readonly string name;\n\n private readonly HeroClass @class;\n\n private readonly int level, experience, gold;\n\n public Hero(string name, HeroClass @class, int maxHealth, int strength, int intelligence, int agility)\n : base(maxHealth, maxHealth, strength, intelligence, agility)\n {\n this.name = name;\n this.@class = @class;\n this.experience = 0;\n this.gold = 0;\n this.level = 1;\n }\n\n public string HeroName\n {\n get\n {\n return this.name;\n }\n }\n\n public HeroClass HeroClass\n {\n get\n {\n return this.@class;\n }\n }\n\n public int Level\n {\n get\n {\n return this.level;\n }\n }\n\n public int Experience\n {\n get\n {\n return this.experience;\n }\n }\n\n public int Gold\n {\n get\n {\n return this.gold;\n }\n }\n\n public static Hero ClassSelect(string name, HeroClass @class)\n {\n var maxHealth = 100;\n var strength = 0; // this is not set anywhere in your original code.\n var intelligence = 10;\n var agility = 10;\n\n switch (@class)\n {\n case HeroClass.Warrior:\n maxHealth = maxHealth * 115 / 100;\n strength = strength * 12 / 100;\n break;\n case HeroClass.Mage:\n intelligence = intelligence * 12 / 100;\n break;\n case HeroClass.Rogue:\n agility = agility * 12 / 100;\n break;\n }\n\n return new Hero(name, @class, maxHealth, strength, intelligence, agility);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T11:24:25.883",
"Id": "32140",
"Score": "0",
"body": "Thanks for this reply as well, I'll see how I can incorporate those elements in my code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T18:14:50.753",
"Id": "32379",
"Score": "0",
"body": "Just echoing my comment on the other answer, because it applies here too (even moreso) - I find it much simpler and easier to read to have automatic properties with private setters than private fields exposed by public get-only properties."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T18:20:18.227",
"Id": "32380",
"Score": "0",
"body": "@Bobson I would certainly agree, except in the case where the values are intended to be frozen after initialization (`readonly` for the backing fields). Automatic properties don't give that option to signify the intent. It's a bit lamentable that it's not the case given today's push for parallel processing and the associated desire for immutable objects where applicable."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T22:15:44.900",
"Id": "20105",
"ParentId": "20102",
"Score": "3"
}
},
{
"body": "<p>I haven't done much work in C#, but from a general coding perspective...</p>\n\n<pre><code>class Main\n{\n static void Main(string[] args)\n {\n // lotsa stuff....\n }\n}\n</code></pre>\n\n<p>These (the class and method both) really ought to be <code>public</code>, as I believe that most application runners/executables will be looking for public methods. Additionally, a <code>Main()</code> method should be mostly empty, containing just enough code to launch the rest of the application (whether this submits an additional process or not).</p>\n\n<pre><code> Console.WriteLine() // Many times\n</code></pre>\n\n<p>Ideally, never call out to the console specifically. What you should be doing is <em>injecting</em> some sort of output/input stream. It's fine if these actually come from the console, but explicitly tying it to the console itself is frowned upon.</p>\n\n<pre><code>Console.WriteLine(\"1. New Game\\n\" +\n \"2. Load Game\\n\" +\n \"3. Exit Game\\n\");\n</code></pre>\n\n<p>So... you're using <code>WriteLine()</code> to write multiple lines at a time? Seems a little counter-intuitive. I'm slightly torn between recommending using individual calls (and potentially having output re-ordered because of some threading issue), or just using <code>Write()</code>...</p>\n\n<pre><code>while (correctChoice == false)\n{\n // stuff\n}\n</code></pre>\n\n<p>Using booleans like this is frowned upon; don't compare the boolean with a value, use the boolean itself (that's what it's for) - so, it should be <code>while (!correctChoice) { ... }</code>. Additionally, the name is somewhat ambiguous: possibly <code>availableOptionChosen</code>?</p>\n\n<pre><code>switch (choice)\n{\n // lotsa stuff\n}\n</code></pre>\n\n<p>Look into something called the <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow\">Strategy Pattern</a>. While the use of a switch works out for simple things, software patterns are something to always keep in mind.</p>\n\n<pre><code>case \"2\":\n Console.WriteLine(\"This feature is not yet implemented.\");\n correctChoice = false;\n break;\n</code></pre>\n\n<p>Strictly speaking, <code>correctChoice = false;</code> shouldn't be necessary.</p>\n\n<pre><code>case \"3\":\n Environment.Exit(0);\n break;\n</code></pre>\n\n<p>Using <code>Environment.Exic(0);</code> should end the running thread. However (if this is anything like Java's <code>System.Exit()</code>) this may have unintended consequences. It would be much better to simply <code>return</code> to the next level.</p>\n\n<pre><code>default:\n Console.WriteLine(\"Please enter a correct value.\");\n break;\n</code></pre>\n\n<p>You check the 'remaining' cases. Good; generally speaking, you should <em>always</em> do so, even if it's impossible (some of those should maybe only be 'asserts', used for verification-time checks).</p>\n\n<pre><code> Console.ReadLine();\n }\n}\n</code></pre>\n\n<p>You read a line immediately before the program exits. Why?</p>\n\n<pre><code>class CharacterCreation\n{\n\n // Lotsa stuff\n}\n</code></pre>\n\n<p>This is semantically a <a href=\"http://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow\">Builder-pattern</a>, so the class name is a little odd - perhaps <code>CharacterCreator</code>?</p>\n\n<pre><code>public static void createChar(Hero newHero) \n{\n // Stuff\n}\n</code></pre>\n\n<p>Why the abbreviation of 'Character' (and why all the abbreviations, generally)? Also, if it's named 'create...', you shouldn't be passing it in - it should be the return type (alternatively, call it <code>setupCharacter()</code>, and pass in the <code>Hero</code>). Additionally, <code>newHero</code> is an awkward name here - just use <code>hero</code> (you don't have an `oldHero you're using, do you?).</p>\n\n<pre><code>while (correctChoice == false)\n{\n switch (classChoice)\n {\n</code></pre>\n\n<p>The stuff I mentioned about your main loop applies here as well. This is especially prevalent with the class, if you're eventually going for something like DnD (which can have hundreds of classes).</p>\n\n<pre><code>class Character\n{\n public int charHealth, charMaxHealth, charStr, charInt, charAgi;\n}\n</code></pre>\n\n<p>Always put member definitions on their own lines. Always make them private, and provide equivalent <a href=\"http://msdn.microsoft.com/en-us/library/x9fsa0sw%28v=vs.80%29.aspx\" rel=\"nofollow\">public properties</a>. Don't abbreviate unnecessarily, seek to be understandable. Don't prefix variable names with their enclosing class' name (especially abbreviated) - it's noise.</p>\n\n<pre><code>class Hero : Character\n{\n // Acceptable\n}\n</code></pre>\n\n<p>This works, although it may become awkward in the future.</p>\n\n<pre><code>public static void ClassSelect(Hero newHero)\n{\n newHero.charAgi = 10;\n newHero.charInt = 10;\n newHero.charMaxHealth = 100;\n newHero.experience = 0;\n newHero.gold = 0;\n newHero.level = 1;\n\n switch (newHero.heroClass)\n {\n case \"Warrior\":\n newHero.charMaxHealth = newHero.charMaxHealth * 115 / 100;\n newHero.charStr = newHero.charStr * 12 / 100;\n break;\n case \"Mage\":\n newHero.charInt = newHero.charInt * 12 / 100;\n break;\n case \"Rogue\":\n newHero.charAgi = newHero.charAgi * 12 / 100;\n break;\n }\n newHero.charHealth = newHero.charMaxHealth;\n}\n</code></pre>\n\n<p>This, though, belongs in <code>CharacterCreation</code> (that's what it's there for). Additionally, instead of</p>\n\n<pre><code>newHero.charXxx = newHero.charXxx * 12 / 100;\n</code></pre>\n\n<p>you should probably just be setting it to the desired value. Especially because that's probably a bug, since a warrior will start out with a higher Int (10) than a mage</p>\n\n<pre><code>((10 * 12) / 100) = 120 / 100 = 1.2 -> 1\n</code></pre>\n\n<p>which I doubt is what you want.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T11:23:49.347",
"Id": "32139",
"Score": "0",
"body": "Thanks for this reply, very clear and complete, I'll try to fix the code and keep all those things in mind when I'm working on this project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T12:48:18.387",
"Id": "32304",
"Score": "0",
"body": "“the `break;` shouldn't be necessary” In C#, you can't have fall-through `case`s, so the `break` is actually necessary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T16:37:04.973",
"Id": "32367",
"Score": "0",
"body": "@svick - I think something might have been copied wrong (or something), especially given the next sentence. Especially since the `break` is necessary for program flow anyways, much less C#'s syntax requirements. Also, I dislike fall-through anyways..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T18:12:56.967",
"Id": "32378",
"Score": "1",
"body": "Re: `Always put member definitions on their own lines. Always make them private, and provide equivalent public properties.` - I find it much simpler to not use members at all, and simply have automatic properties with private setters. `public int Health { get; private set; }`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T23:02:12.727",
"Id": "20108",
"ParentId": "20102",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "20108",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T21:13:36.207",
"Id": "20102",
"Score": "3",
"Tags": [
"c#",
"beginner",
"console",
"role-playing-game"
],
"Title": "RPG character creation implementation"
}
|
20102
|
<p>I had this programming exercise of mine where I had to find the shortest path to an exit in an NxM -grid maze in under a second (both N and M would be anywhere between 3 and 1000). The program would be tested with 10 different inputs (mazes), all of which includes a very different amount of exits.</p>
<p>The input goes as follows:</p>
<pre><code>7 10
##########
#.....#... <- exit
#.#.###.##
#..X..#..#
#.#.#.#.##
#......... <- exit
###.######
^exit
</code></pre>
<p>Where the first number is height and the second width. The rest is the maze itself, and X marks the (starting) spot.</p>
<p>Well, I solved the problem using the A* algorithm and at the same time keeping track of the nearest exit (simple Manhattan distance). Now what's bugging me is that my fellow programmers have come to a lot faster and more memory-friendly solutions than I. My request is that you guys point out anything that comes to your mind, were it to be a completely different algorithm or just a stupid memory leak.</p>
<p>Here's the code:</p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm>
typedef std::vector<int> monovector;
typedef std::vector< std::vector<int> > bivector;
int _abs(int num);
int* get_nearest_goal(int y, int x, bivector &goals_t);
int goals = 0;
void appendClosedList(int y, int x, bivector &openList, bivector &closedList) {
for(size_t i = 0; i < openList.size(); i++)
if(openList[i][0] == y && openList[i][1] == x) closedList.push_back(openList[i]);
}
void dropOpenList(int y, int x, bivector &openList) {
for(size_t i = 0; i < openList.size(); i++)
if(openList[i][0] == y && openList[i][1] == x) openList.erase(openList.begin()+i);
}
int* get_coords(bivector &openList)
{
int* coords = new int[2];
int min_element = 1000000;
for(size_t i = 0; i < openList.size(); i++) {
if(openList[i][2] < min_element) {
min_element = openList[i][2];
coords[0] = openList[i][0];
coords[1] = openList[i][1];
}
}
return coords;
}
struct laby_t {
int h, w, s_y, s_x;
char **m_layout;
int ***m_attr, ***_m_attr;
int ***m_parent, ***_m_parent;
laby_t() {
std::cin >> h >> w;
m_layout = new char *[h+1];
for (int i = 0; i < h+1; i++)
m_layout[i] = new char[w+1];
m_parent = new int **[h];
m_attr = new int **[h];
for (int i = 0; i < h; i++) {
m_attr[i] = new int *[w];
m_parent[i] = new int *[w];
std::cin >> m_layout[i];
for (int j = 0; j < w; j++) {
m_attr[i][j] = new int[4];
m_parent[i][j] = new int[2];
m_attr[i][j][0] = 0;
m_attr[i][j][1] = 0;
m_parent[i][j][0] = 0;
m_parent[i][j][1] = 0;
if(m_layout[i][j] == '#') m_attr[i][j][0] = 2;
if(m_layout[i][j] == 'X') { s_y = i; s_x = j; }
}
}
}
int get_visited (int y, int x) { return this->m_attr[y][x][0]; }
int get_depth(int y, int x) {
if(this->m_attr[y][x][1]) return this->m_attr[y][x][1];
else return 0;
}
int get_estimate(int y, int x) { return this->m_attr[y][x][2]; }
int get_priority(int y, int x) { return this->m_attr[y][x][3]; }
void set_visited(int py, int px, int y, int x, int f_y, int f_x, int depth) {
this->m_attr[y][x][0] = 1;
this->m_attr[y][x][1] = depth;
this->m_attr[y][x][2] = _abs(f_y - y) + _abs(f_x - x);
this->m_attr[y][x][3] = this->m_attr[y][x][1] + this->m_attr[y][x][2];
this->m_parent[y][x][0] = py;
this->m_parent[y][x][1] = px;
}
void reset()
{
delete this->m_attr;
delete this->m_parent;
delete this->m_layout;
}
};
void dropGoals(int f_y, int f_x, bivector &goals_t, laby_t &laby)
{
for(size_t i = 0; i < goals_t.size(); i++)
if(goals_t[i][0] == f_y && goals_t[i][1] == f_x) {
goals_t.erase(goals_t.begin()+i);
laby.m_layout[goals_t[i][0]][goals_t[i][i]] = '#';
laby.m_attr[goals_t[i][0]][goals_t[i][i]][0] = 2;
}
}
int wander(int y, int x, int f_y, int f_x, laby_t &laby, bivector goals_t)
{
int depth = 1;
laby.set_visited(y, x, y, x, f_y, f_x, depth);
monovector r; r.push_back(y); r.push_back(x); r.push_back(laby.get_priority(y, x)); r.push_back(0);
bivector openList, closedList;
openList.push_back(r);
r.clear();
int dir[4][2] = {
{ 1, 0},
{-1, 0},
{ 0, 1},
{ 0,-1}
};
while(!(y == f_y && x == f_x))
{
for(int i = 0; i < 4; i++)
{
int _y = y + dir[i][0];
int _x = x + dir[i][1];
if(y > 0 && y < laby.h-1 && x > 0 && x < laby.w-1) {
if(
(
(laby.get_visited(_y, _x) == 0) ||
(laby.get_visited(_y, _x) == 1 && laby.get_depth(y, x)+1 < laby.get_depth(_y, _x))
)
)
{
laby.set_visited(y, x, _y, _x, f_y, f_x, laby.get_depth(y, x)+1);
monovector r; r.push_back(_y); r.push_back(_x); r.push_back(laby.get_priority(_y, _x));
openList.push_back(r);
r.clear();
if((_y == 0 || _y == laby.h-1 || _x == 0 || _x == laby.w-1) && (_y != f_y || _x != f_x)) {
int d = laby.get_depth(_y, _x);
openList.clear();
closedList.clear();
laby.reset();
return d;
}
}
}
else { return laby.get_depth(y, x); };
}
appendClosedList(y, x, openList, closedList);
dropOpenList(y, x, openList);
int *yx = get_coords(openList);
y = yx[0];
x = yx[1];
yx = get_nearest_goal(y, x, goals_t);
f_y = yx[0];
f_x = yx[1];
delete yx;
}
int d = laby.get_depth(y, x);
openList.clear();
closedList.clear();
laby.reset();
return d;
}
int _abs(int num)
{
if(num <= 0) return -num;
else return num;
}
int* get_nearest_goal(int y, int x, bivector &goals_t)
{
int min_dist = 1000000;
int *f_coords = new int[2];
for(size_t i = 1; i < goals_t.size(); i++) {
if(_abs(y - goals_t[i][0]) + _abs(x - goals_t[i][1]) < min_dist) {
min_dist = _abs(y - goals_t[i][0]) + _abs(x - goals_t[i][1]);
f_coords[0] = goals_t[i][0];
f_coords[1] = goals_t[i][1];
}
}
return f_coords;
}
int* get_goals(int &goals, bivector &goals_t, laby_t &laby)
{
for(int i = 1; i < laby.h - 1; i++) {
if(laby.m_layout[i][0] == '.') {
goals++;
monovector t; t.push_back(i); t.push_back(0); goals_t.push_back(t);
t.clear();
}
if(laby.m_layout[i][laby.w - 1] == '.') {
goals++;
monovector t; t.push_back(i); t.push_back(laby.w - 1); goals_t.push_back(t);
t.clear();
}
}
for(int i = 1; i < laby.w - 1; i++) {
if(laby.m_layout[0][i] == '.') {
goals++;
monovector t; t.push_back(0); t.push_back(i); goals_t.push_back(t);
t.clear();
}
if(laby.m_layout[laby.h - 1][i] == '.') {
goals++;
monovector t; t.push_back(laby.h - 1); t.push_back(i); goals_t.push_back(t);
t.clear();
}
}
return get_nearest_goal(laby.s_y, laby.s_x, goals_t);
}
int main()
{
int *f_coords = new int[2];
bivector goals_t;
laby_t laby;
f_coords = get_goals(goals, goals_t, laby);
int min_path = wander(laby.s_y, laby.s_x, f_coords[0], f_coords[1], laby, goals_t);
delete f_coords;
std::cout << min_path << std::endl;
//system("pause");
return 0;
}
</code></pre>
<p>I was too lazy to add comments, so tell me if they are needed.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T00:54:38.110",
"Id": "32121",
"Score": "0",
"body": "This: `int *f_coords = new int[2];` just screams \"I have no idea how to use C++\". This is not Java don't use the language as if it was. Unless there is a good reason to use new you probably should not. Even if you use new you should never use `delete` as pointers life spans should be controlled by objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T01:00:23.140",
"Id": "32122",
"Score": "0",
"body": "Clue 1: The variable `m_attr` should be declared as: `std::vector<std::vector<std::vector<int>>> m_attr(std::vector<std::vector<int>>(std::vector<int>(0, 4), w), h);` Done. All memory management correctly handled (unlike your code)."
}
] |
[
{
"body": "<p>Reviewing all of this is a fairly big task, so let me start with a few ideas and come back later if I have the time.</p>\n\n<h2>Algorithmic considerations</h2>\n\n<p>As Sylvain pointed out in his answer to <a href=\"https://stackoverflow.com/questions/14129584/a-shortest-path-algorithm-optimization-request\">your question on Stackoverflow</a>, your heuristic is too simple and will underestimate the distance repeatedly and by substantial amounts. This will affect the running time of your algorithm to the point where something like a Dijkstra search may easily be better. For educational purposes, I think it would be best if you took Sylvain's other suggestion of implementing a reverse search from the exits to your startin location.</p>\n\n<h2>Style</h2>\n\n<ul>\n<li>Don't be a <a href=\"http://c2.com/cgi/wiki?ThreeStarProgrammer\" rel=\"nofollow noreferrer\">three star programmer</a>. In this case in particular, hiding the additional information contained in your nodes in <code>m[][][0]</code> to <code>m[][][4]</code> makes it extremely difficult to read for anyone who hasn't spent hours writing it (i.e. you). Use a structured way of implementing your nodes like a <code>class</code> or a <code>struct</code>.</li>\n<li>Use standard names. 'monovector' and 'bivector' make sense only in your brain. Your 'monovector' is a 2D coordinate vector (it is NOT a good idea to make it an <code>std::vector</code>, more on that later!) - why not call it <code>vector2d</code> or <code>coordinate</code>? Your 'bivector' is a list of coordinates.</li>\n</ul>\n\n<h2>Choice of data structures</h2>\n\n<p>Everything is a <code>vector</code> in your implementation. That's far from ideal</p>\n\n<ul>\n<li>A 2D coordinate vector always has exactly two elements. A C++ <code>std::vector</code> is designed to have a variable and arbitrary number of elements and is therefore not a good fit (I do agree that the name is confusing for someone coming to coding from a mathematical point of view).</li>\n<li>In the A* algorithm, you repeatedly need to take the cheapest (in terms of estimated remaining distance) element from the open list. It may be sensible to choose a data structure which is kept sorted automatically.</li>\n</ul>\n\n<h2>Implementation issues</h2>\n\n<ul>\n<li>If you were consistently working with a proper datatype for your nodes, you could easily get rid of the inefficient implementations of <code>appendClosedList</code> and <code>dropOpenList</code>. Both of those currently scan the entire lists, and all that while your program <em>knows</em> which node they have to remove/add - it's working on them at the very moment you call those functions!</li>\n</ul>\n\n<h2>Memory management</h2>\n\n<p>As Loki Astari mentioned in the comments, most of these issues will automagically disappear with correct use of containers and <a href=\"https://stackoverflow.com/questions/2635882/raii-tutorial-for-c\">other relevant techniques</a>. It may still be worthwhile to know how to do things correctly 'your way', even if it isn't advisable to actually write code like that.</p>\n\n<p>Now, it is not really a case of finding \"just a stupid memory leak\" in your code, practically everything in there leaks or does error-prone things.\nJust consider, as an example,</p>\n\n<pre><code> int *yx = get_coords(openList);\n y = yx[0];\n x = yx[1];\n\n yx = get_nearest_goal(y, x, goals_t);\n f_y = yx[0];\n f_x = yx[1];\n\n delete yx;\n</code></pre>\n\n<p>First of all, allocation is handled by the callee and deallocation by the caller, which is (imho) intransparent and error-prone. Then, you're reusing <code>yx</code>, the memory allocated in <code>get_coords</code> always leaks. Additionally, you allocate memory in <code>get_nearest_goal</code> with <code>new[]</code>, then deallocate it with <code>delete</code>.\nFurthermore, your <code>reset()</code> function is <a href=\"https://stackoverflow.com/questions/7601375/delete-multidimensional-arrays\">completely broken</a>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T16:55:30.463",
"Id": "20128",
"ParentId": "20104",
"Score": "1"
}
},
{
"body": "<p>I remember two optimization from my own implementation of the A* algorithm.</p>\n\n<ul>\n<li><p>Use only one list and give an Closed/Opened flag to your item. Then instead of removing/adding items from one list to another, simply toggle the flag.</p></li>\n<li><p>Use a map / multimap instead of vector. Sort them with a custom comparator. Then instead of doing linear searches in vectors, the map will quickly find what you need it its sorted tree.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T23:32:44.420",
"Id": "32398",
"Score": "0",
"body": "But if you just toggle flags, you either have to scan the entire list in each step or insert the nodes obtained from the extension at a middle point in the list, no? I don't quite see how this is more efficient."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T22:38:51.260",
"Id": "20251",
"ParentId": "20104",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T21:48:57.413",
"Id": "20104",
"Score": "2",
"Tags": [
"c++",
"performance",
"memory-management",
"taxicab-geometry"
],
"Title": "A* shortest path algorithm optimization"
}
|
20104
|
<p>This program displays either the time, current temperature, 12hr graph of temps, 24 hr graph of temp or a week's graph of temps. Selection is based on user input of one of the GPIO pins.</p>
<p>Please review my code, especially the use of the global variables, indentation and comments.</p>
<pre><code>from subprocess import *
import matplotlib
from numpy import genfromtxt
matplotlib.use('Agg')
import pylab
import Image
import pygame
import os
import time
from time import strftime
#from pygame.locals import*
#from matplotlib.dates import DateFormatter
import RPi.GPIO as GPIO
import datetime
def run_cmd(cmd):
"""Used to run Linux commands"""
p = Popen(cmd, shell=True, stdout=PIPE)
output = p.communicate()[0]
return output
def ckyorn( prompt, help="" ):
"""Used for Y/N prompt"""
a= ""
ok= False
while not ok:
a=raw_input( prompt + " [y,n,?]: " )
if a.upper() in [ 'Y', 'N', 'YES', 'NO' ]:
ok= True
return a.upper()[0]
def delete_old_data():
""" Used to delete old data in input file. Will check for data older than 14 days
and ask if you would like everything older than 7 days to be deleted. This should not being asked more than once a week"""
now = datetime.datetime.now()
#get the first line of the data file, which will be the oldest entry
getfirstLine = run_cmd("head -1 temperature_logging | awk '{print $2}'")
#convert string to time.
firstLineTime = datetime.datetime.strptime(getfirstLine, '%m-%d-%Y-%H:%M:%S ')
#Get the date and time for seven days ago from now.
sevenDays = now - datetime.timedelta(days=7)
removeFrom = sevenDays.strftime('%m-%d-%Y-%T')
#If the data and time in the first line is older than 14 days, ask if okay to delete.
if (now - firstLineTime) > datetime.timedelta(days=14):
print ("More than 14 days worth of data has been collected.")
var = ckyorn ("Would you like to delete data older than 7 days?")
if var == 'Y' :
sedCommand = "sed -n -i '/" + removeFrom[1:15] + "/,$p' temperature_logging"
run_cmd(sedCommand)
def displayText(text, size, line, color, clearScreen):
"""Used to display text to the screen. displayText is only configured to display
two lines on the TFT. Only clear screen when writing the first line"""
if clearScreen == True:
screen.fill((0, 0, 0))
font = pygame.font.Font(None, size)
text = font.render(text, 0, color)
textRotated = pygame.transform.rotate(text, -90)
textpos = textRotated.get_rect()
textpos.centery = 80
if line == 1:
textpos.centerx = 90
screen.blit(textRotated,textpos)
elif line == 2:
textpos.centerx = 40
screen.blit(textRotated,textpos)
def displayTime():
"""Used to display date and time on the TFT"""
screen.fill((0, 0, 0))
currentTimeLine1 = strftime("%H:%M:%S", time.localtime())
currentTimeLine2 = strftime("%d %b", time.localtime())
font = pygame.font.Font(None, 50)
text1 = font.render(currentTimeLine1, 0, (0,250,150))
text2 = font.render(currentTimeLine2, 0, (0,250,150))
Surf1 = pygame.transform.rotate(text1, -90)
Surf2 = pygame.transform.rotate(text2, -90)
screen.blit(Surf1,(60,20))
screen.blit(Surf2,(10,20))
def graph(toKeep):
"""Used to display the graphs. Text will be shown before hand as
the graphs take time to generate"""
global firstTime
#Display some text stating that graphs are being generated
if toKeep == TwelveHours:
displayText('Creating', 35, 1,(200,200,1),True)
displayText('12 Hour Graph', 32, 2,(150,150,255), False)
elif toKeep == TwentyFourHours:
displayText('Creating', 35, 1,(200,200,1), True)
displayText('24 Hour Graph', 32, 2,(150,150,255), False)
elif toKeep == OneWeek:
displayText('Creating', 35, 1,(200,200,1), True)
displayText('One Week Graph', 28, 2,(150,150,255), False)
pygame.display.flip()
#Get temperature and time data from data file
temp = genfromtxt('temperature_logging', dtype=None, usecols=(0), skip_header = lines - toKeep)
timecaptured = genfromtxt('temperature_logging', dtype=None, usecols=(1), skip_header = lines - toKeep)
#Site the size of the font for the axis
for label in ax.get_xticklabels():
label.set_fontsize(8)
for label in ax.get_yticklabels():
label.set_fontsize(8)
#Create xaxis labels and only show every 12th or 96th
xlabels = range(toKeep)
if toKeep == OneWeek:
pylab.xticks(xlabels[::96], [v[:5:] for v in timecaptured[::96]])
else:
pylab.xticks(xlabels[::12], [v[11:16] for v in timecaptured[::12]])
#Plot the graph
pylab.plot(temp,linewidth=2, antialiased=True)
#Change some colours
ax.patch.set_facecolor('#FFFFCC')
ax.patch.set_alpha(0.5)
#Rotate the text in the xaxis
fig.autofmt_xdate(rotation=90)
#Set the yaxsis limits
pylab.ylim(0,40)
#Save the graph as an image and the re-open it, rotate it and then display to TFT.
pylab.savefig('gp.png', facecolor=fig.get_facecolor(),bbox_inches='tight', dpi=80,pad_inches=0.03)
pil_im = Image.open('gp.png')
pil_out = pil_im.rotate(-90)
pil_out.save("gp.png")
img = pygame.image.load('gp.png')
screen.blit(img,(0,0))
pygame.display.flip()
#Clear graph data in preparation for next plot
pylab.cla()
#Reset the firstTime Variable
firstTime = 0
def main():
global ax,fig,screen
global firstTime,lines
global TwentyFourHours,TwelveHours,OneWeek
size = width, height = 128, 160
TFTxSize = 2.28
TFTySize = 1.63
firstTime = True #Used to work out if a function has already been run
TwentyFourHours = 288
TwelveHours = 144
OneWeek = 2016
whatToDisplay = 1 #What do display on screen
rotate = 2 #Used when automatically rotating the display.
startTime = time.time() #Used to work out how much time has passed when rotating.
#Set the framebuffer device to be the TFT
os.environ["SDL_FBDEV"] = "/dev/fb1"
#Setup pygame display
pygame.init()
pygame.mouse.set_visible(0)
screen = pygame.display.set_mode(size)
#Setup plot area
fig = pylab.figure()
ax = fig.add_subplot(111)
fig.set_size_inches(TFTxSize, TFTySize)
background = pygame.Surface(screen.get_size())
background = background.convert()
#Setup GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN) #Read GPIO 17 as input
#Open data file and count how many lines
file = open('temperature_logging')
lines = sum(1 for word in file if "." in word)
file.seek(0,0)
delete_old_data()
while True:
time.sleep(.5)
"""Check to see if button is pressed, and if so, increment by one
or reset to one if over 6"""
if GPIO.input(17):
if whatToDisplay < 7:
whatToDisplay = whatToDisplay + 1
firstTime = True
else:
whatToDisplay = 1
firstTime = True
import pdb; pdb.set_trace()
if whatToDisplay == 1: #Display time
displayTime()
elif whatToDisplay == 2: #Display last temperature recorded.
file.seek(-26,2) #Go to end of data file to get temperature
currentTemp = file.readline(5) + ' \xb0C'
displayText('Current Temp', 30, 1, (200,200,1), True )
displayText(currentTemp, 50, 2, (150,150,255), False )
elif whatToDisplay == 4 and firstTime == True:
graph(TwelveHours)
elif whatToDisplay == 5 and firstTime == True:
graph(TwentyFourHours)
elif whatToDisplay == 6 and firstTime == True:
graph(OneWeek)
elif whatToDisplay == 3: #Rotate display
elapsedTime = time.time() - startTime
if elapsedTime > 5:
if rotate == 1:
rotate = 2
startTime = time.time()
else:
rotate = 1
startTime = time.time()
if rotate == 1:
displayTime()
elif rotate == 2:
file.seek(-26,2)
currentTemp = file.readline(5) + ' \xb0C'
displayText('Current Temp', 30, 1, (200,200,1), True )
displayText(currentTemp, 50, 2, (150,150,255), False )
#Write to TFT
pygame.display.flip()
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T12:38:25.133",
"Id": "32251",
"Score": "0",
"body": "I see that you have accepted my answer. Don't you want to put a new version of your code here so that one can have a deeper look ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T16:55:57.030",
"Id": "33109",
"Score": "0",
"body": "I'd love to see the new and improved version too :)"
}
] |
[
{
"body": "<p>Too much to put as a comment, so this is going to be an answer :</p>\n\n<p>As a general comment, you use many variables which are used only once, so they might not really be useful.</p>\n\n<p><code>ckyorn</code> can be rewritten in a more concise way. Also, its name is weird and one of the parameters is not used.</p>\n\n<pre><code>def ckyorn( prompt):\n \"\"\"Used for Y/N prompt\"\"\"\n while True:\n a=raw_input( prompt + \" [y,n,?]: \" ).upper()\n if a in [ 'Y', 'N', 'YES', 'NO' ]: \n return a[0]\n</code></pre>\n\n<p>I think it would make sense if this function was to return a boolean instead of a string.</p>\n\n<pre><code> if a in [ 'Y', 'YES']: \n return True\n if a in [ 'N', 'No']: \n return False\n</code></pre>\n\n<p>And then, the calling code becomes clearer :</p>\n\n<pre><code>if ckyorn (\"Would you like to delete data older than 7 days?\"):\n</code></pre>\n\n<p>You can write <code>if clearScreen:</code> instead of <code>if clearScreen == True:</code>. This applies to different parts of your code.</p>\n\n<p>Make sure you always extract common code from then and else blocks. For instance,</p>\n\n<pre><code> if whatToDisplay < 7:\n whatToDisplay = whatToDisplay + 1\n firstTime = True\n else:\n whatToDisplay = 1\n firstTime = True\n</code></pre>\n\n<p>is exactly the same as :</p>\n\n<pre><code> if whatToDisplay < 7:\n whatToDisplay = whatToDisplay + 1\n else:\n whatToDisplay = 1\n firstTime = True\n</code></pre>\n\n<p>Please note that what you are doing on <code>whatToDisplay</code> could be done with the modular operator:</p>\n\n<pre><code> whatToDisplay = 1+(whatToDisplay%7)\n</code></pre>\n\n<p>Data structures can be used to extract common code. For instance <code>displayTime</code> could be :</p>\n\n<pre><code>def displayTime():\n \"\"\"Used to display date and time on the TFT\"\"\"\n screen.fill((0, 0, 0))\n font = pygame.font.Font(None, 50)\n now=time.localtime()\n for setting in [(\"%H:%M:%S\",60),(\"%d %b\",10)] :\n timeformat,dim=setting\n currentTimeLine = strftime(timeformat, now)\n text = font.render(currentTimeLine, 0, (0,250,150))\n Surf = pygame.transform.rotate(text, -90)\n screen.blit(Surf,(dim,20))\n</code></pre>\n\n<p>I haven't looked at it much so far but the global variables seem dodgy to me.</p>\n\n<p>My intuition is that rotation should actually be a boolean as it takes only 2 different values. Then, </p>\n\n<pre><code> if elapsedTime > 5:\n if rotate == 1:\n rotate = 2\n startTime = time.time()\n else:\n rotate = 1\n startTime = time.time()\n if rotate == 1:\n displayTime()\n elif rotate == 2:\n file.seek(-26,2)\n</code></pre>\n\n<p>would become :</p>\n\n<pre><code> if elapsedTime > 5:\n rotate = not rotate\n startTime = time.time()\n if rotate:\n displayTime()\n elif not rotate:\n file.seek(-26,2)\n</code></pre>\n\n<p><strong>Edit</strong>\nAfter a second look at <code>delete_old_data</code> :</p>\n\n<ul>\n<li><p>The variables names are not really good. In particular :</p>\n\n<ul>\n<li><code>getfirstline</code> should be <code>firstline</code></li>\n<li><code>sevenDays</code> should be something like <code>sevenDaysAgo</code></li>\n<li><code>removeFrom</code> should be something like <code>sevenDaysAgoStr</code></li>\n</ul></li>\n<li><p>You probably don't need to call shell command as you could do the same things in pure Python.</p></li>\n<li>The name of the file (<code>temperature_logging</code>) should appear only once in the code (you store it in a variable). The same applies to <code>gp.png</code> later in the code.</li>\n<li><code>sevenDays</code> and <code>removeFrom</code> should be defined in the smallest possible scope. In your case, you don't need them until after <code>if var == 'Y'</code>.</li>\n<li>I don't know why you want to take the letters 1 from 15 in <code>removeFrom</code>. Can't you just make sure that <code>removeFrom</code> is formatted just the way you want using <code>strftime</code>?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T21:52:17.883",
"Id": "32174",
"Score": "0",
"body": "Thank you so much for spending time with looking at my code. Its muchly appreciated.\nAll your points are very much valid… and I have learned a great deal.\n\nI had no idea you can use the modulo operator to rotate a number like that…… a lot cleaner than what I was doing!\n\nAnd what you did to Def displayTime(): … again, I had no idea you could do this and it looks much more efficient. \n\nI’m going to go away and work on your other points.\nThank you very much!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T22:09:19.837",
"Id": "32176",
"Score": "0",
"body": "@Josay Your modular-operator-solution for `whatToDisplay` only does the same thing as the original code for values between 0 and (including) 7. For values > 7, it's totally different."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T23:07:27.287",
"Id": "32179",
"Score": "0",
"body": "Actually, the point is that it never takes a value > 7. By making sure that this variable is only changed by this single statement, I think it enforces this and makes it clearer (only one branch to consider instead of 2 in the if-else structure). However, I do agree that more generally speaking, the two pieces of code have different effects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T23:10:09.750",
"Id": "32180",
"Score": "0",
"body": "Also, this could be even clearer if we were to use values in [0,6] instead of values in [1,7] by re-indexing every thing. Then, we would just have : \"whatToDisplay = whatToDisplay%7\""
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T07:35:36.533",
"Id": "20116",
"ParentId": "20109",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "20116",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-02T23:33:37.267",
"Id": "20109",
"Score": "12",
"Tags": [
"python",
"beginner",
"matplotlib",
"raspberry-pi"
],
"Title": "Time and temperature displaying program for Raspberry Pi"
}
|
20109
|
<p>I am using <code>DataGrid</code> to show storagehouse occupancy (Occupied-Show Image With a box, Not Occupied-Show Empty Image).<br>
In DataGrid I am using <code>DataGridTemplateColumn</code> to override the Images.<br>
My Main Form XAML Code: </p>
<pre><code><xctk:BusyIndicator Name="ctrlBusy" IsBusy="False" BusyContent="Generating Maps..." >
<Grid>
<StackPanel>
<Button Name="btnClick" Grid.Row="0" Click="Button_Click_1" Height="44" VerticalAlignment="Top"
HorizontalAlignment="Left" Width="114" Panel.ZIndex="4" Margin="6,3,0,0">Click</Button>
<StackPanel Orientation="Vertical" Grid.Row="1">
<TextBlock Background="SkyBlue" Height="50">
</TextBlock>
<DataGrid GridLinesVisibility="None" Background="SkyBlue"
BorderBrush="Transparent" IsReadOnly="True" ItemsSource="{Binding}"
AutoGenerateColumns="True" AutoGeneratingColumn="dgvMap_AutoGeneratingColumn"
CanUserAddRows="False" CanUserSortColumns="true" CanUserDeleteRows="False"
HeadersVisibility="Row" Name="dgvMap" SelectionMode="Single"
Panel.ZIndex="0" Margin="0,0,0,0" VirtualizingStackPanel.VirtualizationMode="Standard">
<!--for removing the blue color bkground default for row selection-->
<DataGrid.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Transparent"/>
</DataGrid.Resources>
</DataGrid>
<TextBlock Background="SkyBlue" Height="50">
</TextBlock>
</StackPanel>
</StackPanel>
</Grid>
</xctk:BusyIndicator>
</code></pre>
<p>Datatemplate for DataGrid: </p>
<pre><code> <DataTemplate x:Key="MyDataTemplate" DataType="DataRowView">
<Grid Background="Transparent">
<Image Tag="{Binding}" Name="Layer0" Margin="0,0,0,0" Panel.ZIndex="1"
Width="50" Height="50" ToolTipService.HasDropShadow="True" ToolTipService.ShowDuration="20000" ToolTipService.InitialShowDelay="200" >
<Image.ToolTip>
<StackPanel>
<Label FontWeight="Bold" Background="Blue" Foreground="White" Content="{Binding}" />
<TextBlock Padding="10" TextWrapping="WrapWithOverflow" Width="200">
This coil is located in this location. Yard Name is FG. Zone is Dispatch Area.
</TextBlock>
<Line Stroke="Black" StrokeThickness="1" X2="200" />
<StackPanel Orientation="Horizontal">
<Label FontWeight="Bold">Report to admin in case of coil location mismatch</Label>
</StackPanel>
</StackPanel>
</Image.ToolTip>
<Image.Resources>
<Style TargetType="{x:Type Image}">
<Setter Property="Source" Value="{Binding Converter={StaticResource IntToImageConverter}, ConverterParameter = Layer0}" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<!-- Hover image -->
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Source" Value="C:\Users\Images\Coil3.png"/>
<!--<Setter Property="Source" Value="{Binding Converter={StaticResource HoverImage}}"/>-->
</Trigger>
</Style.Triggers>
</Style>
</Image.Resources>
</Image>
</Grid>
</DataTemplate>
</code></pre>
<p>Main Form Code-Behind: </p>
<pre><code> private void Button_Click_1(object sender, RoutedEventArgs e)
{
btnClick.Content = "Data Loaded";
Stopwatch sw = new Stopwatch();
DataTable dt = dbLayer.tblSaddleSelectAll();
sw.Start();
dgvMap.ItemsSource = dt.DefaultView;
sw.Stop();
btnClick.Content = sw.ElapsedMilliseconds.ToString();
}
private void dgvMap_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == "row")
{
e.Column.Visibility = System.Windows.Visibility.Hidden;
}
var column = new DataRowColumn(e.PropertyName);
column.Header = e.Column.Header;
column.CellTemplate = (DataTemplate)Resources["MyDataTemplate"];
e.Column = column;
}
</code></pre>
<p>ValueConverter for DataGrid: </p>
<pre><code>public class BoolToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
ImageSource result = null;
var intValue = value.ToString();
switch (parameter.ToString())
{
case "Layer1":
if (intValue.ToUpper().Contains("EMPTY"))
{
result = null;
}
else
{
result = new BitmapImage(new Uri(@"C:\Users\Images\Box3.png"));
}
return result;
default:
if (intValue.ToUpper().Contains("EMPTY"))
{
//result = null;
result = new BitmapImage(new Uri(@"C:\Users\Images\Box1.png"));
}
else
{
result = new BitmapImage(new Uri(@"C:\Users\Images\Box2.png"));
}
return result;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
</code></pre>
<p>Custom DatagridTemplateColumn: </p>
<pre><code> public class DataRowColumn : DataGridTemplateColumn
{
public DataRowColumn(string column) { ColumnName = column; }
public string ColumnName { get; private set; }
protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
{
var row = (DataRowView)dataItem;
var item = row[ColumnName];
cell.DataContext = item;
var element = base.GenerateElement(cell, item);
return element;
}
}
</code></pre>
<p>The Data from Database will be like this: </p>
<p><img src="https://i.stack.imgur.com/wwCsr.png" alt="example of data from database"></p>
<p>I will be loading maximum of 250 columns, 20 rows from database.<br>
My questions:</p>
<ol>
<li>Is <code>datagrid</code> is best way to show map kind of layouts for the data given range? I need to show presence and absence with some <code>tooltip</code> descriptions. </li>
<li>The stopwatch i kept for checking time taken to load DataGrid. It is showing value less than 250ms. But in reality it is taking too much take show and for 4-6 second the UI gets hanged. Why is hanging? How to overcome it? How can i show BusyIndicator till DataGrid is fully created? </li>
<li>Is attaching <code>DataTable</code>'s <code>DefaultView</code> to <code>DataGrid</code> is better way to do in performance in wise?? </li>
<li>Is there anything(properties) I missed in <code>DataGrid</code> to improve the performance. </li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-20T01:08:56.223",
"Id": "45130",
"Score": "1",
"body": "This will never work fine. We are facing a similar issue with a grid (~20 row and ~90 column) and everything is slow as hell becouse Silverlight/desktop WPF application can not handle this kind of situation. I have created an old Windows Forms application to solve our problem and everything becode fast."
}
] |
[
{
"body": "<blockquote>\n <p>The stopwatch i kept for checking time taken to load DataGrid. It is\n showing value less than 250ms. But in reality it is taking too much\n take show and for 4-6 second the UI gets hanged. Why is hanging? How\n to overcome it?</p>\n</blockquote>\n\n<p>That's beacuse the datagrid layout update is happening asynchronously. You can work around it by exploiting the dispatcher priority system:</p>\n\n<pre><code>Dispatcher.CurrentDispatcher.BeginInvoke(\n ((Action)(() =>\n {\n sw.Stop(); //We stop it here, after the datagrid has been rendered\n btnClick.Content = sw.ElapsedMilliseconds.ToString();\n })),\n DispatcherPriority.Loaded);\n</code></pre>\n\n<p>The Loaded priority is just below the Render priority, so that code will be executed after the datagrid has been rendered.</p>\n\n<blockquote>\n <p>How can i show BusyIndicator till DataGrid is fully created?</p>\n</blockquote>\n\n<p>Use a task to load the data table:</p>\n\n<pre><code>ctrlBusy.IsBusy = true;\nvar task = Task.Factory.StartNew<DataTable>(() => dbLayer.tblSaddleSelectAll());\ntask.ContinueWith(\n t => dgvMap.ItemsSource = t.Result.DefaultView, \n CancellationToken.None, \n Tasks.TaskContinuationOptions.OnlyOnRanToCompletion, \n TaskScheduler.FromCurrentSynchronizationContext());\n\ntask.ContinueWith(\n t => ctrlBusy.IsBusy = false, \n CancellationToken.None, \n Tasks.TaskContinuationOptions.None, \n TaskScheduler.FromCurrentSynchronizationContext());\n</code></pre>\n\n<p>I'm sorry i can't help with the other questions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T17:08:42.443",
"Id": "22894",
"ParentId": "20111",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-01-03T05:29:37.730",
"Id": "20111",
"Score": "2",
"Tags": [
"c#",
"wpf",
".net-datatable"
],
"Title": "Performance of WPF datagrid when using DataGridTemplateColumn"
}
|
20111
|
<p>I have a wrapper which interacts with a third party component. In Each function i am performing the operation if it the component is initialized. </p>
<p>I have other function to check the errorCode and component initialization check. </p>
<p>Is this right way to do this? I am not happy with the readability of this code. Help me improving this code. </p>
<p>Thanks in advance.</p>
<pre><code>Void Operation1 (parameter someInput)
{
int errorCode= 0;
if (Initialized)
{
errorCode = ThirdPartyComponent.Operation1(someInput);
}
CheckErrorCodeAndShowError ("Operation1 with someInput failed", returnValue);
}
Void Operation2 (parameter someInput)
{
int errorCode= 0;
if (Initialized)
{
errorCode = ThirdPartyComponent.Operation2(someInput);
}
CheckErrorCodeAndShowError ("Operation2 with someInput failed", returnValue);
}
Void CheckErrorCodeAndShowError (String errorMessage, int errorCode)
{
if (!Initialized)
{
//Show not initialized error
}
if (errorCode == -1)
{
//Show Operation failed error (errorMessage)
}
else if (errorCode == 0)
{
//Show operation success message etc
}
//other error code check
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T07:17:12.590",
"Id": "32132",
"Score": "0",
"body": "Does the third party have some sort of mapping of error codes to strings? Most of the third party libraries I have used have had something like that. Either a function I could call with the error code that would return a string or a file that contained a definition of the values with some comments of what they mean."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T07:30:13.513",
"Id": "32133",
"Score": "0",
"body": "No, it does not have any mapping."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T07:44:15.300",
"Id": "32134",
"Score": "0",
"body": "Does it always return `-1` when there is an error? Does it not have any way to get some extended information. Like a Windows \"GetLastError\" type of call?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T08:21:21.060",
"Id": "32135",
"Score": "0",
"body": "It has many error codes. For simplicity i showed only -1. But no other extended information is available from that component."
}
] |
[
{
"body": "<p>Okay, well here is what I would probably do in this situation. If the error codes you are getting are consistent this will make this type of solution even better (consistent as in \"FileNotFound\" error code is always -42 or something like that).</p>\n\n<p>I would add a private method that throws an \"Uninitialized\" exception if the object has not been initialized. There is no need to be checking that twice for each function call.</p>\n\n<pre><code>private void ValidateInitialized()\n{\n throw new LibraryUninitializedException(); // Just create this exception class\n}\n</code></pre>\n\n<p>Then I would create a helper method that takes a <code>Func<int></code> that you can call from each of the wrapper methods. The helper method will handle the error code stuff for you. It would look something like this (note: I have not compiled this, so I may have some minor syntax errors).</p>\n\n<pre><code>private void DoThirdPartyOperation(Func<int> operation, string message = \"\")\n{\n ValidateInitialized();\n switch(operation())\n {\n case 0:\n // No error - do nothing\n break;\n case someErrorCode:\n throw new SomeErrorException(message);\n break;\n case someOtherErrorCode:\n throw new SomeOtherErrorException(message);\n break;\n\n default:\n // Choose either to throw some sort of general exception and include\n // the error code in it OR throw an UnrecognizedErrorException\n }\n}\n\npublic void Operation1(someParameter)\n{\n DoThirdPartyOperation(() => { ThirdParty.Operation1(someParameter); });\n}\n\npublic void Operation2(someParameter)\n{\n DoThirdPartyOperation(() => { ThirdParty.Operation2(someParameter); },\n \"Failed performing Operation2\");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T08:53:12.677",
"Id": "32136",
"Score": "0",
"body": "Thanks pstrjds. I agree with your first part (ValidateInitialized), but the second is is not ok, due to incomplete information which i provided. Because, each operation may need different type of input and number of inputs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T08:56:45.403",
"Id": "32137",
"Score": "0",
"body": "Okay. I kind of thought maybe that was the case. What is the third party library you are using? Can you provide additional details?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T09:09:33.363",
"Id": "32138",
"Score": "0",
"body": "It is proprietary component, internal to our organization (at the same time we don't have control to change now:( )."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T12:26:59.560",
"Id": "32146",
"Score": "0",
"body": "Even though it solved only half of my problem, i am marking this as answer because the problem is not with the answer it is with the question. I haven't explained him fully at first."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T08:43:02.417",
"Id": "20117",
"ParentId": "20113",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20117",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T07:02:17.407",
"Id": "20113",
"Score": "1",
"Tags": [
"c#",
"error-handling"
],
"Title": "Best way to handle repetitive error code or return value"
}
|
20113
|
<p>This is my command interface:</p>
<pre><code>public interface IConverter {
void convert();
}
</code></pre>
<p>This is my Receiver class:</p>
<pre><code>public class Ogg extends Audio{
private File src;
private File trgt;
public static final String CODEC = "libvorbis";
public static final String FORMAT = "ogg";
public Ogg(File src, File trgt){
this.src = src;
this.trgt = trgt;
}
public void convertToOgg(){
audioAttr.setCodec(CODEC);
encoAttrs.setFormat(FORMAT);
encoAttrs.setAudioAttributes(audioAttr);
try {
encoder.encode(src, trgt, encoAttrs);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>And this is my Concrete Command:</p>
<pre><code>package org.hitplay.audio.converters;
public class OggConverter implements IConverter {
private Ogg ogg;
public OggConverter(Ogg ogg){
this.ogg = ogg;
}
@Override
public void convert() {
ogg.convertToOgg();
}
}
</code></pre>
<p>This is my Invoker class:</p>
<pre><code>public class AudioConverter {
IConverter audio;
public AudioConverter(IConverter audi){
this.audio = audi;
}
public void setAudio(IConverter audio){
this.audio = audio;
}
public void convert(){
audio.convert();
}
}
</code></pre>
<p>I have currently studied the command design pattern on <a href="http://www.avajava.com/tutorials/lessons/command-pattern.html?page=1" rel="nofollow">this link</a> and I was wondering if I have implemented the design pattern correctly. f I do not, please tell me why, and how else I can improve this code. Also, I have other classes besides <code>Ogg and OggConverter</code>; I also have <code>Mp3</code> and <code>Mp3Converter</code>.</p>
|
[] |
[
{
"body": "<p>I do not see the reason of for class <code>OggConverter</code> as it is now. </p>\n\n<p>Instead of that you could just add the interface <code>IConverter</code> to class <code>Ogg</code>. And remove all others classes as then only forward the call. </p>\n\n<p><code>IConverter converter = OggConverter(Ogg(file1,file2));</code></p>\n\n<p>If we add the interface to Ogg</p>\n\n<p><code>IConverter converter = Ogg(file1,file2);</code></p>\n\n<p>I also do not see the reason for class AudioConverter, beside that it can store the ref to IConverter but we can store this reference in other place. </p>\n\n<p>In addition to improve are those <code>CODEC</code> and <code>FORMAT</code> string constant. Instead of string constatns you shuld provide enumerations. </p>\n\n<pre><code>public enum AudioCodec {\n LIBVORBIS;\n}\n\n\npublic enum AudioFormat {\n OGG(\"ogg\"),\n MP3(\"mp3\");\n\nprivate final String ext; \n\nprivate AudioFormat(String ext) {\n this.ext = ext;\n}\n\n\npublic String getExt() {\n return this.ext;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T13:05:30.753",
"Id": "32150",
"Score": "0",
"body": "if I did that, would it be tightly coupled?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T13:16:53.893",
"Id": "32151",
"Score": "0",
"body": "No. Losse couplind is not based about cration as many classes as posibile. It about creation the classes that do not depend on each other. For that you should have class that know how to convert a file. and a class that provide the definition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T14:00:44.533",
"Id": "32153",
"Score": "0",
"body": "About the enums, the codecs and Formats is required to be an mp3. not an enum, if I decide to make it as an enum how would I then provide it as a String rather than an enum itself?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T14:20:46.707",
"Id": "32155",
"Score": "0",
"body": "You can use the `name` method or create own definition, see my edit."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T12:49:43.787",
"Id": "20122",
"ParentId": "20114",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T07:05:13.160",
"Id": "20114",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"design-patterns",
"interface",
"audio"
],
"Title": "Ogg audio format conversion classes"
}
|
20114
|
<p>I am working on a sparse matrix application in C and I choose compressed sparse row (CSC) and compressed sparse column (CSC) as my data structure for it. But the difficult part is I cannot improve my matrix multiplication function.</p>
<pre><code>/**
* The element and matrix are the naive format I have for sparse matrix,
* They are just for storing information got from after reading the file(s).
*/
typedef struct{
int row;
int column;
int id;
int value;
} element;
typedef struct{
int row;
int column;
int numberofElements;
element* elements;
} matrix;
/**
* CSR and CSC are compressed sparse row/column format to store sparse matrix
* The detailed definition is here:http://en.wikipedia.org/wiki/Sparse_matrix
*/
typedef struct{
int row;
int column;
int length;//The number of non-zero element in a matrix.
int* val;
int* col_ind;
int* row_ptr;
} CSR;
typedef struct{
int row;
int column;
int length;
int* val;
int* row_ind;
int* col_ptr;
} CSC;
typedef struct{
int val;
int index;
} tuple;
int compute(tuple* row, tuple* column, int row_length, int col_length){
int result = 0;
for(int i = 0; i < row_length; i++){
for(int j = 0; j < col_length; j++){
if(row[i].index == column[j].index){
result += row[i].val * column[j].val;
}
}
}
return result;
}
void multiply(matrix X, matrix Y, matrix* result){
CSR cX;
CSC cY;
int product = 0;
tuple **row = NULL, **column = NULL;
int *row_length,*col_length;
matrixtoCSR(&cX, X);
matrixtoCSC(&cY, Y);
row = (tuple **) malloc(X.row * sizeof(tuple *));
row_length = (int *) malloc (X.row * sizeof(int));
column = (tuple **) malloc(Y.column *sizeof(tuple *));
col_length = (int *) malloc (Y.column * sizeof (int ));
for(int r = 0; r < X.row; r++){
row_length[r] = (r == cX.row-1) ? cX.length - cX.row_ptr[r]:cX.row_ptr[r+1] - cX.row_ptr[r];
row[r] = !row_length[r] ? NULL : (tuple* ) malloc (row_length[r] * sizeof(tuple));
if(row[r] != NULL){
for(int i = 0; i < row_length[r]; i++){
row[r][i].val = cX.val[cX.row_ptr[r]+i];
row[r][i].index = cX.col_ind[cX.row_ptr[r]+i];
}
}
}
for(int c = 0; c < Y.column; c++){
col_length[c] = (c == cY.column-1) ? cY.length- cY.col_ptr[c]:cY.col_ptr[c+1] - cY.col_ptr[c];
column[c] = !col_length[c] ? NULL : (tuple *) malloc (col_length[c] * sizeof(tuple));
if(column != NULL){
for(int i = 0; i < col_length[c]; i++){
column[c][i].val = cY.val[cY.col_ptr[c]+i];
column[c][i].index = cY.row_ind[cY.col_ptr[c]+i];
}
}
}
for(int r = 0; r < X.row; r++){
for(int c = 0; c < Y.column; c++){
product = 0;
if(row[r] != NULL && column[c] != NULL)
product=compute(row[r], column[c], row_length[r], col_length[c]);
if(product){
result->elements[result->numberofElements].row = r;
result->elements[result->numberofElements].column = c;
result->elements[result->numberofElements].id = r * result->column + c;
result->elements[result->numberofElements].value = product;
result->numberofElements++;
}
}
}
result->elements = (element *)realloc( result->elements , result->numberofElements * sizeof(element));
for(int i = 0 ; i < X.row; i++){
if(row[i] != NULL)
free(row[i]);
}
free(row);
for(int i = 0 ; i < Y.column; i++){
if(column[i] != NULL)
free(column[i]);
}
free(column);
free(row_length);
free(col_length);
cleanCSR(&cX);
cleanCSC(&cY);
}
</code></pre>
<p>I used gprof to prof it and it shows that if I multiply 4 1000*1000 matrix the program will take about 7s to compute the output and 98.7% of time it is running this function.</p>
<p>How can I improve it? I have tried a lot of things like trade-off some space but the time just doesn't go down. I think I am kind of stuck.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T19:16:11.840",
"Id": "32164",
"Score": "0",
"body": "Well you could make sure the indentation is consistent so people can read it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T21:58:55.700",
"Id": "32175",
"Score": "2",
"body": "please post the struct and type definitions too - I wont review it unless I can compile it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T10:54:15.903",
"Id": "32194",
"Score": "0",
"body": "Hi, I have updated it. would u please have a look at it now? Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T18:16:03.310",
"Id": "32316",
"Score": "0",
"body": "Your `tuple` type and `matrixtoCSR` and `matrixtoCSC` are still missing. Also please post a `main()` with a simple test case. BTW why do you use a CSC **and** a CSR?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T18:22:09.910",
"Id": "32317",
"Score": "0",
"body": "@WilliamMorris Hi I have updated it with the def of tuple but sorry I cannot provide a test case because the main method reads some files of certain form and then call the multiply function. It will be too many lines to paste here. If you want I can send a email to you withe all the source files and test files. The reason why I use CSC and CSR is that I read the sparse matrix entry in wikipedia and I think it is a good idea to store the matrix in this form since it is fast for row/column slicing."
}
] |
[
{
"body": "<p>Here is my understanding of what you are doing:</p>\n\n<ul>\n<li>you have some matrices stored in files using your own 'naive' format.</li>\n<li>you read these into your <code>matrix</code> structures</li>\n<li>two of these matrices are then passed to <code>multiply()</code></li>\n<li>you convert one of the matrices into a Compressed Row Storage</li>\n<li>and the other into a Compressed Column Storage</li>\n<li>you then extract the matrices from these compressed forms into arrays of\nvalues, one for rows and one for columns</li>\n<li>and finally you multiply them.</li>\n</ul>\n\n<p>I find that complicated!</p>\n\n<ul>\n<li>Why not store the matrices directly in compressed format?</li>\n<li>Or convert your naive format into the extracted form without the CSC/CSR stage?</li>\n<li>Why use <strong>both</strong> CSR and CSC? They are both methods of compressing a matrix but\nthey do the same job. I can see no point in using both.</li>\n</ul>\n\n<p>With these defects, there is not much point in reviewing the code in detail,\nbut here are some general points:</p>\n\n<ul>\n<li>include the right headers and don't cast the return from <code>malloc</code></li>\n<li><p>know that <code>calloc</code> gives you a zeroed array </p></li>\n<li><p>use <code>const</code> where possible on function parameters (eg row/column in\n<code>compute</code>, X/Y in <code>multiply</code>)</p></li>\n<li><p>use <code>static</code> where possible for functions</p></li>\n<li><p><code>compute</code> and <code>multiply</code> are badly named</p></li>\n<li><p>improve your naming in general. You have four structures all containing\nfields named <code>row</code> and <code>column</code>. I'm sure at least two of these contain the\n<strong>number</strong> of rows/columns (eg. <code>n_rows</code>). And your <code>tuple</code> lists are\ncalled <code>row</code> and <code>column</code>. It all becomes very confusing.</p></li>\n<li><p>pass by reference is better for structures.</p></li>\n<li><p>your <code>multiply</code> does a lot more than just multiply the matrices. It first\ncompresses the input matrices and then expands the compressed matrices.\nThese steps belong elsewhere (if they belong anywhere). Your first two big\nfor-loops shoud be separate functions. The nested-for in each might well\nbelong in a separate function too (difficult to tell, but nested loops are\noften better split). And the free-loops should also be separate functions. By splitting a big function into several smaller ones (with appropriate names), you make the code easier to read and test.</p></li>\n</ul>\n\n<p>Sorry to be negative.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T20:29:46.813",
"Id": "32323",
"Score": "1",
"body": "Thanks. I will try to follow your advice and modify my code. Thanks indeed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T20:02:57.950",
"Id": "20213",
"ParentId": "20124",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T14:22:58.130",
"Id": "20124",
"Score": "2",
"Tags": [
"optimization",
"performance",
"c",
"matrix"
],
"Title": "Sparse matrix multiplication"
}
|
20124
|
<p>I have some pretty basic Regex that scans the output of a <strong>HTML</strong> file (the whole document source) and attempts to extract all of the absolute links that look like images. Whether they <em>are</em> actually images or not isn't too important, as those checks would be made later.</p>
<p>I am just trying to see if this Regex looks okay, since I kind of hacked it together from various sources. </p>
<p><strong>The Raw Regex Pattern:</strong></p>
<pre><code>\bhttps?:[^)''"]+\.(?:jpg|jpeg|gif|png)
</code></pre>
<p><strong>The Regex in Practice (I am coding in Railo - an open source CFML engine):</strong></p>
<pre><code><cfset variables.getImageURLs = reMatch('\bhttps?:[^)''"]+\.(?:jpg|jpeg|gif|png)', variables.getDocument) />
</code></pre>
<p><strong>NOTE:</strong> <code>variables.getDocument</code> contains the raw HTML code.</p>
<p>It seems to work great right now and I'm not seeing any issues, but just wanting to know if you can see any potential pitfalls with this method? Is there room for improvement?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T14:37:22.860",
"Id": "35189",
"Score": "1",
"body": "Someone has to link it, do not parse html with regex: http://stackoverflow.com/a/1732454/7602"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T15:01:26.837",
"Id": "35191",
"Score": "0",
"body": "@tomdemuyt Nice and enjoyable read! However, in my case, it's the best thing going right now and I only need it for the simplest of tasks, nothing complicated other than grabbing a few links."
}
] |
[
{
"body": "<p>Have you tested your regex with lines such as :\n<a href=\"http://example.com/\" rel=\"nofollow\">http://example.com/</a> file.png</p>\n\n<p>(note the space before file).</p>\n\n<p>It matches such lines. Is it what you intend ?</p>\n\n<p>As your question is about efficiency, you should consider having only valid char for url so that it rejects string sooner (instead of simply excluding some invalid chars)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T11:11:35.650",
"Id": "32195",
"Score": "0",
"body": "Ahh, good catch! Any idea how I can adapt what I have to avoid this? Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T12:22:59.460",
"Id": "32198",
"Score": "0",
"body": "@MichaelGiovanniPumo I think adding `\\s` into the disallowed characters section should prevent this: `\\bhttps?:[^)''\"\\s]+\\.(?:jpg|jpeg|gif|png)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T15:40:19.240",
"Id": "32208",
"Score": "0",
"body": "Next catch : `http://exemple.com/folder.png/file.txt`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T15:00:50.100",
"Id": "32350",
"Score": "0",
"body": "@sfk Good catch - any ideas on how to end the match after one of the extensions has been met? That might solve it. My Regex knowledge is still very much in the novice stage! Thanks."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T23:59:46.480",
"Id": "20138",
"ParentId": "20126",
"Score": "2"
}
},
{
"body": "<p>@sfk find next catch, link will be: <a href=\"http://exemple.com/folder.png/file.txt\" rel=\"nofollow\">http://exemple.com/folder.png/file.txt</a>\nI use Negative lookahead. Specifies a group that can not match after your main expression (ie. if it matches, the result is discarded). For testing RegEx i used <a href=\"http://gskinner.com/RegExr/\" rel=\"nofollow\">http://gskinner.com/RegExr/</a></p>\n\n<pre><code>\\bhttps?:[^)''\"]+\\.(?:jpg|jpeg|gif|png)(?![a-z/])\n</code></pre>\n\n<p>Links as <a href=\"http://exemple.com/folder.png/file.txt\" rel=\"nofollow\">http://exemple.com/folder.png/file.txt</a> ignored well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T17:02:09.070",
"Id": "35209",
"Score": "0",
"body": "This didn't seem to work very well, are you sure this is correct? It seemed to match more than it should have done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T20:34:17.777",
"Id": "35214",
"Score": "0",
"body": "yes, i updated comment and put link for online RegEx, where i testing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T15:21:15.057",
"Id": "35273",
"Score": "0",
"body": "Try it with a whole set of links including good and bad ones, it seems to match more than it should. It event matched a simple domain name? Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-20T16:22:01.873",
"Id": "35279",
"Score": "0",
"body": "Surprised to hear it. Basic expression is the absolute same as your, I have added a (?![a-z/]) to the end your pattern. What match more than it should? Can you open this link http://regexr.com?33rg4 to test and create own example?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T11:22:53.547",
"Id": "22888",
"ParentId": "20126",
"Score": "2"
}
},
{
"body": "<p>If you're truly only looking for images, why not parse any <code>src</code> attributes you can find? As it stands, all of the provided Regular Expressions will fail on local images, as well as on dynamically generated images, such as:</p>\n\n<pre><code><img src=\"/local/images/get_profile_pic.php?id=12345\" title=\"John Doe\" />\n</code></pre>\n\n<p>This is perfectly valid, and none of the other expressions would capture them. Generally, for parsing HTML, you're better of traversing it with something like an XML reader, or a DOM builder, depending on how well the HTML is formed.</p>\n\n<p>Ben Nadel has a pretty good <a href=\"http://www.bennadel.com/blog/1723-Parsing-Invalid-HTML-Into-XML-Using-ColdFusion-Groovy-And-TagSoup.htm\" rel=\"noreferrer\">blog article</a> on working with badly formed HTML and translating into an XML document. Once you have an XML document, you can unleash the power of <code>XPath</code> to do some very nice searching.</p>\n\n<p>If, however, you just want a quick and dirty <code>RegEx</code> to get the job done, I'd recommend actually using the underlying <code>Java</code> Regular Expression library, as it's probably more efficient when matching multiple items over a large document.</p>\n\n<p>The main <code>RegEx</code> I'll be using is as follows:</p>\n\n<pre><code><img\\s+[^>]*?src=(\"|')([^\"']+)\\1\n</code></pre>\n\n<p>Which looks for the <code>src</code> attribute in <code>img</code> tags. You can vary this as you see fit.</p>\n\n<pre><code><cfset html = variables.getDocument /> <!--- your HTML --->\n<cfset pattern = CreateObject(\"java\",\"java.util.regex.Pattern\").compile('(?i)<img\\s+[^>]*?src=(\"|')([^\"']+)\\1') />\n<cfset matcher = pattern.matcher(html) />\n\n<!--- loop through the matches --->\n<cfloop condition=\"matcher.find()\">\n <cfset src = matcher.group(2) />\n</cfloop>\n</code></pre>\n\n<p><strong>UPDATE :</strong>\nHere's an explanation of the pattern I chose:</p>\n\n<pre><code><img - Literal string \"<img\", match the opening tag\n\\s+ - Match one or more whitespace characters, so <img\\t is valid\n[^>]*? - Lazily match any character that is not a '>' while looking for the next literal string\nsrc= - Literal string \"src=\"\n(\"|') - Match either a single or a double quote, both are valid in HTML\n([^\"']+) - Match anything that isn't a single or double quote. Note: You *could* use [^\\1] here, however this way the match will reject malformed HTML attributes that have mismatched quotes\n\\1 - Match the value of the first group (either a single or double quote)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T12:15:03.153",
"Id": "35182",
"Score": "0",
"body": "Thanks Jason. As it happens, I already utilise jSoup in my application. So getting image SRC contents is extremely trivial. However, I need to get more than just the contents of SRC attributes in image tags. Sometimes, references to images are made in CSS, or perhaps inline CSS on HTML tags (for things like logos etc). I want to be able to retrieve as many as possible you see."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T16:48:53.260",
"Id": "35206",
"Score": "0",
"body": "Then a more general solution can be used, however you're still going experience the same issues as I mention here. It may be easier to write patterns to match each way that an image can be referred to (there is a finite, documented list of ways this can be done)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T17:05:55.247",
"Id": "35210",
"Score": "0",
"body": "Yep, I understand. As it happens, the regex part is just to get URL's that look like images. I will do various checks there after to sanitize them, like if it's a valid URI to start with, mime type checks etc. Thanks for your input though - it's an insightful read and will help!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-05T19:31:22.720",
"Id": "407781",
"Score": "0",
"body": "Excellent answer. The regex pattern is very well thought out, and is easier than having to set up jSoup. I also like your use of Java. I am looking forward to implementing this, in a current project. Upvoted..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T11:48:32.970",
"Id": "22889",
"ParentId": "20126",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T15:37:21.613",
"Id": "20126",
"Score": "4",
"Tags": [
"regex",
"coldfusion"
],
"Title": "Regex to get all image links"
}
|
20126
|
<pre><code>public class NANDFunction : FunctionInfo
{
public override string Name { get { return "NAND"; } }
public override int MinArgs { get { return 2; } }
public override int MaxArgs { get { return 2; } }
public override object Evaluate(object[] args)
{
bool arg0 = CalcConvert.ToBool(args[0]);
bool arg1 = CalcConvert.ToBool(args[1]);
return ((arg0 != arg1) || (!arg0 && !arg1));
}
}
</code></pre>
<p>What do you think of this code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T19:20:25.187",
"Id": "32165",
"Score": "0",
"body": "Is FunctionInfo a class you've created? If so, what does it look like?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T19:22:05.383",
"Id": "32166",
"Score": "0",
"body": "no, it is from a third party control , a spread sheet control.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T19:22:54.990",
"Id": "32167",
"Score": "0",
"body": "static analysis tell me I can remove the last \"!arg1\" because it is always true...I don' get it why it says that either."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T19:39:46.527",
"Id": "32169",
"Score": "2",
"body": "Because if arg0 = true and arg1 = false then the left part of the or passes and the statement exists. Therefore if you get to the right part of the check, if arg0 is false the right part fails there, if it is true, it failed in the left side, so you will never hit the !arg1 check."
}
] |
[
{
"body": "<p>You may want to add some additional validation around how many arguments you're expecting (since you know via <code>MinArgs</code> and <code>MaxArgs</code>). You can also eliminate having to create an object array explicitly in the caller by using the <code>params</code> keyword (make sure you do it in the declaration in <code>FunctionInfo</code> as well). Lastly, if this class is intended to be non-inheritable (unlike <code>FunctionInfo</code>), mark it as <code>sealed</code>:</p>\n\n<pre><code>public sealed class NANDFunction : FunctionInfo\n{\n public override string Name { get { return \"NAND\"; } }\n public override int MinArgs { get { return 2; } }\n public override int MaxArgs { get { return 2; } }\n\n public override object Evaluate(params object[] args)\n {\n if ((args.Length < this.MinArgs) || (args.Length > this.MaxArgs))\n {\n throw new ArgumentException(\"An insufficient number of arguments were passed.\");\n }\n\n bool arg0 = CalcConvert.ToBool(args[0]);\n bool arg1 = CalcConvert.ToBool(args[1]);\n return (arg0 != arg1) || (!arg0 && !arg1);\n } \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T21:33:09.910",
"Id": "32173",
"Score": "2",
"body": "Now that I'm thinking about it, the argument validation (the `if` block with the `throw`) might be better handled in the `FunctionInfo` superclass' implementation of `Evaluate` and be replaced in the subclass with a call to `base.Evaluate(args);`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T14:50:55.830",
"Id": "32205",
"Score": "1",
"body": "Sharing the common validation is a good idea, but I don't like calling the base implementation for that. For one, you're calling a method that returns something and you'll always ignore that. I think separating this into `public Evaluate` and `protected abstract EvaluateNoValidation` (or some better name) would be better."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T19:34:27.263",
"Id": "20131",
"ParentId": "20129",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20131",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T19:14:13.847",
"Id": "20129",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Possible issues and best practices for this piece of code"
}
|
20129
|
<p>I'm developing a desktop app that will scan a user's system for mp3 files and send their whole collection to a website. I'm assuming the best file format for sending this data to a server would be XML -- although correct me if I'm wrong.</p>
<p>Can someone kindly comment on whether the formatting of the sample XML file below looks okay? Thanks!</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<collection>
<artist name="Michael Jackson">
<track>Beat It</track>
<track>Thriller</track>
</artist>
<artist name="The Beatles">
<track>Hey Jude</track>
<track>Yellow Submarine</track>
</artist>
<artist name="Eminem">
<track>Lose Yourself</track>
<track>Without Me</track>
</artist>
</collection>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T22:25:23.630",
"Id": "32177",
"Score": "2",
"body": "Are you trusting metadata from the file? What about performing some sort of hashing on the file, to get ids? What is your usecase, if somebody tries to feed you false information (tracks they don't have, artists that don't exist, tracks that belong to other artists, various misspellings)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T23:06:58.757",
"Id": "32178",
"Score": "0",
"body": "I'm actually using this for .cdg files, which AFAIK don't have ID3 tags. I'm trusting that the user has them formatted in a way that contains the artist & track title and will perform validation once the XML payload is uploaded to the server."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T05:20:49.543",
"Id": "32187",
"Score": "0",
"body": "to expand on @clockwork-muse 's comment but to quote your question : \"I'm developing a desktop app that will scan a user's system for mp3 files and send their whole collection to a website.\" ---- have you considered the situation of a user having 3tb+ of \"validated\" files? I know this is not your actual question but your proposed operation is suspect to say the least. What volume of data are you capable of processing realistically? That will help shape an answer to your question."
}
] |
[
{
"body": "<p>It looks fine. I'd add a space before the xml closing tag:</p>\n\n<p><code><?xml version=\"1.0\" encoding=\"utf-8\" ?></code></p>\n\n<p>But surely you want more than artist and track title? Album? Maybe not much else could be figured out by the scanning. But if you can get into the ID3 tag of the MP3 file, you could get more.</p>\n\n<p>An XML Validator found no problems either: <a href=\"http://www.w3schools.com/xml/xml_validator.asp\" rel=\"nofollow\">http://www.w3schools.com/xml/xml_validator.asp</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T21:57:20.223",
"Id": "20133",
"ParentId": "20130",
"Score": "1"
}
},
{
"body": "<p>You may run into a problem if a track has more than one artist.</p>\n\n<p>You'd have to enter the track for each artist again, or you'd have to only use the first artist, or you'd have to create a new \"combined\" artist.</p>\n\n<p>Why not omit the artist→track hierarchy?</p>\n\n<pre><code><collection>\n <track>\n <title>Thriller</title>\n <artist>Michael Jackson</artist>\n </track>\n <track>\n <title>Hey Jude</title>\n <artist>The Beatles</artist>\n </track>\n</collection> \n</code></pre>\n\n<p>Benefits:</p>\n\n<ul>\n<li>You can add more metadata for tracks (composer, album, etc.)</li>\n<li>You can add tracks without title and/or artist</li>\n</ul>\n\n<p>If different artists may have the same name, you'd need a way to differentiate the <code>artist</code> elements; e.g. by using <code>id</code> with an ID of an artist database.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T16:14:59.777",
"Id": "32210",
"Score": "1",
"body": "I would second this and add that many people are very sloppy about keeping artist uniform - i.e. \"Beatles\", \"The Beatles\", \"beatles\", etc."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T14:45:13.813",
"Id": "20150",
"ParentId": "20130",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T19:19:35.797",
"Id": "20130",
"Score": "2",
"Tags": [
"xml"
],
"Title": "XML format for mp3 files"
}
|
20130
|
<p>I need help refactoring this code to dynamically generate a sort string that I can send to my data layer so that my database does the sorting instead of it happening in memory. I am using MVC4 with EF5 as my data layer.</p>
<pre><code>public ActionResult InstanceSearch(int? page, string sortOrder, string computerName, string instanceName,
string productName, string version)
{
int pageSize = 10;
int pageNumber = (page ?? 1);
if (pageNumber < 1)
{
pageNumber = 1;
}
if (string.IsNullOrEmpty(sortOrder))
{
sortOrder = "Computer";
}
ViewBag.CurrentSort = sortOrder;
ViewBag.ComputerSort = sortOrder == "Computer" ? "ComputerDesc" : "Computer";
ViewBag.InstanceSort = sortOrder == "Instance" ? "InstanceDesc" : "Instance";
ViewBag.VersionSort = sortOrder == "Version" ? "VersionDesc" : "Version";
ViewBag.ProductSort = sortOrder == "Product" ? "ProductDesc" : "Product";
//IEnumerable<Instance> instances = ecuWebDataContext.Instances;
IQueryable<Instance> instances
= string.IsNullOrEmpty(computerName) == true ? ecuWebDataContext.Instances : ecuWebDataContext.Instances.Where(i => i.Computer.Name == computerName);
if (string.IsNullOrEmpty(instanceName) == false)
{
instances = instances.Where(i => i.Name == instanceName);
}
if (!string.IsNullOrEmpty(productName))
{
ProductName product = (ProductName)Enum.Parse(typeof(ProductName), productName);
instances = instances.Where(i => i.Product.Name == product);
}
if (!string.IsNullOrEmpty(version))
{
instances = instances.Where(i => i.Version == version);
}
switch (sortOrder)
{
case "Computer":
instances = instances.OrderBy(i => i.Computer.Name);
break;
case "ComputerDesc":
instances = instances.OrderByDescending(i => i.Computer.Name);
break;
case "Instance":
instances = instances.OrderBy(i => i.Name);
break;
case "InstanceDesc":
instances = instances.OrderByDescending(i => i.Name);
break;
case "Version":
instances = instances.OrderBy(i => i.Version);
break;
case "VersionDesc":
instances = instances.OrderByDescending(i => i.Version);
break;
case "Product":
instances = instances.OrderBy(i => i.Product.Name);
//instances = instances.OrderBy(i => Enum.Parse(typeof(ProductName), i.Product.Name));
break;
case "ProductDesc":
instances = instances.OrderByDescending(i => i.Product.Name);
//instances = instances.OrderByDescending(i => Enum.Parse(typeof(ProductName), i.Product.Name));
break;
}
ViewBag.SortOrder = sortOrder;
var instanceSearchModel = new InstanceSearchModel { ComputerName = computerName, InstanceName = instanceName };
ViewBag.ComputerName = computerName;
ViewBag.InstanceName = instanceName;
ViewBag.ProductName = productName;
ViewBag.InstanceCount = instances.Count();
ViewBag.Version = version;
return View(instances.ToPagedList(pageNumber, pageSize));
}
</code></pre>
<p>I tried returning an IQueryable from the data layer, but then I run into connection problems because I never close it.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T03:13:54.963",
"Id": "32186",
"Score": "0",
"body": "Does this work correctly? If not, then you need to get it working before posting here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T16:53:54.463",
"Id": "32214",
"Score": "0",
"body": "Yes this works correctly. However I have wrappers around the datalayer to hide it behind interfaces so I can swap out databases without affecting the application and this code uses the database context directly which has the intened effect of offloading to the database for the sorting, but I am looking for help building the sort string then sending it completely to my data layer."
}
] |
[
{
"body": "<p>The data layer that appears to be causing your problem is the root cause.</p>\n\n<p>You're abstracting over an abstraction, and in the process having to marshall sort orders around as a result. Prefer injecting your context in a request scope and remove the abstraction.</p>\n\n<p>You can always create an abstraction over the specific query, and inject the query, which has a dependency on the context, if you <em>really</em> need to.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-11T15:47:43.770",
"Id": "32704",
"Score": "0",
"body": "Ok thank you i will get started on doing that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-11T14:58:25.520",
"Id": "20426",
"ParentId": "20132",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20426",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T21:33:00.447",
"Id": "20132",
"Score": "1",
"Tags": [
"c#",
"asp.net",
"asp.net-mvc-4"
],
"Title": "How to dynamically Generate Sort strings for Data Layer from Controller"
}
|
20132
|
<p>I would like to know, if my design of this class is good OOP.
Should I implement for every hash algorithm a separate class?
I'm asking this, because the <code>HashService</code> can be used with a <code>KeyedHashAlgorithm</code> which wouldn't work correctly?!</p>
<pre><code>public class HashService : IDisposable
{
public HashService(HashAlgorithm algorithm)
{
HashAlgorithm = algorithm;
Encoder = Encoding.UTF8;
}
protected HashAlgorithm HashAlgorithm { get; set; }
/// <summary>
/// The size, in bits, of the computed hash code.
/// </summary>
public int HashSize
{
get { return HashAlgorithm.HashSize; }
}
/// <summary>
/// Gets or sets the encoding for strings.
/// </summary>
public Encoding Encoder { get; set; }
public string ComputeHash(string input)
{
byte[] bytes = Encoder.GetBytes(input);
byte[] hash = ComputeHash(bytes);
return ToHex(hash); // method impl. omitted
}
/// <summary>
/// Computes the hash value for the specified byte array
/// </summary>
/// <param name="buffer">The input to compute the hash code for.</param>
/// <returns>The computed hash code.</returns>
public byte[] ComputeHash(byte[] buffer)
{
return HashAlgorithm.ComputeHash(buffer);
}
public byte[] ComputeHash(byte[] buffer, int offset, int count)
{
return HashAlgorithm.ComputeHash(buffer, offset, count);
}
public byte[] ComputeHash(Stream inputStream)
{
return HashAlgorithm.ComputeHash(inputStream);
}
#region Implementation of IDisposable
// omitted
#endregion
// ReSharper disable InconsistentNaming
public static HashService CreateMd5()
{
return new HashService(new MD5CryptoServiceProvider());
}
public static HashService CreateRIPEMD160()
{
return new HashService(new RIPEMD160Managed());
}
public static HashService CreateSHA256()
{
return new HashService(new SHA256Managed());
}
public static HashService CreateSHA384()
{
return new HashService(new SHA384Managed());
}
public static HashService CreateSHA512()
{
return new HashService(new SHA512Managed());
}
public static HashService CreateSHA1()
{
return new HashService(new SHA1Managed());
}
public static HashService CreateCrc32()
{
return new HashService(new Crc32Managed());
}
// ReSharper restore InconsistentNaming
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T00:57:39.973",
"Id": "32184",
"Score": "0",
"body": "If you want to control the Algorithms supported then you could make the constructor private. Then you would control what algorithms you support. Not very OCP though???"
}
] |
[
{
"body": "<p>Personally I think that all properties (Getters/Setters) should be at the top of the class, before the constructor. I believe that also matches Microsoft's style guide.</p>\n\n<p>I personally use <code>this.Property</code>, I think its much easier to read and tells you its a class member not a local variable (or static method).</p>\n\n<pre><code>HashAlgorithm = algorithm; -> this.HashAlgorithm = algorithm;\n</code></pre>\n\n<p>Also naming, those are acronyms so capitalize all the letters.</p>\n\n<pre><code>public static HashService CreateMd5() -> public static HashService CreateMD5()\npublic static HashService CreateCrc32() -> public static HashService CreateCRC32()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T18:35:45.747",
"Id": "32221",
"Score": "0",
"body": "No, MS spec is that properties come after constructors, but before other methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-04T16:03:47.990",
"Id": "34176",
"Score": "0",
"body": "The MS style guide says that you should only capitalize the first letter of acronyms with at least three letters. \"When using acronyms, use Pascal case or camel case for acronyms more than two characters long. For example, use HtmlButton or htmlButton. However, you should capitalize acronyms that consist of only two characters, such as System.IO instead of System.Io.\""
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T23:50:25.343",
"Id": "20137",
"ParentId": "20134",
"Score": "0"
}
},
{
"body": "<p>Overall, its nice code. Easy to read and good use of white space.</p>\n\n<p>I would move the creating of the HashService to a Factory class though. The way you are using it, I don't think it belongs in the class.</p>\n\n<pre><code>public class HashServiceFactory\n{\n public Create(HashAlgorithm algorithm)\n {\n return new HashService(algorithm);\n }\n}\n\n// Usage\n\nvar factory = new HashServiceFactory();\n\nvar sha256Managed = factory.Create(new SHA256Managed());\nvar md5CryptoServiceProvider = factory.Create(new MD5CryptoServiceProvider());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T05:38:47.870",
"Id": "32188",
"Score": "1",
"body": "In what regards is the way he using it make it better to put into a separate class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T17:13:55.023",
"Id": "32215",
"Score": "0",
"body": "For one, it would allow addition of more HashAlgorithms without having to change the behaviour of HashService."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T18:07:48.810",
"Id": "32218",
"Score": "1",
"body": "Agreed. Although he can still do that with the current implementation as the HashService constructor allows that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T21:01:24.817",
"Id": "32229",
"Score": "0",
"body": "True. Even though its not shown in my example, with the factory, you could have all HashService instances you need in your app created in a static dictionary that has the HashAlogorithm as the key, change the Create method to accept a generic, or type, find that HashService in your dictionary and return it. Doing it this will would allow you to inject the factory and not have news all over your code."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T01:01:06.907",
"Id": "20139",
"ParentId": "20134",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T22:58:01.857",
"Id": "20134",
"Score": "3",
"Tags": [
"c#",
"object-oriented",
"cryptography"
],
"Title": "Nice design of my hash service class"
}
|
20134
|
<pre><code>Uint8Array.prototype.indexOfMulti = function(searchElements, fromIndex) {
fromIndex = fromIndex || 0;
var index = Array.prototype.indexOf.call(this, searchElements[0], fromIndex);
if(searchElements.length === 1 || index === -1) {
// Not found or no other elements to check
return index;
}
for(var i = index, j = 0; j < searchElements.length && i < this.length; i++, j++) {
if(this[i] !== searchElements[j]) {
return this.indexOfMulti(searchElements, index + 1);
}
}
return (i === index + searchElements.length) ? index : -1;
};
</code></pre>
<p>It works fine but I wonder if I missed any important case or if anyone sees a way to optimize this.</p>
|
[] |
[
{
"body": "<p>First things first. This code is fairly difficult to read. <code>indexOfMulti</code> could mean</p>\n\n<ul>\n<li>You're searching for any one of multiple values.</li>\n<li>You're searching for all occurrences of a value (less likely -- might be <code>indicesOf</code> or <code>findAll</code>).</li>\n<li>You're searching for the first occurrence of a sequence.</li>\n</ul>\n\n<p>I'd name this something like <code>find</code>, <code>findSequence</code>, <code>findSubstring</code>. I'd also rename <code>searchElements</code> to something like <code>needle</code>, <code>targetSequence</code>.</p>\n\n<hr>\n\n<p>You have two different efficiency issues here.</p>\n\n<p>First, if this code is running in an implementation without tail-call optimization (I can't tell if <em>any</em> do, much less whether it's common), your memory usage may blow up whenever the first part of <code>needle</code> is common in your <code>haystack</code> but the full <code>needle</code> isn't found, because you'll blow up the stack. Better to implement this non-recursively.</p>\n\n<p>Second, you've chosen the naive string search algorithm (see <a href=\"http://en.wikipedia.org/wiki/String_searching_algorithm\" rel=\"nofollow\">http://en.wikipedia.org/wiki/String_searching_algorithm</a>). It will work fine when <code>needle</code> and <code>haystack</code> are small, or when prefixes of <code>needle</code> are rare in <code>haystack</code>, but it will be quite slow on the following example:</p>\n\n<pre><code>haystack = \"aaaaaaaaaaaaaaaaaaaaab\";\nneedle = \"aaaab\";\nhaystack.findSequence(needle);\n</code></pre>\n\n<p>You'd be better off selecting one of the other algorithms in that wikipedia article; a good choice is <a href=\"http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm\" rel=\"nofollow\">Boyer-Moore</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T00:04:20.497",
"Id": "37452",
"ParentId": "20136",
"Score": "3"
}
},
{
"body": "<p>Regarding Boyer-Moore: <a href=\"https://gist.github.com/etrepum/6235082\" rel=\"nofollow noreferrer\">https://gist.github.com/etrepum/6235082</a></p>\n\n<p><a href=\"http://www.typescriptlang.org/play/#src=type%20needleType%20%3D%20string%20%7C%20Uint8Array%20%7C%20ArrayBuffer%3B%0Atype%20haystackType%20%3D%20ArrayBuffer%20%7C%20Uint8Array%3B%0A%0A%2F%2F%20Implementation%20of%20Boyer-Moore%20substring%20search%20ported%20from%20page%20772%20of%0A%2F%2F%20Algorithms%20Fourth%20Edition%20(Sedgewick%2C%20Wayne)%0A%2F%2F%20http%3A%2F%2Falgs4.cs.princeton.edu%2F53substring%2FBoyerMoore.java.html%0A%2F*%0AUSAGE%3A%0A%20%20%20%2F%2F%20needle%20should%20be%20ASCII%20string%2C%20ArrayBuffer%2C%20or%20Uint8Array%0A%20%20%20%2F%2F%20haystack%20should%20be%20an%20ArrayBuffer%20or%20Uint8Array%0A%0A%20%20%20const%20boyerMoore%20%3D%20new%20BoyerMoore(needle)%3B%0A%20%20%20const%20indexes%20%3D%20boyerMoore.findIndexes(haystack)%3B%0A*%2F%0A%0Aclass%20BoyerMoore%20%7B%0A%20%20private%20search%3A%20((txtBuffer%3A%20needleType%2C%20start%3F%3A%20number%2C%20end%3F%3A%20number)%20%3D%3E%20number%20)%3B%0A%20%20private%20skip%3A%20number%3B%0A%0A%20%20constructor(needle%3A%20needleType)%20%7B%0A%20%20%20%20%5Bthis.search%2C%20this.skip%5D%20%3D%20this.boyerMoore(needle)%3B%0A%20%20%7D%0A%0A%20%20public%20findIndex(haystack%3A%20haystackType)%3A%20number%20%7B%0A%20%20%20%20return%20this.search(haystack)%3B%0A%20%20%7D%0A%0A%20%20public%20findIndexes(haystack%3A%20haystackType)%3A%20number%5B%5D%20%7B%0A%20%20%20%20const%20indexes%3A%20number%5B%5D%20%3D%20%5B%5D%3B%0A%20%20%20%20for%20(let%20i%20%3D%20this.search(haystack)%3B%20i%20!%3D%3D%20-1%3B%20i%20%3D%20this.search(haystack%2C%20i%20%2B%20this.skip))%20%7B%0A%20%20%20%20%20%20indexes.push(i)%3B%0A%20%20%20%20%7D%0A%20%20%20%20return%20indexes%3B%0A%20%20%7D%0A%0A%20%20private%20asUint8Array(input%3A%20Uint8Array%20%7C%20string%20%7C%20ArrayBuffer)%3A%20Uint8Array%20%7B%0A%20%20%20%20if%20(input%20instanceof%20Uint8Array)%20%7B%0A%20%20%20%20%20%20return%20input%3B%0A%20%20%20%20%7D%20else%20if%20(typeof(input)%20%3D%3D%3D%20'string')%20%7B%0A%20%20%20%20%20%20%2F%2F%20This%20naive%20transform%20only%20supports%20ASCII%20patterns.%20UTF-8%20support%0A%20%20%20%20%20%20%2F%2F%20not%20necessary%20for%20the%20intended%20use%20case%20here.%0A%20%20%20%20%20%20const%20uint8Array%3A%20Uint8Array%20%3D%20new%20Uint8Array(input.length)%3B%0A%20%20%20%20%20%20for%20(let%20i%20%3D%200%3B%20i%20%3C%20input.length%3B%20i%2B%2B)%20%7B%0A%20%20%20%20%20%20%20%20const%20charCode%20%3D%20input.charCodeAt(i)%3B%0A%20%20%20%20%20%20%20%20if%20(charCode%20%3E%20127)%20%7B%0A%20%20%20%20%20%20%20%20%20%20throw%20new%20TypeError('Only%20ASCII%20patterns%20are%20supported')%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20uint8Array%5Bi%5D%20%3D%20charCode%3B%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20return%20uint8Array%3B%0A%20%20%20%20%7D%20else%20%7B%0A%20%20%20%20%20%20%2F%2F%20Assume%20that%20it's%20already%20something%20that%20can%20be%20coerced.%0A%20%20%20%20%20%20return%20new%20Uint8Array(input)%3B%0A%20%20%20%20%7D%0A%20%20%7D%0A%0A%20%20private%20boyerMoore(patternBuffer)%3A%20%5B((txtBuffer%3A%20needleType%2C%20start%3F%3A%20number%2C%20end%3F%3A%20number)%20%3D%3E%20number%20)%2C%20number%5D%20%7B%0A%20%20%20%20const%20pattern%20%3D%20this.asUint8Array(patternBuffer)%3B%0A%20%20%20%20const%20M%3A%20number%20%3D%20pattern.length%3B%0A%20%20%20%20if%20(M%20%3D%3D%3D%200)%20%7B%0A%20%20%20%20%20%20throw%20new%20TypeError('patternBuffer%20must%20be%20at%20least%201%20byte%20long')%3B%0A%20%20%20%20%7D%0A%20%20%20%20%2F%2F%20radix%0A%20%20%20%20const%20radix%3A%20number%20%3D%20256%3B%0A%20%20%20%20const%20rightmost_positions%3A%20Int32Array%20%3D%20new%20Int32Array(radix)%3B%0A%20%20%20%20%2F%2F%20position%20of%20the%20rightmost%20occurrence%20of%20the%20byte%20c%20in%20the%20pattern%0A%20%20%20%20for%20(let%20c%3A%20number%20%3D%200%3B%20c%20%3C%20radix%3B%20c%2B%2B)%20%7B%0A%20%20%20%20%20%20%2F%2F%20-1%20for%20bytes%20not%20in%20pattern%0A%20%20%20%20%20%20rightmost_positions%5Bc%5D%20%3D%20-1%3B%0A%20%20%20%20%7D%0A%20%20%20%20for%20(let%20j%20%3D%200%3B%20j%20%3C%20M%3B%20j%2B%2B)%20%7B%0A%20%20%20%20%20%20%2F%2F%20rightmost%20position%20for%20bytes%20in%20pattern%0A%20%20%20%20%20%20rightmost_positions%5Bpattern%5Bj%5D%5D%20%3D%20j%3B%0A%20%20%20%20%7D%0A%0A%20%20%20%20function%20boyerMooreSearch(txtBuffer%3A%20needleType%2C%20start%3A%20number%20%3D%200%2C%20end%3F%3A%20number)%3A%20number%20%7B%0A%20%20%20%20%20%20%2F%2F%20Return%20offset%20of%20first%20match%2C%20-1%20if%20no%20match.%0A%20%20%20%20%20%20const%20text%20%3D%20this.asUint8Array(txtBuffer)%3B%0A%0A%20%20%20%20%20%20if%20(end%20%3D%3D%3D%20undefined)%20%7B%0A%20%20%20%20%20%20%20%20end%20%3D%20text.length%3B%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20const%20pat%20%3D%20pattern%3B%0A%20%20%20%20%20%20const%20right%20%3D%20rightmost_positions%3B%0A%20%20%20%20%20%20const%20lastIndex%20%3D%20end%20-%20pat.length%3B%0A%20%20%20%20%20%20const%20lastPatIndex%20%3D%20pat.length%20-%201%3B%0A%20%20%20%20%20%20let%20skip%3B%0A%20%20%20%20%20%20for%20(let%20i%20%3D%20start%3B%20i%20%3C%3D%20lastIndex%3B%20i%20%2B%3D%20skip)%20%7B%0A%20%20%20%20%20%20%20%20skip%20%3D%200%3B%0A%20%20%20%20%20%20%20%20for%20(let%20j%20%3D%20lastPatIndex%3B%20j%20%3E%3D%200%3B%20j--)%20%7B%0A%20%20%20%20%20%20%20%20%20%20const%20char%3A%20number%20%3D%20text%5Bi%20%2B%20j%5D%3B%0A%20%20%20%20%20%20%20%20%20%20if%20(pat%5Bj%5D%20!%3D%3D%20char)%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20skip%20%3D%20Math.max(1%2C%20j%20-%20right%5Bchar%5D)%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20break%3B%0A%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20if%20(skip%20%3D%3D%3D%200)%20%7B%0A%20%20%20%20%20%20%20%20%20%20return%20i%3B%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20return%20-1%3B%0A%20%20%20%20%7D%0A%0A%20%20%20%20return%20%5BboyerMooreSearch%2C%20pattern.byteLength%5D%3B%0A%20%20%7D%0A%7D%0A%0A%0A%2F%2F%20Simple%20usage%20example%0Aconst%20boyerMoore%20%3D%20new%20BoyerMoore(new%20Uint8Array(%5B0x12%2C%200x13%2C%200x14%5D))%3B%0Aconst%20indexes%20%3D%20boyerMoore.findIndexes(new%20Uint8Array(%5B0x01%2C%200x02%2C%200x12%2C%200x13%2C%200x14%5D))%3B%0Aconsole.log(indexes)%3B%0A%0A\" rel=\"nofollow noreferrer\">Click here for a cleaner typescript implementation</a></p>\n\n<pre><code>function asUint8Array(input) {\n if (input instanceof Uint8Array) {\n return input;\n } else if (typeof(input) === 'string') {\n // This naive transform only supports ASCII patterns. UTF-8 support\n // not necessary for the intended use case here.\n var arr = new Uint8Array(input.length);\n for (var i = 0; i < input.length; i++) {\n var c = input.charCodeAt(i);\n if (c > 127) {\n throw new TypeError(\"Only ASCII patterns are supported\");\n }\n arr[i] = c;\n }\n return arr;\n } else {\n // Assume that it's already something that can be coerced.\n return new Uint8Array(input);\n }\n}\nfunction boyerMoore(patternBuffer) {\n // Implementation of Boyer-Moore substring search ported from page 772 of\n // Algorithms Fourth Edition (Sedgewick, Wayne)\n // http://algs4.cs.princeton.edu/53substring/BoyerMoore.java.html\n /*\n USAGE:\n // needle should be ASCII string, ArrayBuffer, or Uint8Array\n // haystack should be an ArrayBuffer or Uint8Array\n var search = boyerMoore(needle);\n var skip = search.byteLength;\n var indexes = [];\n for (var i = search(haystack); i !== -1; i = search(haystack, i + skip)) {\n indexes.push(i);\n }\n */\n var pattern = asUint8Array(patternBuffer);\n var M = pattern.length;\n if (M === 0) {\n throw new TypeError(\"patternBuffer must be at least 1 byte long\");\n }\n // radix\n var R = 256;\n var rightmost_positions = new Int32Array(R);\n // position of the rightmost occurrence of the byte c in the pattern\n for (var c = 0; c < R; c++) {\n // -1 for bytes not in pattern\n rightmost_positions[c] = -1;\n }\n for (var j = 0; j < M; j++) {\n // rightmost position for bytes in pattern\n rightmost_positions[pattern[j]] = j;\n }\n function boyerMooreSearch(txtBuffer, start, end) {\n // Return offset of first match, -1 if no match.\n var txt = asUint8Array(txtBuffer);\n if (start === undefined) start = 0;\n if (end === undefined) end = txt.length;\n var pat = pattern;\n var right = rightmost_positions;\n var lastIndex = end - pat.length;\n var lastPatIndex = pat.length - 1;\n var skip;\n for (var i = start; i <= lastIndex; i += skip) {\n skip = 0;\n for (var j = lastPatIndex; j >= 0; j--) {\n var c = txt[i + j];\n if (pat[j] !== c) {\n skip = Math.max(1, j - right[c]);\n break;\n }\n }\n if (skip === 0) {\n return i;\n }\n }\n return -1;\n };\n boyerMooreSearch.byteLength = pattern.byteLength;\n return boyerMooreSearch;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-15T19:45:20.047",
"Id": "192136",
"ParentId": "20136",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-03T23:21:36.603",
"Id": "20136",
"Score": "1",
"Tags": [
"javascript",
"optimization",
"node.js"
],
"Title": "Uint8Array indexOf method that allows to search for byte sequences"
}
|
20136
|
<p>I have following in Windows Forms .NET 3.5</p>
<p>It works fine for csv with records less than 10,000 but is slower for records above 30,000.
Input csv file can can any records between 1 - 1,00,000 records </p>
<p>Code currently used :</p>
<pre><code>/// <summary>
/// This will import file to the collection object
/// </summary>
private bool ImportFile()
{
try
{
String fName;
String textLine = string.Empty;
String[] splitLine;
// clear the grid view
accountsDataGridView.Rows.Clear();
fName = openFileDialog1.FileName;
if (System.IO.File.Exists(fName))
{
System.IO.StreamReader objReader = new System.IO.StreamReader(fName);
do
{
textLine = objReader.ReadLine();
if (textLine != "")
{
splitLine = textLine.Split(',');
if (splitLine[0] != "" || splitLine[1] != "")
{
accountsDataGridView.Rows.Add(splitLine);
}
}
} while (objReader.Peek() != -1);
}
return true;
}
catch (Exception ex)
{
if (ex.Message.Contains("The process cannot access the file"))
{
MessageBox.Show("The file you are importing is open.", "Import Account", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
MessageBox.Show(ex.Message);
}
return false;
}
}
</code></pre>
<p>Sample Input file :
<br />
18906,Y<br />
18908,Y<br />
18909,Y<br />
18910,Y<br />
18912,N<br />
18913,N<br /></p>
<p>Need some advice on optimizing this code for fast reads & view in grid.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T12:48:51.700",
"Id": "32199",
"Score": "0",
"body": "Do you have a multi core machine? Then you can parse in parallel. Does the CSV files contain redundant data? In this case it does make sense to intern strings to reduce memory load. The main issue why parsing does become slower is that you need more memory to hold the data."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T14:02:07.073",
"Id": "32203",
"Score": "8",
"body": "**Never** rely on `Exception.Message` to determine the type of an exception! Catch the right one instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T15:51:28.453",
"Id": "32209",
"Score": "0",
"body": "I haven't used it, but there's a CSV parser in the VB.NET runtime. It is `Microsoft.VisualBasic.FileIO.TextFieldParser`. It is probably not faster but will cater for quotes, etc."
}
] |
[
{
"body": "<p>There isn't much to optimize in regards to speed, but following is much more readable. If it is too slow, it probably isn't the method <em>reading</em> the file, but your WinForm that needs to display >30k records.</p>\n\n<pre><code> accountsDataGridView.Rows.Clear();\n using (FileStream file = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096))\n using (StreamReader reader = new StreamReader(file))\n {\n while (!reader.EndOfStream)\n {\n var fields = reader.ReadLine().Split(',');\n if (fields.Length == 2 && (fields[0] != \"\" || fields[1] != \"\"))\n {\n accountsDataGridView.Rows.Add(fields);\n }\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T12:48:31.007",
"Id": "20146",
"ParentId": "20145",
"Score": "1"
}
},
{
"body": "<p>What's the use of presenting even 5,000 records to the user? Do you expect a user to scroll to row 4711, look at \"18912,N\", and say \"Strange, why wasn't there a '12345,N' in row 1234?\", or \"Interesting, now let's see where the corresponding '54321,X\" is to be found!\"?</p>\n\n<p>Your GUI should help the user to specify the comparatively small set(s) of records pertinent to his current problem/question; even if working with the data means \"check every item in turn\", it would be more human to present the records in small batches.</p>\n\n<p>All this points to using your file as a database table bound to the controls of your GUI; then the problem of \"reading a .csv fast\" completely vanishes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T22:02:06.177",
"Id": "32232",
"Score": "0",
"body": "True but it is still a good idea to read the stuff at once at a decent speed. When reading a CSV file like this it you will get around 20MB/s which is far less than any hard disc can deliver. If you read it a second time you get it from the OS cache at ca. 500MB/s but you parse it still at 20MB/s."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T13:41:22.567",
"Id": "20147",
"ParentId": "20145",
"Score": "8"
}
},
{
"body": "<p>A few thoughts that could improve speed up what you're doing:</p>\n\n<ol>\n<li><p>Use parallel processing to process multiple lines simultaneously. If you've got a multi-core machine, this would go some way to offloading the task of manipulating strings and adding them to a control. The <a href=\"http://msdn.microsoft.com/en-us/library/dd997371.aspx\" rel=\"nofollow\"><code>BlockingCollection<T></code></a> would be well-suited to this task.</p></li>\n<li><p>Buffer your read of the file using a <code>FileStream</code>. The IO itself is quite an overhead, so doing fewer-but-bigger reads could speed up the process considerably.</p></li>\n<li><p>Don't actually read all the rows into the grid. Set up pagination so that you only load a portion of it until the user requests the next set of data. It's very unlikely a human will actually read 30,000 rows.</p></li>\n</ol>\n\n<p>Here's an example of how to use the <code>FileStream</code> class and to handle the processing of the lines as an asynchronous process: </p>\n\n<pre><code>// Internally the collection uses a ConcurrentQueue<T> by default.\nvar queue = new BlockingCollection<string>();\n\n// Set up an asynchronous operation to process the queue.\nTask.StartNew(() => \n{\n foreach(var line in queue.GetConsumingEnumerable())\n {\n if (textLine != \"\")\n {\n splitLine = textLine.Split(',');\n if (splitLine[0] != \"\" || splitLine[1] != \"\")\n {\n accountsDataGridView.Invoke( \n () => accountsDataGridView.Rows.Add(splitLine);\n }\n }\n }\n});\n\n/* You should tweak the buffersize to get the balance you want between memory use\n and speed of execution. */\nvar bufferSize = 8192; // 8k is the default size used by `FileStream`.\n\nusing(var fs = \n new FileStream(\n openFileDialog1.FileName,\n FileMode.Open, // Open an existing file (don't create it)\n FileAccess.Read, // Open the file to read it\n FileShare.Read, // Allow sharing with other readers\n bufferSize))\n{\n using(var reader = new StreamReader(fs))\n {\n while(reader.Peek() >= 0)\n {\n queue.Add(reader.ReadLine());\n }\n\n // Signal that there are no more items to be added.\n queue.CompleteAdding();\n }\n}\n</code></pre>\n\n<p>As an aside, you probably want to perform the read of the CSV on a background thread, so the operation doesn't block the UI.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T22:09:08.357",
"Id": "32233",
"Score": "0",
"body": "It is a very bad idea to call invoke for every parsed line. The overhead for this is far higher than to read and parse a single line. You have exchanged one bottleneck with another one. If have tried a similar thing to use one reader thread and to have n parsing threads. It turned out that the single threaded solution did outperform it still by 30%. The reason was (I think) that you do loose cache locality if one thread reads stuff and n other threads try to read other stuff. To prevent too many UI updates read here: http://geekswithblogs.net/akraus1/archive/2011/12/02/147923.aspx"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T13:46:06.600",
"Id": "20148",
"ParentId": "20145",
"Score": "4"
}
},
{
"body": "<p>We use the <a href=\"http://www.codeproject.com/Articles/11698/A-Portable-and-Efficient-Generic-Parser-for-Flat-F\" rel=\"nofollow\"><code>GenericParser</code> library</a>. It's pretty easy to use, too. </p>\n\n<p>Your code would look something like this:</p>\n\n<pre><code>GenericParserAdapter parser = new GenericParserAdapter(fName);\n\nparser.ColumnDelimiter = ',';\nparser.FirstRowSetsExpectedColumnCount = true;\nparser.FirstRowHasHeader = false;\n\naccountsDataGridView.DataSource = parser.GetDataTable();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T16:28:34.807",
"Id": "20153",
"ParentId": "20145",
"Score": "2"
}
},
{
"body": "<p>I am assuming it is OK to load everything into memory all at once, since you are doing that with the grid anyways. The fastest simple option I see is loading the data into a data object and binding it to the grid, rather than adding rows one at a time.</p>\n\n<p>I tossed together a CSV file with 100,000 rows, all consisting of the following data:</p>\n\n<pre><code>\"a\", \"a\", \"a\", \"a\", 1234, 1234, 1234, 1234\n</code></pre>\n\n<p>(It was thrown together quick just for quick turn-around sake.)</p>\n\n<p>I then provided 3 ways of loading. One loads the data much like you did above:</p>\n\n<pre><code> private void LoadDirect (string fName)\n {\n String textLine = string.Empty;\n String[] splitLine;\n\n // clear the grid view\n\n CSVGrid.SuspendLayout ();\n\n CSVGrid.Rows.Clear ();\n\n if (System.IO.File.Exists (fName))\n {\n System.IO.StreamReader objReader = new System.IO.StreamReader (fName);\n\n do\n {\n textLine = objReader.ReadLine ();\n if (textLine != string.Empty)\n {\n splitLine = textLine.Split (',');\n if (splitLine [0] != string.Empty || splitLine [1] != string.Empty)\n {\n CSVGrid.Rows.Add (splitLine);\n }\n }\n } while (objReader.Peek () != -1);\n }\n\n CSVGrid.ResumeLayout ();\n }\n</code></pre>\n\n<p>That consistently took around 21 seconds to populate the grid.</p>\n\n<p>To eliminate the possibility that the largest slowdown factor was loading from the file one line at a time, I produced a similar method which loads the entire file up front, then used a StringReader in place of the StreamReader inside the loop:</p>\n\n<pre><code>private void LoadBuffered (string fName)\n{\n String textLine = string.Empty;\n String[] splitLine;\n\n CSVGrid.SuspendLayout ();\n\n // clear the grid view\n CSVGrid.Rows.Clear ();\n\n if (System.IO.File.Exists (fName))\n {\n System.IO.StreamReader objReader = new System.IO.StreamReader (fName);\n\n var contents = objReader.ReadToEnd ();\n var strReader = new System.IO.StringReader (contents);\n\n do\n {\n textLine = strReader.ReadLine ();\n if (textLine != string.Empty)\n {\n splitLine = textLine.Split (',');\n if (splitLine [0] != string.Empty || splitLine [1] != string.Empty)\n {\n CSVGrid.Rows.Add (splitLine);\n }\n }\n } while (strReader.Peek () != -1);\n }\n CSVGrid.ResumeLayout ();\n }\n</code></pre>\n\n<p>Once again, this took around 21 seconds consistently.</p>\n\n<p>Finally, I created a simplistic variant which loads all the data up front, places it into a System.Data.DataTable in the loop, then binds the table to the grid upon completion:</p>\n\n<pre><code> private void LoadBound (string fName)\n {\n String textLine = string.Empty;\n String[] splitLine;\n\n // clear the grid view\n\n var data = new DataTable ();\n data.Columns.AddRange (new []\n {\n new DataColumn (\"Column1\"),\n new DataColumn (\"Column2\"),\n new DataColumn (\"Column3\"),\n new DataColumn (\"Column4\"),\n new DataColumn (\"Column5\",typeof (int)),\n new DataColumn (\"Column6\",typeof (int)),\n new DataColumn (\"Column7\",typeof (int)),\n new DataColumn (\"Column8\",typeof (int)),\n });\n\n data.Rows.Clear ();\n\n if (System.IO.File.Exists (fName))\n {\n System.IO.StreamReader objReader = new System.IO.StreamReader (fName);\n\n var contents = objReader.ReadToEnd ();\n\n var strReader = new System.IO.StringReader (contents);\n\n do\n {\n textLine = strReader.ReadLine ();\n if (textLine != string.Empty)\n {\n splitLine = textLine.Split (',');\n if (splitLine [0] != string.Empty || splitLine [1] != string.Empty)\n {\n data.Rows.Add (splitLine);\n }\n }\n } while (strReader.Peek () != -1);\n }\n\n CSVGrid.DataSource = data;\n }\n</code></pre>\n\n<p>This variant consistently takes around 0.8 seconds. Perhaps unsurprisingly, the real killer was adding items to the grid row-by-row.</p>\n\n<p>It has the added benefit of isolating your file reading, parsing, and grid population operations into separate sections of code which could be split into methods/objects.</p>\n\n<p>Of course, rather than using a System.Data.DataTable, I would prefer to use a well-structured object. The DataTable was merely used to build a quick example.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T00:26:31.750",
"Id": "32234",
"Score": "1",
"body": "Nice analysis. I think you have nailed his perf issue. It should be forbidden to ask performance questions without showing a profiler screenshot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T19:16:27.510",
"Id": "20162",
"ParentId": "20145",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T12:34:29.223",
"Id": "20145",
"Score": "6",
"Tags": [
"c#",
".net",
"winforms",
"csv"
],
"Title": "Faster way of reading csv to grid"
}
|
20145
|
<p>The following logic:</p>
<p>Iterate over the URLs array and If the HTTP request with the given URL does not timeout, continue. If the URL times out, remove it from the array and continue with the next one until the array is exhausted.</p>
<p>Has been implemented in the following way:</p>
<pre><code>@urls.delete_if do |url|
begin
doc = perform_request(some_params)
break
rescue TimeoutError
Rails.logger.warn("URL #{url} times out, will be removed from list")
true
end
end
</code></pre>
<p>Anyone for a cleaner solution? Basically, I want to iterate over an array and remove elements from it if there is a timeout, but if the URL works loop should end and app should continue processing.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T15:23:43.613",
"Id": "32206",
"Score": "0",
"body": "Specifically, hate the break in there - maybe someone can propose a cleaner solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T15:33:12.537",
"Id": "32207",
"Score": "0",
"body": "Btw \"true\" in the rescue can be removed, not needed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T17:57:56.857",
"Id": "32217",
"Score": "0",
"body": "if not needed just edit the question! I have a doubt, why do you want to modify inplace @urls? wouldn't do a functional solution?"
}
] |
[
{
"body": "<p>I'd take a functional approach (no in-place updates):</p>\n\n<pre><code>url, doc = @urls.map_detect do |url|\n begin\n [url, perform_request(some_params)]\n rescue TimeoutError\n Rails.logger.warn(\"URL #{url} timed out\")\n false\n end\nend\n</code></pre>\n\n<p>This snippet uses the custom abstraction <a href=\"https://code.google.com/p/tokland/wiki/RubyIdioms#Enumerable#map_detect\" rel=\"nofollow\">Enumerable#map_detect</a> (see also <a href=\"http://rubydoc.info/github/rubyworks/facets/master/Enumerable#find_yield-instance_method\" rel=\"nofollow\">Facets</a>)</p>\n\n<p>You can then use <code>url</code> to update <code>@urls</code>, but it's better not to mix the algorithm (even if it's so simple) with the updates required by the app. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T18:18:37.033",
"Id": "20158",
"ParentId": "20151",
"Score": "0"
}
},
{
"body": "<p>You may use <a href=\"http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-drop_while\" rel=\"nofollow\">drop_while</a> to get rid of iterative operator <code>break</code>:</p>\n\n<pre><code>@urls = @urls.drop_while do |url|\n begin\n doc = perform_request(some_params)\n false\n rescue TimeoutError\n Rails.logger.warn(\"URL #{url} times out, will be removed from list\")\n true\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T21:23:57.593",
"Id": "32230",
"Score": "0",
"body": "the problem is `doc` won't be visible outside the block's scope."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T20:01:49.943",
"Id": "20165",
"ParentId": "20151",
"Score": "0"
}
},
{
"body": "<p>note : your <code>break</code> is useless, because if the block returns a falsey value, the url is kept.</p>\n\n<p>Maybe it can just be a bit more expressive ?</p>\n\n<pre><code>def timeouts?( url )\n perform_request( url ) && false \nrescue TimeoutError\n true\nend\n\n@urls.delete_if {|url| timeouts?( url ) }\n</code></pre>\n\n<p>You could even make <code>timeouts?</code> a method on your <code>@urls</code> objects, for extra readability : </p>\n\n<pre><code>@urls.delete_if( &:timeouts? )\n</code></pre>\n\n<p>if you want to keep @tokland's functionnal approach, just use :</p>\n\n<pre><code>@kept_urls = @urls.reject{|url| timeouts?( url ) }\n</code></pre>\n\n<p>however, it would not be fully \"functionnal\", because <code>timeouts</code> may not return the same results with the same arguments, depending on the execution environment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-26T10:03:01.217",
"Id": "462698",
"Score": "0",
"body": "Maybe calling the function `timesout?` instead of `timeouts?` would semantically be better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-06T13:23:00.373",
"Id": "27087",
"ParentId": "20151",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T15:23:14.970",
"Id": "20151",
"Score": "3",
"Tags": [
"ruby"
],
"Title": "iterate over an array and delete elements conditionally"
}
|
20151
|
<p>I have this problem where I have to find the shortest path in an NxM grid from point A (always top left) to point B (always bottom right) by only moving right or down. Sounds easy, eh? Well here's the catch: I can only move the number shown on the tile I'm sitting on at the moment. Let me illustrate:</p>
<pre><code>2 5 1 2
9 2 5 3
3 3 1 1
4 8 2 7
</code></pre>
<p>In this 4x4 grid the shortest path would take 3 steps, walking from top left 2 nodes down to 3, and from there 3 nodes right to 1, and then 1 node down to the goal.</p>
<pre><code>[2] 5 1 2
9 2 5 3
[3] 3 1 [1]
4 8 2 [7]
</code></pre>
<p>If not for the shortest path, I could also be taking this route:</p>
<pre><code>[2] 5 [1][2]
9 2 5 3
3 3 1 [1]
4 8 2 [7]
</code></pre>
<p>That would unfortunately take a <strong>whopping 4 steps</strong>, and thus, is not in my interest.
That should clear things out a bit. <strong>Now about the input.</strong></p>
<hr>
<p>The user inputs the grid as follows:</p>
<pre><code>5 4 // height and width
2 5 2 2 //
2 2 7 3 // the
3 1 2 2 // grid
4 8 2 7 //
1 1 1 1 //
</code></pre>
<hr>
<p>So what have I done? I figured the best way around this (to begin with) would be BFS. Voila, correct answer on every input. Hurray, it's too freakin' slow.</p>
<p>Anyway here's the code at the moment:</p>
<pre><code>#include <iostream>
#include <vector>
struct Point {
int y, x, depth;
Point(int yPos = 0, int xPos = 0, int dDepth = 0) : y(yPos), x(xPos), depth(dDepth) { }
};
struct grid_t {
int height, width;
std::vector< std::vector<int> > tiles;
grid_t() // construct the grid
{
std::cin >> height >> width; // input grid height & width
tiles.resize(height, std::vector<int>(width, 0)); // initialize grid tiles
for(int i = 0; i < height; i++) //
for(int j = 0; j < width; j++) // input each tile one at a time
std::cin >> tiles[i][j]; // by looping through the grid
}
};
int go_find_it(grid_t &grid)
{
std::vector<Point> openList, closedList;
openList.push_back(Point(0, 0)); // (0, 0) is the first point we want to consult, of course
do
{
closedList.push_back(openList[0]); // the tile we are at is good and checked. mark it so.
openList.erase(openList.begin()); // we don't need this guy no more
int y = closedList.back().y; // now we'll actually move to the new point
int x = closedList.back().x; //
int depth = closedList.back().depth; // the new depth
if(y == grid.height-1 && x == grid.width-1) return depth; // the first path is the shortest one. return it
int jump = grid.tiles[y][x]; // 'jump' is the number shown on the tile we're standing on.
grid.tiles[y][x] = 0; // mark the tile visited
if(y + jump < grid.height && grid.tiles[y+jump][x] != 0) // if we're not going out of bounds or on a visited tile
{
openList.push_back(Point(y+jump, x, depth+1)); // push in the new promising point along with the new depth
}
if(x + jump < grid.width && grid.tiles[y][x+jump] != 0) // if we're not going out of bounds or on a visited tile
{
openList.push_back(Point(y, x+jump, depth+1)); // push in the new promising point along with the new depth
}
}
while(openList.size() > 0); // when there are no new tiles to check, break out and return false
return 0;
}
int main()
{
grid_t grid; // initialize grid
int min_path = go_find_it(grid); // BFS
std::cout << min_path << std::endl; // print the result
//system("pause");
return 0;
}
</code></pre>
<p>So what I want is some optimization hints, because I suck at it (and am relatively new to C++). Basically jumped into it a month ago with only as much knowledge from PHP and javascript). Should I make it A* instead of BFS? If I did that, how would I calculate the heuristic?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T16:34:52.920",
"Id": "32211",
"Score": "0",
"body": "always right or down, always the total amount the case value is at? so it should be *very* fast : on each step, try both directions: try_right (goes N right, and also store \"R\" in the current result string), and try_down (goes N down, and stores \"D\" in the result string). And if you reach exatcly the bottom-right end: keep_result (keeps the current result_string if it is shorter than the previously stored). Otherwise (we go > down or >right than bottom left?) discard current result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T16:37:57.613",
"Id": "32212",
"Score": "0",
"body": "tricky part in my solution is to keep track of progress, to explore it all. Recursivity should help (beware you have separate current strings for each path)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T16:41:40.293",
"Id": "32213",
"Score": "1",
"body": "in your case example, it is easy to see there are only 2 routes. On a much bigger case, it could grow quite a lot, but still: on an X/Y tile, you can only progress toward the bottom right at least 1 step (right, or down) : you can't have more than (max(heigth,width)) steps overall in your final solution. If (worst case) all solutinos are at least that long (ex: all tiles contain \"1\"), it's trivial to compute the worst possible number of steps your algorithm will have to test to cover all possibilities"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T17:29:33.607",
"Id": "32216",
"Score": "0",
"body": "If this is a programming contest question, which it sounds like, what are the upper bounds for **N** and **M**?\n\nFor a 100000 X 100000 grid of all 1s will take a lot of time with a naive solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T18:13:38.393",
"Id": "32219",
"Score": "0",
"body": "1000x1000 is the upper bound"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T01:57:10.987",
"Id": "32237",
"Score": "0",
"body": "Do you happen to have a sample of one of the slow cases? There's a few optimizations that jump out at me, and I'm curious to test them."
}
] |
[
{
"body": "<p>I think BFS is your algorithm, but I do have some cleanups for you. The reason A* won't work is because your estimation of how much farther you have to go (you could do a simple grid distance from where you are to the end point, also considering the jump value where you are sitting) could be wrong based on future jumps, and in your case, estimations are not acceptable. (Note: in some cases, for example if this was an AI in a game, estimation can be acceptable if performance is greatly improved)</p>\n\n<ol>\n<li><p>Use a queue instead of a vector for openList. Every erase on the first item in a vector means you have to copy all the items to new memory positions!!! BFS algorithm and std::queue are a married pair because your push and pop are constant time, and you won't accidentally push or pop at the wrong end.</p></li>\n<li><p>You are keeping a list of visited points, but you aren't using this list, and you aren't using it because you don't need it. You can't go backwards in your path toward the end, so you don't have to keep track of where you have been.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-15T12:43:14.807",
"Id": "396584",
"Score": "0",
"body": "Actually, it *is* interesting whether a point was already visited: If so, any *additional* route leading to it is uninteresting, as it cannot be *shorter*. Just zeroing the distance one can travel from there is better than making a separate list though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-01-04T16:53:44.183",
"Id": "20154",
"ParentId": "20152",
"Score": "5"
}
},
{
"body": "<ol>\n<li>profile it!</li>\n<li><p>it's a good choice to use a <code>std::deque</code> (which is the default container used by <code>std::queue</code>) instead of a <code>std::vector</code>. The potentially expensive operations (again, you should profile to confirm this) are <code>push_back()</code> and <code>pop_front()</code> (<code>back()</code> is likely to be constant time for almost any container)</p>\n\n<ul>\n<li><code>std::vector</code> has amortized constant time <code>push_back</code>, but <code>push_front</code> is linear time\n<ul>\n<li>NB. this is because it has to move each of <em>n-1</em> items forward one space, but it does <em>not</em> have to reallocate</li>\n</ul></li>\n<li><code>std::deque</code> has amortized constant time <code>push_back</code> <em>and</em> <code>push_front</code>, so is probably faster</li>\n</ul>\n\n<p>I'm going to say it again though - you should profile both choices and verify this. Even if the asymptotic complexity is better for <code>std::deque</code>, the constant overhead is greater, and that could dominate depending on your data size</p></li>\n<li><p>do you actually use <code>closedList</code> for anything? It looks like you only ever use the back, in which case you could replace it with a single <code>Point</code></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T17:19:27.717",
"Id": "20156",
"ParentId": "20152",
"Score": "4"
}
},
{
"body": "<ul>\n<li>Most importantly algorithm: Since the shortest path from top-left to any point on the grid is dependent on the points above and to the left of that point, <strong>dynamic programming</strong> can be used to calculate the path. It's O(MN) so it should give an answer in reasonable time for 1000*1000 grid. space complexity is O(MN) too. memory consumption will be about 2MB.</li>\n<li>Dont do IO in the constructor. </li>\n</ul>\n\n<p><strike>\n - Use plain arrays when the size is known. as in this case. use new[] operator. std::vector does bounds checking. arrays are faster.</strike></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T20:42:47.140",
"Id": "32228",
"Score": "1",
"body": "`\"std::vector does bounds checking\"` `at` does bounds checking; `operator[]` does not."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T19:07:41.747",
"Id": "20160",
"ParentId": "20152",
"Score": "0"
}
},
{
"body": "<h1><code>struct Point</code></h1>\n\n<p>The constructor could be omitted, with small changes to the calling code:</p>\n\n<pre><code>openList.push_back({0,0,0});\n\n openList.push_back({y+jump, x, depth+1});\n\n openList.push_back({y, x+jump, depth+1});\n</code></pre>\n\n<h1><code>struct grid_t</code></h1>\n\n<p><code>height</code> and <code>width</code> are redundant.</p>\n\n<p>A better structure would use a single vector of <code>height</code> × <code>width</code> elements, to give better locality of reference. Consider providing an <code>operator()(std::size_t x, std::size_t y)</code> to index it.</p>\n\n<p>Instead of reading unconditionally from <code>std::cin</code>, allow user to specify a stream (don't forget <code>explicit</code>!). And throw an exception if reading fails - at present, a partially-read grid will be filled with zeros, without any indication of failure.</p>\n\n<h1><code>go_find_it()</code></h1>\n\n<p>Consider working backwards: from the target point to the starting point. There will be much more opportunity for pruning at each step if we only need to consider the valid jumps that land exactly on the current square.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-15T09:34:57.603",
"Id": "205595",
"ParentId": "20152",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T15:27:15.477",
"Id": "20152",
"Score": "4",
"Tags": [
"c++",
"optimization",
"algorithm",
"pathfinding",
"breadth-first-search"
],
"Title": "Shortest path in a grid between two points"
}
|
20152
|
<p>This is the backend to my jquery.php plugin which handles requests to make function calls and execute PHP code that is sent in various forms. After requests are processed they're sent back to the client side as a JSON object with a type flag set so JavaScript can convert the returned data to the correct type for the user.</p>
<p>So far I have some configuration variables which control the security, allowing us to work in a blacklist or whitelist mode. </p>
<p>I'm looking for constructive advice related to creating code that will allow me to detect things like infinite loops and race conditions as well as anything else I haven't thought of related to security.</p>
<p>To provide a bit of context related to how the backend is used here is a JSON block that is sent to the server as it exists in JavaScript:</p>
<pre><code>var codeBlock = {
opts:
[
{
http: {
method: "GET",
header: "Accept-language: en\r\n" +
"Cookie: foo=bar\r\n"
}
}
],
context:
{
stream_context_create: ['opts']
},
contents:
{
file_get_contents: ['http://www.YourDomain.com/', false, 'context']
},
html:
{
htmlentities: ['contents']
}
}
</code></pre>
<p>In the above code block I'm telling PHP that I want to call <code>file_get_contents</code>. In order to do that I need to define an options array named <code>$opts</code> that is passed to <code>stream_context_create</code>. The returned results from <code>stream_context_create</code> are then to be stored in a variable named <code>$contents</code>. We then store the returned results from <code>file_get_contents</code> into a variable named <code>$contents</code>. Finally we convert the returned data from <code>file_get_contents</code> into the variable <code>$html</code>.</p>
<p>Here's our backend request_handler.php</p>
<pre><code>// Set our error reporting level
error_reporting(0);
/* The blacklist array is used when the SEC_MODE configuration variable is set to 'blacklist'. When configured
* to use the blacklist all functions listed in the array will be disabled.
*/
$blacklist = array(
'`',
'create_function',
'escapeshellcmd',
'exec',
'include',
'include_once',
'passthru',
'pcntl_exec',
'phpinfo',
'popen',
'require',
'require_once',
'shell_exec',
'system'
);
/* The whitelist array is used when the SEC_MODE configuration variable is set to 'whitelist'. When configured
* to use the whitelist only functions listed in the array will be enabled.
*/
$whitelist = array(
// 'strlen', // (e.g. Allowing the strlen function)
// 'highlight_string' // (e.g. Etc...)
);
/* The jquery.php plugin allows for the execution of code provided by the client. This functionality should
* be disabled by default. The 'exec' mode uses the eval() construct which can be very dangerous.
*/
$config = array(
'EXEC' => true,
'SEC_MODE' => 'blacklist',
'LISTS' => array(
'blacklist' => $blacklist,
'whitelist' => $whitelist
)
);
/* The first data we look for from the client is which method request is being made. The method request is one
* of our modes of operations and tells us which "method" to use in our switch statement.
*/
$method_request = $_POST['method'] ? $_POST['method'] : false;
if ( $method_request ) {
switch ( $method_request ) {
// The call "method" handles our requests to use PHP functions.
case 'call' :
// Retrieve the function requested and any arguments to be passed to it
$func_request = $_POST['func'] ? $_POST['func'] : false;
$func_args = $_POST['args'] ? $_POST['args'] : false;
// Based on the security mode we use either our blacklist or whitelist.
switch ( $config['SEC_MODE'] ) {
case 'blacklist' :
if ( function_exists($func_request)
&& !in_array($func_request, $blacklist) ) {
$function = $func_request;
} else {
$function = false;
}
break;
case 'whitelist' :
if ( function_exists($func_request)
&& in_array($func_request, $whitelist) ) {
$function = $func_request;
} else {
$function = false;
}
break;
}
// Convert our parameters string and convert it into an array
$args_arr = json_decode($func_args, false);
// Call the requested function if permitted
if ( $function !== false ) {
$call = $function;
echo parse_type( call_user_func_array($call, $args_arr) );
}
break;
// The exec "method" handles requests to execute PHP code strings
case 'exec' :
if ( $config['EXEC'] === true ) {
// We receive code to be executed by the user
$code_string = $_POST['code'] ? $_POST['code'] : false;
// Prefix our code with return to prevent NULL from being returned.
echo parse_type( eval( $code_string ) );
}
break;
// The block "method" handles requests to execute JSON blocks of PHP code
case 'block' :
// Retrieve our JSON string and convert it to an array
$php_obj = $_POST['pobj'] ? json_decode( $_POST['pobj'] ) : false;
// Pass our JSON decoded PHP objects array to our execution handler
print parse_type( parse_php_object( $php_obj, $config ) );
break;
}
}
/**
* Converts PHP objects to arrays by typecasting.
* @param {object} Object A self referencing PHP object.
*/
function object_to_array( &$object ) {
if ( is_object( $object ) ) {
(Array)$object;
}
}
/**
* Iterates over an array containing PHP and handles calls to enabled functions and executes them.
* @param {phpObj} array A JSON decoded array of representational PHP.
* @return {*} Will return the results of the last function call passed in through phpObj.
*/
function parse_php_object( $arr, $config ) {
// We define a pointer array that contains reference names to parameter placeholders
// that will be replaced by real data.
$pointers = array();
foreach ( $arr as $k => $v ) {
// Create variable definition with our first level array keys
${$k} = $v;
// Populate our pointers index
$pointers[$k] = $k;
// When a value is an object we attempt to call functions defined within
if ( is_object( ${$k} ) ) {
// Convert our function object to an array
$funcArr = (Array)${$k};
// Use the first key of the function array as our function name to call
$func_name = array_keys($funcArr);
$func_name = $func_name[0];
// Get the array of arguments to parse to our arguments array
$func_args = $funcArr[$func_name];
// Create an array to store the arguments to pass to our function call
$args_arr = array();
// Now we iterate over our function arguments looking for reference strings
foreach ( $func_args as $arg ) {
// We compare against the keys in our pointers index which was created above
if ( array_key_exists( $arg, $pointers ) ) {
// This is now a reference to ${$k}, the originally defined definition, the returned
// result of the last sucessful function call
$p = ${$arg};
// We push our arguments onto the args_array which will be passed to our function call
array_push( $args_arr, $p );
} else {
// We push our arguments onto the args_array which will be passed to our function call
array_push( $args_arr, $arg );
}
}
// Based on the security mode selected, use either our blacklist or whitelist.
switch ( $config['SEC_MODE'] ) {
case 'blacklist' :
if ( function_exists( $func_name )
&& !in_array( $func_name, $config['LISTS']['blacklist'] ) ) {
$function_allowed = true;
} else {
$function_allowed = false;
}
break;
case 'whitelist' :
if ( function_exists( $func_name )
&& in_array( $func_name, $config['LISTS']['whitelist'] ) ) {
$function_allowed = true;
} else {
$function_allowed = false;
}
break;
}
// Call the requested function if permitted
if ( $function_allowed === true ) {
// Reassign our variable the returned value of a function call so that further function calls can
// search for the existence of pointers and then use the updated variable definitions. This logic
// takes advantage of the procedural nature of PHP and the order of the sub-blocks in the php object.
${$k} = call_user_func_array( $func_name, $args_arr );
} else {
return ("Function you requested $func_name has been disabled by backend configuration.");
}
}
// When we're not an object we're something else like an array, string, int, etc. If we're an array we need
// to recursively iterate over ourselves to convert any objects into arrays.
else {
if ( is_array( ${$k} ) ) {
array_walk_recursive( ${$k}, 'object_to_array' );
}
}
}
// Return the returned result from our final function call
return ${$k};
}
/**
* Detects the type of a returned result and encodes a type identifier along with the data into a JSON object.
* @param {*} data Result data from a PHP function call.
* @return {Object} JSON encoded result data with type field.
*/
function parse_type( $data ) {
$results = array(
'type' => '',
'data' => NULL
);
switch ( true ) {
case is_int( $data ) :
$type = 'int';
break;
case is_float( $data ) :
$type = 'float';
break;
case is_string( $data ) :
$type = 'string';
break;
case is_object( $data ) :
$type = 'object';
break;
case is_array( $data ) :
$type = 'array';
break;
case is_bool( $data ) :
$type = 'bool';
break;
case is_null( $data ) :
$type = 'null';
break;
default :
$type = 'default';
}
$results['type'] = $type;
$results['data'] = $data;
return json_encode( $results );
}
</code></pre>
|
[] |
[
{
"body": "<p>I can't really help you with your specific questions, but I do have some suggestions.</p>\n\n<p>The first, and most crucial, bit of advice, especially if you are worried about security, is not to turn off your error reporting. Instead you should turn it on all the way. While developing it is essential to know where your errors are and to fix them. This will help fill in those security holes as well as make your application more efficient. After development is done you still do not turn off error reporting, you hide it. Log those errors, that way if anything happens that shouldn't you will be able to recreate the scenario with your logs and remove the problems.</p>\n\n<p>Now, I believe it was in version 5.3 that PHP began allowing you to use short ternary. So if your version is 5.3 or higher you can shorten that ternary like so:</p>\n\n<pre><code>$method_request = $_POST[ 'method' ] ?: FALSE;\n</code></pre>\n\n<p>However, this really isn't all that helpful here because you have not verified that that element exists. You are relying on your error reporting level to ignore the errors this is generating. Instead, your ternary should look like this:</p>\n\n<pre><code>$method_request = isset( $_POST[ 'method' ] ? $_POST[ 'method' ] : FALSE;\n</code></pre>\n\n<p>And then you should sanitize it before attempting to use it. Any user information, or possible user information (POST, GET, COOKIES, etc...), should always be sanitized. Of course you could do it all at once with <code>filter_input()</code> if you really wanted. This will make that ternary unnecessary. <code>filter_input()</code> automatically returns a FALSE value if the requested element doesn't exist.</p>\n\n<pre><code>$method_request = filter_input( INPUT_POST, 'method', FILTER_SANITIZE_STRING );\n</code></pre>\n\n<p>Using an if statement and then a switch with the same condition is redundant. Remove the if statement. Since you don't have an else statement to go with it, then there is no need to do anything else. If you decide later to add an else statement, you can just add a FALSE or default case to your switch statement. It will accomplish the same thing.</p>\n\n<pre><code>//if( $method_request ) {//redundant, a switch is essentially an if statement\nswitch( $method_request ) {//the switch holds the item to be compared\n case FALSE ://the case holds the comparison\n //an else clause would go here\n break;\n default :\n //default can also be used for an else clause\n break;\n}\n</code></pre>\n\n<p>Your code is violating a few different principles here. Key among them are: \"Don't Repeat Yourself\" (DRY) and the Arrow Anti-Pattern. The first should be rather self explanatory: Your code shouldn't repeat. Creating additional functions to handle repetition or similar tasks will help out with this. The second principle is about heavy and unnecessary indentation. Your code is quite heavily indented when it needn't be. Removing that if statement I suggested earlier will help with this, as will creating additional functions.</p>\n\n<p>A purely aesthetic change would be to remove all of those internal comments. If your code is self-documenting, your variables clear and understandable, and you are following core principles, then your code should be able to speak for itself. Anything else should be limited to doccomments. All these internal comments do is add clutter.</p>\n\n<p>Variable-variables are usually considered a security risk, but, as it stands, I don't think they can be avoided. I will point out however, that the curly braces around the entity variable is unnecessary. So, unless it helps with clarity, you can remove them. But that's up to you. There really isn't a standard when it comes to variable-variables because they themselves aren't standard.</p>\n\n<pre><code>${$k} = $v;\n//is the same as\n$$k = $v;\n</code></pre>\n\n<p>Your <code>parse_type()</code> function is recreating a function that already exists in PHP. You can just use <code>gettype()</code> to accomplish the same thing.</p>\n\n<pre><code>$type = gettype( $data );\n</code></pre>\n\n<p>Now, all that being said, I don't really understand your need for this convoluted workaround. It seems like you should be able to accomplish the same thing, minus the headache and potential security risks, by simply using pure PHP. For example, you could pass that IP address to your page via an AJAX or normal GET request and have that page get the contents of the address and return it. There doesn't seem to be any need for the abstractness of variable-variables, <code>exec()</code>, and <code>eval()</code>. This just seems overly complicated, but maybe I'm missing something.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T19:48:10.617",
"Id": "20164",
"ParentId": "20155",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T17:19:15.473",
"Id": "20155",
"Score": "1",
"Tags": [
"php",
"jquery"
],
"Title": "jquery.php plugin security optimization (backend)"
}
|
20155
|
<p>I'd like to practice oojs so I've written code:</p>
<pre><code>function Randoms(c, l, h) {
var count = c,
min = l,
max = h,
nums = Array(),
self = this;
//returns random number from given max and min
var getRand = function () {
return Math.floor(Math.random() * (max - min) + min);
};
//checks if given number is unique
var check = function (a) {
for (var i = nums.length - 1; i >= 0; i--) {
if (nums[i] == a) {
return true;
}
}
return false;
};
//makes array with random, unique numbers
this.build = function () {
var r = getRand();
if (nums.length === 0) {
nums.push(r);
} else {
do {
r = getRand();
} while (check(r));
nums.push(r);
}
if (nums.length == count) {
return true;
} else {
this.build();
}
};
//returns array
this.get = function () {
return nums;
};
//simulating constructor
this.build();
}
var a = new Randoms(1, 1, 18);
console.log(a.get());
</code></pre>
<p>The purpose is to get array with random, unique numbers.</p>
<p>What do you think? Is it a good code or does it require modyfications?</p>
|
[] |
[
{
"body": "<ol>\n<li>Your <code>check</code> method is inefficient for large datasets. I'd recommend using a hash instead. This will eliminate the need of iterating over the array every time you want to check if a number is there. </li>\n<li>It is possible for your code to enter an infinite loop if <code>count</code> is greater than <code>max - min</code>. You need to test for this.</li>\n<li>The code can be simplified a bit as well.</li>\n<li>The recursion slows down the generation dramatically. </li>\n</ol>\n\n<p>I've take then liberty of performing some optimizations: <a href=\"http://jsfiddle.net/FMSpG/2/\" rel=\"nofollow\">http://jsfiddle.net/FMSpG/2/</a></p>\n\n<pre><code>function Randoms(c, l, h) {\n var count = c,\n min = l,\n max = h,\n nums = {},\n out = [],\n r, len = 0;\n\n if (max - min < count) count = max - min;\n\n var getRand = function() {\n return Math.floor(Math.random() * (max - min) + min);\n }, check = function(a) {\n return nums[a];\n }, add = function(a) {\n nums[a] = 1;\n out.push(a);\n len++;\n };\n\n (function init() {\n while (len < count){\n if (len == 0) r = getRand();\n else while (check(r = getRand()));\n add(r);\n }\n })();\n\n this.get = function() {\n return out;\n };\n}\n</code></pre>\n\n<p>And here's a jsPerf showing the huge difference in performance for large datasets:</p>\n\n<p><a href=\"http://jsperf.com/unique-randomization\" rel=\"nofollow\">http://jsperf.com/unique-randomization</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T18:42:22.343",
"Id": "20159",
"ParentId": "20157",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "20159",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T18:01:30.670",
"Id": "20157",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Random array of numbers without repeating - oojs practice"
}
|
20157
|
<p>My A* Algorithm in C++ is pretty slow. I'm not sure if it is because of a bad implementation or just because I have way too many <code>Node</code>s (I have a field of 256x256 <code>Node</code>s). It takes the algorithm about 5 seconds to complete.</p>
<p>I'm using a vector for the open and closed List. For the <code>openList</code> I use <code>std::make_heap</code> to sort the <code>Node</code>s.</p>
<pre><code>/************
* Method to calculate the shortes path
*
**/
std::vector<Position*> Pathfinding::getShortestPath(MapField* startField, MapField* targetField) {
PathNode* startNode = new PathNode(startField, argosMap);
openList.push_back(startNode);
push_heap(openList.begin(), openList.end(), ComparePathNodePointer());
while(!(openList.empty())){
make_heap(openList.begin(), openList.end(), ComparePathNodePointer());
PathNode* currentNode = openList.front();
pop_heap(openList.begin(), openList.end(), ComparePathNodePointer());
openList.pop_back();
make_heap(openList.begin(), openList.end(), ComparePathNodePointer());
if(*(currentNode->getMapField()) == *targetField){
Logger::getInstance()->log("Target found");
return buildpath(currentNode);
}
expandNode(currentNode, targetField);
closedList.push_back(currentNode);
}
return buildpath(startNode);
};
/************
* expands a PathNode and adds it to the openList if it meets the conditions of A*
*
**/
void Pathfinding::expandNode(PathNode* currentNode, MapField* targetField) {
std::vector<PathNode*> children = currentNode->getChildren();
std::vector<PathNode*>::iterator child;
for (child = children.begin(); child != children.end(); child++) {
Utils::PointerValuesEquals<PathNode> childToFind = {*(child)};
//check if Node is alreay in closedList
if(std::find_if(closedList.begin(), closedList.end(), childToFind) == closedList.end()) {
double actualCost = (*child)->getCostOfField(currentNode)+currentNode->getActualCost();
//check if Node is already in openList, if so, check if the value is better if it is better, expand the new Node otherwise use the existing Node
if(!((std::find_if(openList.begin(), openList.end(), childToFind) != openList.end()) && actualCost >= (*std::find_if(openList.begin(), openList.end(), childToFind))->getActualCost())){
double estimatedCosts = actualCost+(*child)->getCostToTarget(targetField);
//when Node is already in Openlist update it, if not add the new Node
if(std::find_if(openList.begin(), openList.end(), childToFind) != openList.end()) {
(*std::find_if(openList.begin(), openList.end(), childToFind))->setParent(currentNode);
(*std::find_if(openList.begin(), openList.end(), childToFind))->setActualCost(actualCost);
(*std::find_if(openList.begin(), openList.end(), childToFind))->setTotalCost(estimatedCosts);
make_heap(openList.begin(), openList.end(), ComparePathNodePointer());
} else {
(*child)->setParent(currentNode);
(*child)->setActualCost(actualCost);
(*child)->setTotalCost(estimatedCosts);
this->openList.push_back(*child);
push_heap(openList.begin(), openList.end(), ComparePathNodePointer());
make_heap(openList.begin(), openList.end(), ComparePathNodePointer());
}
}
}
}
};
</code></pre>
|
[] |
[
{
"body": "<p>As a guideline: your inner loop should contain no operation more expensive than O(log(N)). This means no iterating over the entire closed/open list, and no making heaps over and over again! Here's how:</p>\n\n<ol>\n<li>Use a <code>std::set</code> sorted by weight instead of a heap. <code>begin()</code> is your next node, and to update the weight of a node first remove it from the set, change the weight, and put it back again.</li>\n<li>Don't use <code>find_if</code> to test for set inclusion. Use an <code>std::unordered_set</code> for the closed or open nodes.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-29T08:41:35.710",
"Id": "21018",
"ParentId": "20161",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T19:09:00.640",
"Id": "20161",
"Score": "2",
"Tags": [
"c++",
"performance",
"algorithm",
"pathfinding"
],
"Title": "A* C++ implementation is too slow"
}
|
20161
|
<p>Generally, I structure small threadsafe immutable objects like this:</p>
<pre><code>public class SmallObject {
private final String state;
public SmallObject(final String state) {
this.state = state;
}
// ...
}
</code></pre>
<p>And then wire these up in Spring like this:</p>
<pre><code><bean name="SmallObjectForThisThing" class="my.package.SmallObject">
<constructor-arg name="state" value="in practice this is usually a ref"/>
</bean>
</code></pre>
<p>However, this leads to complications with circular dependencies. To keep the immutability when this happens, I use a "freeze" pattern, where the variables are set once. This is what I want reviewed:</p>
<pre><code>public class SmallObject {
private String state = null;
public void setState(String state) {
if (this.state != null) {
throw new IllegalStateException("state already set: '" + state + "'.");
}
this.state = state;
}
private void ensureInitialized() {
if (this.state == null) {
throw new IllegalStateException(
"state must be set before this instance is used."
);
}
}
// ... For every additional method on the object, I call
// ensureInitialized() first.
}
</code></pre>
<p>And then wire them up like this:</p>
<pre><code><bean name="SmallObjectForThisThing" class="my.package.SmallObject">
<property name="state" value="in practice this is usually a ref"/>
</bean>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T11:36:30.703",
"Id": "32414",
"Score": "2",
"body": "I do not understand the purpose, an opinion about this solution depends heavily on the circumstances. This approach will generate a lot of problems if it comes to threadsafety. And it is not really immutable. Perhaps, it could be a better way to invest some time to solve the \"circular dependencies\" problem."
}
] |
[
{
"body": "<p>This class should instead use an AtomicReference to ensure the state is kept valid. Alternatively, you should incorporate thread-safe handling of the String.</p>\n\n<p>Consider:</p>\n\n<pre><code>private final AtomicReference<String> stateref = new AtomicReference<String>();\n\npublic void setState(final String state) {\n // only one initializer will succeed (assuming state is not null)...\n if (!stateref.compareAndSet(null, state)) {\n throw new IllegalStateException(\"state already set: '\" + state + \"'.\");\n }\n}\n\nprivate void ensureInitialized() {\n if (stateref.get() == null) {\n throw new IllegalStateException(\n \"state must be set before this instance is used.\"\n );\n }\n}\n</code></pre>\n\n<p>This pattern ensures usage is consistent, there can be only one initialization of the instance, and that any thread-unsafe practices are handled well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-09T06:15:10.140",
"Id": "36946",
"ParentId": "20163",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "36946",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-04T19:23:04.683",
"Id": "20163",
"Score": "6",
"Tags": [
"java",
"object-oriented",
"immutability",
"spring"
],
"Title": "Circular dependencies between immutable objects; the Freeze Pattern"
}
|
20163
|
<p>These classes are part of a program I am working on to convert Arabic numerals to Roman numerals and vice-versa. Do these classes look correct for representing objects in Java?</p>
<pre><code>public class ArabicNumeral {
private final int value;
public ArabicNumeral(final int value) {
if (value < 0) {
throw new NumberFormatException("Numbers must be positive");
}
this.value = value;
}
public int getThousands() {
return getCardinalValueFor(1000);
}
public int getHundreds() {
return getCardinalValueFor(100);
}
public int getTens() {
return getCardinalValueFor(10);
}
public int getOnes() {
return getCardinalValueFor(1);
}
private int getCardinalValueFor(final int divisor) {
return value / divisor % 10;
}
}
public enum RomanNumerals {
I("I", 1),
V("V", 5),
X("X", 10),
L("L", 50),
C("C", 100),
D("D", 500),
M("M", 1000);
private final String symbol;
private final int value;
RomanNumerals(final String symbol, final int value) {
this.symbol = symbol;
this.value = value;
}
String symbol() {
return symbol;
}
int value() {
return value;
}
public RomanNumerals getMultipleOfFive() {
return this.ordinal() < RomanNumerals.values().length - 1
? RomanNumerals.values()[this.ordinal() + 1] : null;
}
public RomanNumerals getMultipleOfTen() {
return this.ordinal() < RomanNumerals.values().length - 1
? RomanNumerals.values()[this.ordinal() + 2] : null;
}
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><code>RomanNumerals.D.getMultipleOfTen()</code> is <code>java.lang.ArrayIndexOutOfBoundsException</code></li>\n<li>RomanNumerals.D.getMultipleOfFive() is M</li>\n</ul>\n\n<p>What does <code>getMultipleOfFive</code> mean? And why should it return 1000\n when called on 500?</p>\n\n<ul>\n<li><code>symbol()</code> and <code>value()</code> should be <code>getSymbol()</code> and <code>getValue()</code> by convention.</li>\n<li><p><code>symbol()</code> and <code>value()</code> why are they package-private? What are other classes in the package that use them?</p>\n\n<ul>\n<li>Where does the conversion take place?</li>\n</ul></li>\n</ul>\n\n<p>Objects, like everything else, are meaningful only in a context. There is not a <em>one-correct-representation</em> of an arabic numeral. Arabic numerals are default representation so you <strong><em>probably</em></strong> do not need <code>ArabicNumeral</code> at all.\nonly logic there is in:</p>\n\n<pre><code>private int getCardinalValueFor(final int divisor) {\n return value / divisor % 10;\n}\n</code></pre>\n\n<p>which can be rewritten as :</p>\n\n<pre><code>public static int getCardinalValueFor(int value, int divisor) {\n return value / divisor % 10;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T08:37:15.463",
"Id": "20174",
"ParentId": "20166",
"Score": "3"
}
},
{
"body": "<p>I wouldn't do an <code>ArabicNumeral</code>, too, as this is the default numeric system of java.</p>\n\n<p>From a design view, I would see an object <code>RomanNumeral</code>, which is an aggregation of <code>RomanLiteral</code>objects, this <code>RomanLiteral</code>, are the constant roman string->decimal value pairs, which can't be computed.</p>\n\n<p>Both classes can extend <code>java.lang.Number</code>\n<img src=\"https://i.stack.imgur.com/L74Xr.png\" alt=\"RomanNumeral design\"></p>\n\n<p><strong>Class RomanLiteral</strong> represents one base value of the roman numeral system, it is a String - Integer relation, e.g. \"V\" -> 5. <code>toString()</code> is overriden to return the <code>String</code> value.</p>\n\n<p><strong>Class RomanNumeral</strong>\nRepresents a fully roman numeral, it is an aggregate of <code>RomanLiteral</code>s, which are basic String - Integer relation, e.g. \"V\" -> 5, and so on.</p>\n\n<p><strong>Attributes</strong></p>\n\n<ul>\n<li><code>defaultRomanLiteralSet</code> this <code>Set</code> containts the basic constant <code>RomanLiteral</code>s </li>\n<li><code>literals</code> this is the <code>List</code> which contains all <code>RomanLiteral</code>s that aggregate this <code>RomanNumeral</code></li>\n</ul>\n\n<p><strong>Methods</strong> </p>\n\n<ul>\n<li><code>RomanNumeral parseRomanNumeral(Integer)</code> is an analogy to <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29\" rel=\"nofollow noreferrer\">Integer#parseInt(String)</a> this method may be static, and returns the <code>RomanNumeral</code> of the <code>Integer</code> param.</li>\n<li><code>add(RomanNumeral)</code> adds an <code>RomanNumeral</code> to the current value of the object and returns it.</li>\n<li><code>add(RomanLiteral)</code> adds the <code>RomanLiteral</code> to the current value of the object and returns it.</li>\n<li><code>toString()</code> is overriden to return the right <code>String</code> representation of the roman numeral - there happens some calculations with the matching values in the default-set. Here actually gets the roman String calculated out of the integer value of the aggregate.</li>\n</ul>\n\n<p>I think that would be a good useable design. I would stay quite near to the <code>Number</code> style of java, and would do my implementation and design in this direction. (analgous methods and so on..)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T20:27:49.907",
"Id": "20193",
"ParentId": "20166",
"Score": "6"
}
},
{
"body": "<p>This is about general design structure.</p>\n\n<p>You have methods <code>getThousands()</code>, <code>getHundreds()</code> etc those are calling <code>getCardinalValueFor()</code> with different parameters. You don't need so many methods just to provide different parameters. </p>\n\n<p>As per <em>Effective Java</em> Item number #40 (Design method signatures carefully), <br /></p>\n\n<blockquote>\n <p>Every method should “pull its weight.” Too many methods make a class difficult to learn, use,document, test, and maintain.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T10:17:46.513",
"Id": "20206",
"ParentId": "20166",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20193",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T00:52:39.433",
"Id": "20166",
"Score": "6",
"Tags": [
"java",
"beginner",
"object-oriented",
"converting",
"roman-numerals"
],
"Title": "Converting Arabic numerals to Roman numerals"
}
|
20166
|
<p>I have many thousands of image files spread around various places and would like to copy them into one directory. However, may of the files are duplicates with the same names (often thumbnails or reduced resolution etc). I want to delete all files that have the same name except for the largest. </p>
<p>The following code reads a list of these file paths (fullpath/name). It splits the filename from the path, determines the size of the file and adds each filename and its size to a list (map). Where a name is found that is already in the list, the larger of the two is kept in the list and the smaller is 'deleted' (by which I mean emitting the command "rm path/to/file").</p>
<p>I know this is naive C++, because I am a novice (though not at C). Any help making it less naive would (or just better) is appreciated. </p>
<pre><code>#include <iostream>
#include <string>
#include <sys/stat.h>
#include <map>
using std::map;
using std::string;
class filedata {
std::string path;
size_t size;
public:
filedata (void) : path(""), size(0) { }
filedata (const string& p, size_t s) : path(p), size(s){ }
filedata (const filedata& f) : path(f.path), size(f.size) { }
size_t filesize(void) {
return size;
}
string& filepath(void) {
return path;
}
std::ostream& print(std::ostream& os) const {
os << size << " " << path << "\n";
return os;
}
};
std::ostream& operator<<(std::ostream& os, const filedata& f)
{
return f.print(os);
}
static size_t file_size(const string& s)
{
struct stat st;
if (stat(s.c_str(), &st) == 0) {
return st.st_size;
}
return 0;
}
static void delete_file(const string& s)
{
std::cerr << "rm \"" << s << "\"\n";
}
static bool file_name(const string& path, string& name)
{
size_t pos = path.rfind('/');
if (pos == string::npos) {
return false;
}
name = path.substr(pos+1);
return true;
}
int main(int argc, char **argv)
{
(void) argc;
(void) argv;
string s;
map<string, filedata> files;
while (getline(std::cin, s)) {
string name;
if (file_name(s, name) == false) {
break;
}
size_t size = file_size(s);
if (size == 0) {
delete_file(s);
}
else if (files.count(name) > 0) {
filedata f(files[name]);
if (f.filesize() <= size) {
delete_file(f.filepath());
files[name] = filedata(s, size);
}
}
else {
files[name]= filedata(s, size);
}
}
for (auto i = files.begin(); i != files.end(); ++i) {
std::cout << i->first << " " << i->second;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T22:55:44.187",
"Id": "62167",
"Score": "0",
"body": "prefer to use a range based for loop since you are using c++11:\n\nfor(const auto & file : files)\n{\n std::cout << file.first << \" \" << file.second;\n}"
}
] |
[
{
"body": "<p>Looks good overall (though I'm by no means a C++ expert).</p>\n\n<p>In coming brain-dump though:</p>\n\n<hr>\n\n<p><code>void</code> argument lists are rare in C++. Yes, in C, <code>int c()</code> and <code>int c(void)</code> are different, but in C++, that's not the case. In C++, <code>int c()</code> is implicitly the same declaration as <code>int c(void)</code>.</p>\n\n<hr>\n\n<p>The no-op statements on <code>argv</code> and <code>argc</code> jump out as odd. If you did that so a warning of an unused variable won't be issued, you could always use one of the alternate main declarations (i.e. <code>int main()</code>.</p>\n\n<hr>\n\n<p>Opinion again, but I'm not a fan of comparison to booleans: <code>if (file_name(s, name) == false)</code>. It reads more easily as <code>if (!file_name(s, name))</code></p>\n\n<hr>\n\n<p>This might be on purpose, but the <code>path</code> property of <code>filedata</code> can be mutated from outside:</p>\n\n<pre><code>filedata f(\"name\", 10);\nf.filepath() = \"new\";\n</code></pre>\n\n<p>I would probably make these objects immutable since they seem to be value objects (I think you probably intended to do this, just non-intuitive references got you).</p>\n\n<p>You should return either by value or by const reference from <code>filepath</code>. Even though it will create a usually unnecessary copy, I highly suggest the value route. If you return a const reference, you run the risk of a dangling pointer. Consider this (bad) example:</p>\n\n<pre><code>filepath* f = new filepath(\"blah\", 10);\nconst std::string& s = f->filepath();\ndelete f;\n// Any use of s past here is undefined behavior\n</code></pre>\n\n<p><code>s</code> is essentially a const pointer to <code>f->path</code>. This means that when <code>f</code> is released, <code>s</code> becomes invalid. Note that if you immediately create a copy of a string based on the constant reference [i.e. if you had <code>std::string s = ...</code>] this does not apply. That still creates a copy though, so you might as well return a value.</p>\n\n<p>(Also, obligatory note: raw pointers have very few legitimate uses in C++. Avoid pointers if at all possible, and use a smart pointer when not. The only (possible) exception is low level container implementations.)</p>\n\n<hr>\n\n<p>I'm not a fan of <code>print</code> style member functions. In this application this aversion doesn't make sense, but imagine if some third party library you used provided <code>print</code> methods for some of it's classes. Do you think it would print out in exactly the format you want? I prefer to use helper-type functions for printing rather than putting it as a member of the class. (Though once again, on this application since it's so small, it matters nothing at all.)</p>\n\n<p>(Oh, and this once again is opinion.)</p>\n\n<hr>\n\n<pre><code>filedata (void) : path(\"\"), size(0) { }\nfiledata (const string& p, size_t s) : path(p), size(s){ }\nfiledata (const filedata& f) : path(f.path), size(f.size) { }\n</code></pre>\n\n<p>There's a bit of redundancy here. Technically you could write this just as:</p>\n\n<pre><code>filedata (const string& p = \"\", size_t s = 0) : path(p), size(s){ }\n</code></pre>\n\n<p>Or if you wanted:</p>\n\n<pre><code>filedata (const string& p = string(), size_t s = size_t()) : path(p), size(s){ }\n</code></pre>\n\n<p>Though I'd probably go with the first.</p>\n\n<p>The copy constructor doesn't need to be defined since it's the same as the implicit one. When using the same functionality as the implicit one, do not define one. The implicit one isn't prone to typos or a future failure to update the copier to reflect new properties.</p>\n\n<hr>\n\n<p>I would give more descriptive names to <code>p</code> and <code>s</code>:</p>\n\n<pre><code>filedata (const string& path, size_t size) : path(path), size(size) { }\n</code></pre>\n\n<hr>\n\n<p>I'd probably go with something like <code>uint64_t</code> instead of <code>size_t</code> since <code>size_t</code> will probably be 32 bits on a 32 bit system. If you'd like to abstract away exactly what the type is, you could have a <code>typedef ... size_type</code> member of your class. Not only does that offer a more semantic meaning, it allows for easier future change (assuming consumers actually proper use the typedef...).</p>\n\n<hr>\n\n<p>I tend to declare define the end of an iterator up front:</p>\n\n<pre><code>for (auto i = files.begin(), end = files.end(); i != end; ++i) {\n</code></pre>\n\n<p>Not only does it potentially offer a tiny performance advantage (though not really on any modern compiler), it has clearer meaning. With this version, there much more suggestion that end is not mutated inside of the loop (though it's still not guaranteed since end <code>isn't</code> const).</p>\n\n<hr>\n\n<p><code>std::begin</code> and <code>std::end</code> should be preferred in C++11. They have all the capabilities of the member-function versions plus a bit more.</p>\n\n<hr>\n\n<p><code>stat</code> failing probably shouldn't just return a size of 0. You might end up accidentally deleting a file if something weird happens. (Then again, most of the reasons stat would fail would also cause an attempt to delete a file to fail.)</p>\n\n<hr>\n\n<p>If you had the input include the file sizes, you could reduce your program to pure text processing. I'm also not sure if your program should be emitting <code>rm</code> commands. Seems like a coupling of sorts. Then again, the output would just be transformed into <code>rm</code> commands anyway, so might as well do it directly I guess :).</p>\n\n<hr>\n\n<p>The data put out on stdout seems to be debugging-esque information whereas the stderr data seems to be what you're actually after. Seems like these streams should be swapped.</p>\n\n<hr>\n\n<p>I'd be tempted to use a reference instead of copying the item in the map:</p>\n\n<pre><code>filedata f(files[name]);\n</code></pre>\n\n<p>Could be:</p>\n\n<pre><code>filedata& f = files[name];\n</code></pre>\n\n<p>The performance difference is going to be non-existent; mostly just a (opinion-y) style thing. It would also allow you to simplify the reassignment from <code>files[name] = ...</code> to just <code>f = ...</code>.</p>\n\n<hr>\n\n<p>The <code>filesize</code> member of <code>filedata</code> <em>can't</em> permute size, so you might as well have the method be <code>const</code>. Same for <code>filepath()</code> if it wasn't meant to allow the perumtation of <code>path</code> (as mentioned earlier).</p>\n\n<hr>\n\n<p>Another personal-style thing: I don't like implicit visibility scoping:</p>\n\n<pre><code>class filedata {\n std::string path;\n size_t size;\n</code></pre>\n\n<hr>\n\n<pre><code>os << size << \" \" << path << \"\\n\";\nreturn os;\n</code></pre>\n\n<p>Can be simplified to:</p>\n\n<pre><code>return os << size << \" \" << path << \"\\n\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T03:32:56.927",
"Id": "32239",
"Score": "0",
"body": "Thanks very much. I'll have to digest that tomorrow, but there is a lot for me to be thinking about :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T02:32:53.940",
"Id": "20169",
"ParentId": "20167",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20169",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T01:02:38.980",
"Id": "20167",
"Score": "5",
"Tags": [
"c++",
"beginner",
"file"
],
"Title": "Reading a list of file paths and adding them to a map"
}
|
20167
|
<p>I have created WordPress theme options using an array, and it is working. There are 5 type of input: <code>text</code>, <code>textarea</code>, <code>checkbox</code>, <code>select</code> and <code>upload</code>.</p>
<p>Please read over my code and offer some possible improvements and/or tweaks. </p>
<pre><code><?php
add_action( 'admin_menu', 'admin_enqueue_scripts' );
function admin_enqueue_scripts() {
wp_enqueue_style( 'theme-opt-css', get_template_directory_uri() . '/admin/stylesheet/theme-opt.css' );
wp_enqueue_script( 'theme-opt-js', get_template_directory_uri() . '/admin/javascript/theme-opt.js' );
}
function wp_gear_manager_admin_scripts() {
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_enqueue_script('jquery');
}
function wp_gear_manager_admin_styles() {
wp_enqueue_style('thickbox');
}
add_action('admin_print_scripts', 'wp_gear_manager_admin_scripts');
add_action('admin_print_styles', 'wp_gear_manager_admin_styles');
$themename = "Foundation";
$shortname = "fo";
$mx_categories_obj = get_categories('hide_empty=0');
$mx_categories = array();
foreach ($mx_categories_obj as $mx_cat) {
$mx_categories[$mx_cat->cat_ID] = $mx_cat->cat_name;
}
$categories_tmp = array_unshift($mx_categories, "Select a category:");
$number_entries = array("Select a Number:","1","2","3","4","5","6","7","8","9","10" );
$colorscheme = array("Default", "White", "Blue", "Red", "Purple");
$options = array (
array( "name" => "Main Set Up",
"type" => "heading",
"desc" => "Set your logo and color scheme.",
),
array( "name" => "Logo Display",
"desc" => "The URL address of your logo (best is 400px x 65px). (Leaving it empty will display your blog title)",
"id" => $shortname."_logo",
"type" => "upload",
"std" => ""),
array( "name" => "Blog Color Scheme",
"id" => $shortname."_color",
"type" => "select",
"std" => "Default",
"options" => $colorscheme),
array( "name" => "Blog Width",
"id" => $shortname."_width",
"type" => "text",
"std" => "1440"),
array( "name" => "Navigation Settings",
"type" => "heading"),
array( "name" => "Exclude Categories",
"desc" => "Enter a comma-separated list of the <a href='http://support.wordpress.com/pages/8/'>Category ID's</a> that you'd like to exclude from the main category navigation. (e.g. 1,2,3,4)",
"id" => $shortname."_cat_ex",
"std" => "",
"type" => "text"),
array( "name" => "Featured section",
"type" => "heading",
"desc" => "This section customizes the featured area on the top of the content and the number of stories displayed there.",
),
array( "name" => "Featured section category",
"desc" => "Select the category that you would like to have displayed in Featured list on your homepage.",
"id" => $shortname."_story_category",
"std" => "Uncategorized",
"type" => "select",
"options" => $mx_categories),
array( "name" => "Number of highlight reel posts",
"desc" => "Select the number of posts to display ( Upto 5 is good).",
"id" => $shortname."_story_count",
"std" => "1",
"type" => "select",
"options" => $number_entries),
array( "name" => "Sidebar Set Up",
"type" => "heading",
"desc" => "Set your sidebar layout.",
),
array( "name" => "Disable Tabs box?",
"desc" => "Tick to disable Tabs box.",
"id" => $shortname."_distabs",
"type" => "checkbox",
"std" => "false"),
array( "name" => "Disable Search box?",
"desc" => "Tick to disable Search box.",
"id" => $shortname."_search",
"type" => "checkbox",
"std" => "false"),
array( "name" => "Disable About box?",
"desc" => "Tick to disable About box.",
"id" => $shortname."_dispop",
"type" => "checkbox",
"std" => "false"),
array( "name" => "Disable Ads box?",
"desc" => "Tick to disable Ads box.",
"id" => $shortname."_disads",
"type" => "checkbox",
"std" => "false"),
array( "name" => "Disable Flickr box?",
"desc" => "Tick to disable Flickr box.",
"id" => $shortname."_disflickr",
"type" => "checkbox",
"std" => "false"),
array( "name" => "Disable Follow Me box?",
"desc" => "Tick to disable Follow Me box.",
"id" => $shortname."_disfollow",
"type" => "checkbox",
"std" => "false"),
array( "name" => "Disable Video box?",
"desc" => "Tick to disable Video Me box.",
"id" => $shortname."_disvideo",
"type" => "checkbox",
"std" => "false"),
array( "name" => "About Me Settings",
"type" => "heading",
"desc" => "Set your About me image and text from here .",
),
array("name" => "About me Image",
"desc" => "Enter your avatar image url here.",
"id" => $shortname."_img",
"std" => "",
"type" => "text"),
array("name" => "About me text",
"desc" => "Enter some descriptive text about you, or your site.",
"id" => $shortname."_about",
"std" => "Integer eget dui ante, a vestibulum augue. Suspendisse lorem diam, viverra a interdum in, facilisis eget mauris. Etiam cursus ligula at dolor ultrices adipiscing sodales metus lacinia. Etiam id justo consectetur lorem auctor scelerisque nec varius ante. Ut condimentum nisl nec enim porttitor ut auctor neque adipiscing. Praesent ac eleifend nunc.",
"type" => "textarea"),
array( "name" => "Featured Video Settings",
"type" => "heading",
"desc" => "Displays a featured video on the homepage .",
),
array( "name" => "Featured Video category",
"desc" => "Select the category that you would like to have displayed in the videos section on your homepage.",
"id" => $shortname."_video_category",
"std" => "Select a category:",
"type" => "select",
"options" => $mx_categories),
array( "name" => "Twitter, Facebook, Flickr account",
"type" => "heading",
"desc" => "",
),
array( "name" => "Your Twitter account",
"desc" => "Enter your Twitter account name",
"id" => $shortname."_twitter_user_name",
"type" => "text",
"std" => ""),
array( "name" => "Your Facebook account",
"desc" => "Enter your Facebook account name",
"id" => $shortname."_facebook_user_name",
"type" => "text",
"std" => ""),
array( "name" => "Your Flickr account",
"desc" => "Enter your Flickr account name",
"id" => $shortname."_flickr_user_name",
"type" => "text",
"std" => ""),
array( "name" => "Header Banner Ad (468x60px)",
"desc" => "Enter your AdSense code, or your banner url and destination, or disable header ad.",
"type" => "heading"),
array( "name" => "Adsense code",
"desc" => "Enter your adsense code here.",
"id" => $shortname."_ad_head_adsense",
"std" => "",
"type" => "textarea"),
array( "name" => "Banner Ad Header - Image Location",
"desc" => "Enter the URL for this banner ad.",
"id" => $shortname."_ad_head_image",
"std" => "wp-content/themes/GoodThemeLead/images/ad-big.gif",
"type" => "text"),
array( "name" => "Banner Ad Header - Destination",
"desc" => "Enter the URL where this banner ad points to.",
"id" => $shortname."_ad_head_url",
"std" => "#",
"type" => "text"),
array( "name" => "Disable Ad",
"desc" => "Disable the ad space",
"id" => $shortname."_ad_head_disable",
"std" => "false",
"type" => "checkbox"),
array( "name" => "Content Banner Ad (468x60px)",
"desc" => "Enter your AdSense code, or your banner url and destination, or disable content ad.","type" => "heading"),
array( "name" => "Adsense code",
"desc" => "Enter your adsense code here.",
"id" => $shortname."_ad_content_adsense",
"std" => "",
"type" => "textarea"),
array( "name" => "Banner Ad Content - Image Location",
"desc" => "Enter the URL for this banner ad.",
"id" => $shortname."_ad_content_image",
"std" => "wp-content/themes/GoodThemeLead/images/ad-big.gif",
"type" => "text"),
array( "name" => "Banner Ad Content - Destination",
"desc" => "Enter the URL where this banner ad points to.",
"id" => $shortname."_ad_content_url",
"std" => "#",
"type" => "text"),
array( "name" => "Disable Ad",
"desc" => "Disable the ad space",
"id" => $shortname."_ad_content_disable",
"std" => "false",
"type" => "checkbox"),
array( "name" => "Banner Ads Settings",
"type" => "heading",
"desc" => "You can setup four 125x125 banners for your blog from here",
),
array("name" => "Banner-1 Image",
"desc" => "Enter your 125x125 banner image url here.",
"id" => $shortname."_banner1",
"std" => "wp-content/themes/GoodThemeLead/images/ad-small.gif",
"type" => "text"),
array("name" => "Banner-1 Url",
"desc" => "Enter the banner-1 url here.",
"id" => $shortname."_url1",
"std" => "#",
"type" => "text"),
array("name" => "Banner-2 Image",
"desc" => "Enter your 125x125 banner image url here.",
"id" => $shortname."_banner2",
"std" => "wp-content/themes/GoodThemeLead/images/ad-small.gif",
"type" => "text"),
array("name" => "Banner-2 Url",
"desc" => "Enter the banner-2 url here.",
"id" => $shortname."_url2",
"std" => "#",
"type" => "text"),
array("name" => "Banner-3 Image",
"desc" => "Enter your 125x125 banner image url here.",
"id" => $shortname."_banner3",
"std" => "wp-content/themes/GoodThemeLead/images/ad-small.gif",
"type" => "text"),
array("name" => "Banner-3 Url",
"desc" => "Enter the banner-3 url here.",
"id" => $shortname."_url3",
"std" => "#",
"type" => "text"),
array("name" => "Banner-4 Image",
"desc" => "Enter your 125x125 banner image url here.",
"id" => $shortname."_banner4",
"std" => "wp-content/themes/GoodThemeLead/images/ad-small.gif",
"type" => "text"),
array("name" => "Banner-4 Url",
"desc" => "Enter the banner-4 url here.",
"id" => $shortname."_url4",
"std" => "#",
"type" => "text"),
);
function mytheme_add_admin() {
global $themename, $shortname, $options;
if ( $_GET['page'] == basename(__FILE__) ) {
if ( 'save' == $_REQUEST['action'] ) {
foreach ($options as $value) {
update_option( $value['id'], $_REQUEST[ $value['id'] ] ); }
foreach ($options as $value) {
if( isset( $_REQUEST[ $value['id'] ] ) ) { update_option( $value['id'], $_REQUEST[ $value['id'] ] ); } else { delete_option( $value['id'] ); } }
header("Location: themes.php?page=theme-options.php&saved=true");
die;
} else if( 'reset' == $_REQUEST['action'] ) {
foreach ($options as $value) {
delete_option( $value['id'] );
update_option( $value['id'], $value['std'] );}
header("Location: themes.php?page=theme-options.php&reset=true");
die;
}
}
add_theme_page($themename." Options", "$themename Options", 'edit_themes', basename(__FILE__), 'mytheme_admin');
}
function mytheme_admin() {
global $themename, $shortname, $options;
if ( $_REQUEST['saved'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings saved.</strong></p></div>';
if ( $_REQUEST['reset'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings reset.</strong></p></div>';
?>
<div id="<?php echo $shortname; ?>" class="wrap">
<h2><b><?php echo $themename; ?> options</b></h2>
<div class="theme-opts-c">
<div class="theme-opts-author">
<div class="about-me">
<h1 class="thank">Thank You!</h1>
<h2 class="visit">Visit </h2>
</div>
</div>
<form method="post">
<div class="options-grids" >
<?php foreach ($options as $value) {
if ($value['type'] == "text") {
/* ----------------------Start Input Text -------------------*/
?>
<div class="option-box">
<h1 class="option-title"><?php echo $value['name']; ?></h1>
<div class="option-input">
<input name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" value="<?php if ( get_settings( $value['id'] ) != "") { echo get_settings( $value['id'] ); } else { echo $value['std']; } ?>" size="40" />
</div>
<div class="option-desc"><?php echo $value['desc']; ?> </div>
</div>
<?php
/* ----------------------End Input text-------------------*/
} elseif ($value['type'] == "textarea") {
/* ----------------------Start textarea -------------------*/
?>
<div class="option-box">
<h1 class="option-title"><?php echo $value['name']; ?></h1>
<div class="option-input">
<textarea name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" cols="40" rows="5"/><?php if ( get_settings( $value['id'] ) != "") { echo get_settings( $value['id'] ); } else { echo $value['std']; } ?>
</textarea>
</div>
<div class="option-desc"><?php echo $value['desc']; ?> </div>
</div>
<?php
/* ----------------------End textarea -------------------*/
} elseif ($value['type'] == "select") {
/* ----------------------Start Select -------------------*/
?>
<div class="option-box">
<h1 class="option-title"><?php echo $value['name']; ?></h1>
<div class="option-input">
<select name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>">
<?php foreach ($value['options'] as $option) { ?>
<option<?php if ( get_settings( $value['id'] ) == $option) { echo ' selected="selected"'; }?>><?php echo $option; ?></option>
<?php } ?>
</select>
</div>
<div class="option-desc"><?php echo $value['desc']; ?> </div>
</div>
<?php
/* ----------------------End Select-------------------*/
} elseif ($value['type'] == "checkbox") {
/* ----------------------Start checkbox -------------------*/
?>
<div class="option-box">
<h1 class="option-title"><?php echo $value['name']; ?></h1>
<div class="option-input">
<?php if(get_settings($value['id'])){ $checked = "checked=\"checked\""; }else{ $checked = ""; } ?>
<input type="checkbox" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" value="true" <?php echo $checked; ?> />
</div>
<div class="option-desc"><?php echo $value['desc']; ?> </div>
</div>
<?php
/* ------------------- end checkbox -------------------*/
}elseif ($value['type'] == "upload") {
/* ----------------------Start upload -------------------*/
?>
<div class="option-box">
<h1 class="option-title"><?php echo $value['name']; ?></h1>
<div id="upload-opt" class="option-input">
<input id="upload_image" type="text" size="36" name="<?php echo $value['id']; ?>" value="<?php echo $gearimage; ?>" />
<input id="upload_image_button" type="button" value="Upload Image" />
</div>
<div class="option-desc"><?php echo $value['desc']; ?> </div>
</div>
<?php
/* ------------------- end upload -------------------*/
} elseif ($value['type'] == "heading") {
/* ----------------------Start heading -------------------*/
?>
<div class="option-heading">
<h2 class="option-heading-title"><?php echo $value['name']; ?></h2>
<div class="option-heading-desc"><?php echo $value['desc']; ?> </div>
</div>
<?php /* ----------------------End Heading -------------------*/} ?>
<?php } ?>
</div>
<div class="opt-submit">
<div class="submit">
<input name="save" type="submit" value="Save changes" />
<input type="hidden" name="action" value="save" />
</div>
</div>
</form>
<div class="opt-reset">
<form method="post">
<div class="reset">
<input name="reset" type="submit" value="Reset" />
<input type="hidden" name="action" value="reset" />
</div>
</form>
</div>
</div>
</div>
<?php
}
add_action('admin_menu', 'mytheme_add_admin'); ?>
</code></pre>
|
[] |
[
{
"body": "<p>Mostly, it just appears that your code is violating the \"Don't Repeat Yourself\" (DRY) Principle. As the name implies, your code should not repeat itself. There are a few reasons for this, efficiency and reusablity chief among them. Your first violation of DRY is sort of a combination of the two. When you have a similar value being reused, without using a variable, and that value is something mutable like a directory, then it is inefficient and harder to reuse as you will have to change every instance of that value if it ever needs to be changed. Additionally, if that value, or part of it, is being fetched from a function, then you are making your code work harder than it needs to. Using functions has a higher processing cost than using a variable, so calling the function once and setting its return to a variable is more efficient. Another added benefit of abstracting this value is shorter line lengths, which means more legible code.</p>\n\n<pre><code>$dir = get_template_directory_uri() . '/admin/';\nwp_enqueue_style( 'theme-opt-css', $dir . 'stylesheet/theme-opt.css' );\nwp_enqueue_script( 'theme-opt-js', $dir . 'javascript/theme-opt.js' );\n</code></pre>\n\n<p>That's still sort of violating DRY, what with that first parameter and filename being so similar, but after toying around with <code>str_replace()</code> and <code>substr_replace()</code> for a few minutes I decided it was more hassle than it was worth, and creating a function just for that seems unnecessary unless it will be reused a lot more.</p>\n\n<p>I don't know if its an issue with with the uploaded script or not, but some of your functions are not indented. I'd make sure this isn't the case with your actual code, and if it is, I would fix it. Indentation is a pretty big point for legibility.</p>\n\n<p>There is a quote that goes along with the above principle: \"You can either do something once, or you can do something many times. There's no such thing as doing something only twice.\" I probably slaughtered that quote, but its pretty close. Essentially it just means that you should use loops or functions to simulate repetition in tasks. For example:</p>\n\n<pre><code>$scripts = array(\n 'media-upload',\n 'thickbox',\n 'jquery'\n);\n\nforeach( $scripts AS $script ) {\n wp_enqueue_script( $script );\n}\n</code></pre>\n\n<p>The above can also be applied to those <code>add_action()</code> function calls too, just use a multi-dimensional array.</p>\n\n<p>Here's a neat trick: If you have a range of numbers you want in an array, you can use PHP's <code>range()</code> function to populate it for you. This makes it a little easier to manipulate that range, if needs be, and helps with legibility.</p>\n\n<pre><code>$number_entries = range( 1, 10 );\n$number_entries = array_unshift( $number_entries, 'Select a Number:' );\n</code></pre>\n\n<p>I have no idea what this <code>$options</code> array is, nor what its being used for, but that is just too large to throw in the middle of your code like that. You should see if you can't abstract it away from your code somehow. I'm thinking maybe a config file or database. I'm just going to ignore this for now.</p>\n\n<p>Globals are evil. Forget you ever heard of them. You will NEVER need a global. EVER. You should avoid globals at all costs. There are a number of reasons for this, but there are two main ones: They are insecure because any application can use them once they are declared; They are hard to maintain because they are difficult to read and trace. Everything in your script appears to be contained in this one file, but they could just as easily have come from another file, or be manipulated in another file. There are a few different ways we can avoid globals, but the easiest in this case would simply be to inject them into our functions as parameters. <code>$shortname</code> isn't even used in this first function, so it can be left out altogether.</p>\n\n<pre><code>function mytheme_add_admin( $themename, $options ) {\n</code></pre>\n\n<p>You are violating the Arrow Anti-Pattern. This pattern is illustrated by code that is heavily or unnecessarily indented, usually so that it comes to points like an arrow. This should be avoided to enhance legibility. There are a couple of ways we can avoid violating this principle. One is to return early from functions to stop execution. Another is to manipulate our if logic so that it contains the smaller block of code and then return early. If we do the latter, then we can neglect the else statement as it is implied, thus we remove a level of indentation from the larger block of code.</p>\n\n<pre><code>$basename = basename( __FILE__ );\nif ( $_GET[ 'page' ] != $basename ) {\n $options = \"$themename . Options\";\n add_theme_page(\n $options,\n $options,\n 'edit_themes',\n $basename,\n 'mytheme_admin'\n );\n\n return;\n}\n\n//else implied, rest of code here\n</code></pre>\n\n<p>Its perfectly fine to use Yoda syntax or normal syntax, but you should be consistent and choose either one or the other, not both. There is no right or wrong way here. Originally Yoda syntax was considered good practice because a non-variable value can't be defined with a value like a variable, thus avoiding accidentally reassigning a new value to a variable in a statement. However, this practice fell out of common practice because most languages stopped supporting assignments in statements. PHP still allows this, so Yoda syntax still makes sense, but isn't necessary if you are vigilant.</p>\n\n<pre><code>//standard\nif( $_GET[ 'page' ] == $basename ) {\n\n//because second equals sign was forgotten\n//page is now $basename\nif( $_GET[ 'page' ] = $basename ) {\n\n//yoda\nif( 'save' == $_REQUEST[ 'action' ] ) {\n\n//a string cannot be given a value\n//so this throws fatal errors preventing accidents\nif( 'save' = $_REQUEST[ 'action' ] ) {\n</code></pre>\n\n<p>Don't iterate over the same array twice, especially if no changes were made to that array to make a second iteration necessary. Your two foreach loops can be combined. I'm not even sure that first loop was necessary. You are updating the <code>$data[ 'id' ]</code> in the first loop, then the second loop checks that same value against the <code>$_REQUEST</code> array to determine if it should be updated or deleted. Seems kind of redundant.</p>\n\n<pre><code>foreach( $options AS $value ) {\n $id = $value[ 'id' ];\n update_option( $id, $_REQUEST[ $id ] );//is there a reason for this?\n\n\n if( isset( $_REQUEST[ $id ] ) ) {\n update_option( $id, $_REQUEST[ $id ] );\n } else {\n delete_option( $id );\n }\n}\n</code></pre>\n\n<p>Typically when you reload a page with a <code>header()</code>, you use exit, not die. I don't know if there is really any difference in this, but figured I'd mention it.</p>\n\n<pre><code>header(\"Location: themes.php?page=theme-options.php&saved=true\");\nexit;\n</code></pre>\n\n<p>My last bit of advice would be to consider using includes instead of directly outputting HTML with PHP. Its cleaner and will allow you to reuse the HTML if necessary. That first bit of HTML, including the foreach loop with all those if/else statements can be one include. Then inside that foreach loop, each if/else statement can lead to another include.</p>\n\n<pre><code>//new include 'text.inc'\n<div class=\"option-box\">\n <h1 class=\"option-title\"><?php echo $value['name']; ?></h1>\n <div class=\"option-input\">\n <input name=\"<?php echo $value['id']; ?>\" id=\"<?php echo $value['id']; ?>\" type=\"<?php echo $value['type']; ?>\" value=\"<?php\n if( get_settings( $value['id'] ) != '' ) {\n echo get_settings( $value['id'] );\n } else {\n echo $value['std'];\n }\n ?>\" size=\"40\" />\n </div> \n <div class=\"option-desc\"><?php echo $value['desc']; ?> </div>\n\n</div>\n\n//back in the main file\nif( $value[ 'type' ] == 'text' ) {\n include 'text.inc';\n} elseif( $value[ 'type' ] == 'textarea' ) {\n //etc...\n</code></pre>\n\n<p>Side note: The if/else statement in the above include can be rewritten as a ternary statement. Some people do not like ternary because it is usually abused, but as long as it is short and simple, I see no problems with it.</p>\n\n<pre><code>//original\nif( get_settings( $value['id'] ) != '' ) {\n echo get_settings( $value['id'] );\n} else {\n echo $value['std'];\n}\n\n//regular ternary\necho get_settings( $value[ 'id' ] ) ? get_settings( $value[ 'id' ] ) : $value[ 'std' ];\n//PHP >= 5.3 allows short ternary\necho get_settings( $value[ 'id' ] ) ?: $value[ 'std' ];\n</code></pre>\n\n<p>When you are comparing the same value against multiple possibilities, you should use a switch statement rather than if/else statements. They are a bit faster and a little easier to read and maintain.</p>\n\n<pre><code>switch( $value[ 'type' ] ) {\n case 'text' :\n //etc...\n break;\n\n case 'textarea' :\n //etc...\n break;\n\n //etc...\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T17:18:38.017",
"Id": "20239",
"ParentId": "20171",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20239",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T03:55:37.647",
"Id": "20171",
"Score": "2",
"Tags": [
"php",
"wordpress"
],
"Title": "Simple theme options held in array"
}
|
20171
|
<p>My code looks like "spaghetti code". I have yet to use OOP in PHP but I am really interested in how a good programmer would handle this many <code>if</code> statements. It looks like a mess.</p>
<pre><code><?php
session_start();
include './functions.php';
if(empty($_FILES['browseMovie']) || empty($_FILES['browseThumbnail']) || empty($_GET['title']) || empty($_GET['description']))
{
die('Please insert all fields.');
}
$filePartsMovie = pathinfo($_FILES['browseMovie']['name']);
$filePartsThumbnail = pathinfo($_FILES['browseThumbnail']['name']);
if($filePartsMovie['extension'] !== "mp4")
{
die('Video has to be a .mp4 file.');
}
if($filePartsThumbnail['extension'] !== "jpg" && $filePartsThumbnail['extension'] !== "png")
{
die('Thumbnail has to be in jpg/jpeg or png format.');
}
if($_FILES['browseMovie']['size'] + $_FILES['browseThumbnail']['size'] > 1600600000)
{
die('filesize of video and thumbnail = higher 1.5 GB.');
}
$id = $_SESSION["id"];
$name = $_SESSION["username"];
$folderName = generateUniqueFolder();
$title = mysql_real_escape_string($_GET['title']);
$description = mysql_real_escape_string($_GET['description']);
// the original file name will be stored in the database as well
$thumbFileName = basename($_FILES['browseThumbnail']['name']);
$vidFileName = basename($_FILES['browseMovie']['name']);
$userDir = "../users/$name/";
$videoDir = $userDir . "videos/" . $folderName . "/";
$uploadMovieDir = $videoDir . $vidFileName;
$uploadThumbnailDir = $videoDir . $thumbFileName;
if(!isLoggedIn() || !is_dir($userDir))
{
die('User does not have own folder. Please contact the administrator.');
}
if(!mkdir($videoDir))
{
die('Could not create unique video folder.');
}
if(!move_uploaded_file($_FILES['browseMovie']['tmp_name'], $uploadMovieDir))
{
rmdir($videoDir);
die('Could not upload the video correctly.');
}
if(!move_uploaded_file($_FILES['browseThumbnail']['tmp_name'], $uploadThumbnailDir))
{
removeTreeDir($videoDir);
die('Could not upload the thumbnail correctly.');
}
$con = connectDb();
$videoQuery = "INSERT INTO video(userId, title, description, foldername, vidFileName, thumbFileName) VALUES ($id,'$title','$description','$folderName', '$vidFileName', '$thumbFileName')";
if(!mysql_query($videoQuery))
{
removeTreeDir($videoDir);
die('Could not add the video to the database.');
}
mysql_close($con);
echo "true";
?>
</code></pre>
<p>Somewhere in the middle of my code I also need a bunch of variables. How would one clean that up? Create an object and aggregate them together?</p>
|
[] |
[
{
"body": "<p>Your first if can be simplifed with <code>any</code> function.</p>\n\n<pre><code>function any ($list, $pred) \n{\n foreach ($list as $value) \n {\n if (call_user_func ($pred, $value) == TRUE)\n return TRUE;\n }\n return FALSE;\n}\n</code></pre>\n\n<p>So it will be :</p>\n\n<pre><code> $toTest = [$_FILES['browseMovie'], \n $_FILES['browseThumbnail'], \n $_GET['title'], \n $_GET['description'] ]\n if (any ($toTest, \"empty\")) die (\"Please insert all fields\")\n</code></pre>\n\n<p>Then you can simplify the code even more by creating a <code>validate</code> type function</p>\n\n<pre><code>function validateFile ($filePartsMovie, $filePartsThumbnail) \n{\n if($filePartsMovie['extension'] !== \"mp4\")\n {\n die('Video has to be a .mp4 file.');\n }\n\n if($filePartsThumbnail['extension'] !== \"jpg\" &&\n $filePartsThumbnail['extension'] !== \"png\")\n {\n die('Thumbnail has to be in jpg/jpeg or png format.');\n } \n\n if($_FILES['browseMovie']['size'] + $_FILES['browseThumbnail']['size'] > 1600600000)\n {\n die('filesize of video and thumbnail = higher 1.5 GB.');\n }\n}\n</code></pre>\n\n<p>Then you can create a validate function for the rest of the code.</p>\n\n<p>TLDR is to split your code in more separate functions.</p>\n\n<p>BTW I think you do not need brackets when having only one statement after <code>if</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T11:05:33.960",
"Id": "32245",
"Score": "0",
"body": "I do not know PHP so this is from my general programming knowledge. It might not work, but the idea behind the code I posted is good (I hope :))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T11:53:35.257",
"Id": "32246",
"Score": "0",
"body": "Doesnt matter really :) This can happen in any language. It just happened to be written in php when I came across this problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T11:59:59.470",
"Id": "32248",
"Score": "0",
"body": "BTW, I like your validateFile() function. That would definitely make it more organized. :) I dont know about the top one, though. I only need to check if they're empty once. Is that worth the effort adding extra code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T15:56:02.700",
"Id": "32255",
"Score": "0",
"body": "\"BTW I think you do not need brackets when having only one statement after if.\" -- You don't, but I nearly always use them for readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T17:35:49.753",
"Id": "32376",
"Score": "0",
"body": "Indeed, braceless syntax is allowed, but is usually frowned upon. Additionally that short array syntax ([] instead of array()) is relatively new to PHP (5.4) and may be confusing if someone is unfamiliar with it and attempts to use it with an older version."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T11:04:16.563",
"Id": "20178",
"ParentId": "20172",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20178",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T04:11:16.317",
"Id": "20172",
"Score": "2",
"Tags": [
"php",
"optimization"
],
"Title": "Movie database browser"
}
|
20172
|
<p>I'm developing a model for web applications. The database that I use is Redis.</p>
<p>I created special <code>DbField</code> objects like <code>HashDbField</code>, <code>SortedSetDbField</code>, <code>ScalarDbField</code> and so on, for each data type in Redis. This objects provides a convenient way to work with redis keys. Each of it takes target key name in constructor</p>
<p>The second type of objects are <code>DbObject</code>s that represents objects in database. <code>DbObject</code>s (<code>UserDbObject</code>, <code>PostDbObject</code>) consist of <code>DbField</code>s. There are class fields, for some global registers and instance fields for values of certain objects.</p>
<p>Each <code>dbObject</code> has a <code>DbObjectName</code> class field which contains the current object name ('user', 'post', 'comment', and so on...) </p>
<p><code>DbObject</code> class looks like:</p>
<pre><code>class DbObjectType(type):
def __init__(cls, name, bases, dct):
super(DbObjectType, cls).__init__(name, bases, dct)
cls._TypeInit()
class DbObject(metaclass=DbObjectType):
DbObjectName = DB_OBJECT_NAME
@classmethod
def _TypeInit(cls):
cls._SelfDbObjectSerializator = DbObjectSerializator(cls)
cls.LastId = ScalarDbField(cls.DbObjectName, None, R_LAST_ID)
cls.Reg = SortedSetDbField(cls.DbObjectName, None, R_REG, cls._SelfDbObjectSerializator, DateTimeSerializator)
cls._Reg_raw = SortedSetDbField(cls.DbObjectName, None, R_REG)
@classmethod
def Create(cls):
newDbObjectId = cls.LastId.increment()
dbObject = cls(newDbObjectId)
dbObject.createDate.set(datetime.now())
return dbObject
@classmethod
def Get(cls, dbObjectId):
assert dbObjectId
if not cls._Reg_raw.contains(dbObjectId): return None
return cls(dbObjectId)
def delete(self):
for value in self.__dict__.values():
if isinstance(value, DbField):
dbField = value
dbField.destroy()
def __init__(self, dbObjectId):
assert dbObjectId
self._dbObjectId = str(dbObjectId)
self.createDate = ScoreDbField(self.DbObjectName, self._dbObjectId, F_CREATE_DATE, self.Reg, self, DateTimeSerializator)
self.tag = ScalarDbField(self.DbObjectName, self._dbObjectId, F_TAG)
def __hash__(self):
return hash(self._dbObjectId)
def __str__(self):
return self._dbObjectId
def __eq__(self, other):
if type(self) != type(other): return False
return (self.DbObjectName == other.DbObjectName) and (self._dbObjectId == other._dbObjectId)
def __ne__(self, other):
return not self.__eq__(other)
id = property(lambda self: self._dbObjectId)
</code></pre>
<p>As you can see, class fields defining in <code>TypeInit</code>, which is called right after class creates. This trick provides inheritance support, so <code>DbObject</code>'s derivative classes will contain <code>LastId</code> and <code>Reg</code> but for its own <code>DbObjectName</code>.</p>
<p>Is there way to make this more pythonic? I think this can be implemented with decorators, but I'm not sure it will be better. </p>
<p>Here are some <code>DbField</code>s: </p>
<pre><code>class DbField():
_Redis = None
@classmethod
def Connect(cls, host=None, port=None):
cls._Redis = Redis(host or 'localhost', port or 6379, decode_responses =True)
def __init__(self, dbObjectName, dbObjectId, fieldName, valueSerializator=None):
assert dbObjectName
assert fieldName
self._dbObjectName = dbObjectName
self._dbObjectId = dbObjectId
self._fieldName = fieldName
if self._dbObjectId:
self._key = "%s:%s:%s" % (self._dbObjectName, self._dbObjectId, self._fieldName)
else:
self._key = "%s:%s" % (self._dbObjectName, self._fieldName)
self._valueSerializator = valueSerializator or Serializator
def exists(self):
return self._Redis.exists(self._key)
def destroy(self):
return self._Redis.delete(self._key)
class HashDbField(DbField):
def __init__(self, dbObjectName, dbObjectId, fieldName, valueSerializator=None, nameSerializator=None):
super(HashDbField, self).__init__(dbObjectName, dbObjectId, fieldName, valueSerializator)
self._nameSerializator = nameSerializator or Serializator
def set(self, name, value, overwrite=True):
return (self._Redis.hset if overwrite else self._Redis.hsetnx)(
self._key, self._nameSerializator.serialize(name), self._valueSerializator.serialize(value)
)
def get(self, name):
return self._valueSerializator.restore(
self._Redis.hget(self._key, self._nameSerializator.serialize(name))
)
def delete(self, name):
return self._Redis.hdel(self._key, self._nameSerializator.serialize(name))
class SortedSetDbField(DbField):
def __init__(self, dbObjectName, dbObjectId, fieldName, valueSerializator=None, scoreSerializator=None):
super(SortedSetDbField, self).__init__(dbObjectName, dbObjectId, fieldName, valueSerializator)
self._scoreSerializator = scoreSerializator or Serializator
def add(self, value, score):
self._Redis.zadd(self._key, self._valueSerializator.serialize(value), self._scoreSerializator.serialize(score))
def getRange(self, start=0, end=-1, desc=False):
return map(self._valueSerializator.restore, self._Redis.zrange(self._key, start=start, end=end, desc=desc))
def getScore(self, value):
return self._scoreSerializator.restore(self._Redis.zscore(self._key, self._valueSerializator.serialize(value)))
def setScore(self, value, score):
self.add(value, score)
def indexOf(self, value):
return self._Redis.zrank(self._key, self._valueSerializator.serialize(value))
def contains(self, value):
return self.indexOf(value) is not None
def delete(self, value):
self._Redis.zrem(self._key, self._valueSerializator.serialize(value))
def count(self):
return self._Redis.zcard(self._key)
def union(self, sortedSetDbField):
assert isinstance(sortedSetDbField, SortedSetDbField)
self._Redis.zunionstore(self._key, (self._key, sortedSetDbField._key), aggregate='max')
def subtract(self, sortedSetDbField):
assert isinstance(sortedSetDbField, SortedSetDbField)
self._Redis.zunionstore(self._key, {self._key: 1, sortedSetDbField._key: -1}, aggregate='min')
self._Redis.zremrangebyscore(self._key, '-inf', 0)
class ScalarDbField(DbField):
def set(self, value, overwrite=True):
return (self._Redis.set if overwrite else self._Redis.setnx)(self._key, self._valueSerializator.serialize(value))
def get(self):
return self._valueSerializator.restore(self._Redis.get(self._key))
def increment(self, amount=1):
return self._Redis.incr(self._key, amount)
class RefValueDbField(ScalarDbField):
def __init__(self, dbObjectName, dbObjectId, fieldName, targetHashDbField, targetHashDbFieldValue, valueSerializator=None):
super(RefValueDbField, self).__init__(dbObjectName, dbObjectId, fieldName, valueSerializator)
self._targetHashDbField = targetHashDbField
self._targetHashDbFieldValue = targetHashDbFieldValue
def set(self, name, overwrite=False):
if not self._targetHashDbField.set(name, self._targetHashDbFieldValue, overwrite):
return False
oldName = self.get()
super(RefValueDbField, self).set(name)
if oldName is not None: self._targetHashDbField.delete(oldName)
return True
def destroy(self):
name = self.get()
if name is not None: self._targetHashDbField.delete(name)
super(RefValueDbField, self).destroy()
class ScoreDbField(ScalarDbField):
def __init__(self, dbObjectName, dbObjectId, fieldName, targetSortedSetDbField, targetSortedSetDbFieldValue, valueSerializator=None):
assert isinstance(targetSortedSetDbField, SortedSetDbField)
super(ScoreDbField, self).__init__(dbObjectName, dbObjectId, fieldName, valueSerializator)
self._targetSortedSetDbField = targetSortedSetDbField
self._targetSortedSetDbFieldValue = targetSortedSetDbFieldValue
def set(self, score):
self._targetSortedSetDbField.setScore(self._targetSortedSetDbFieldValue, score)
super(ScoreDbField, self).set(score)
def exists(self):
return self._targetSortedSetDbField.contains(self._targetSortedSetDbFieldValue)
def destroy(self):
self._targetSortedSetDbField.delete(self._targetSortedSetDbFieldValue)
super(ScoreDbField, self).destroy()
</code></pre>
<p>I'm in trouble with <code>ScalarDbField</code> because I have to call get/set methods to get/set values. I can't use it like descriptor to get/set values like in regular variable because it mostly used like instance field, and I don't like to use properties with lambdas:</p>
<pre><code>nick = property(lambda self: self._nick.get(), lambda self, value: self._nick.set(value))
</code></pre>
<p>Here is <code>UserDbObject</code>:</p>
<pre><code>class UserDbObject(DbObject):
DbObjectName = DB_OBJECT_NAME
@classmethod
def _TypeInit(cls):
super(cls, cls)._TypeInit()
cls.Nicks = HashDbField(cls.DbObjectName, None, R_NICKS, cls._SelfDbObjectSerializator, nameSerializator=IgnoreCaseSerializator)
cls.Emails = HashDbField(cls.DbObjectName, None, R_EMAILS, cls._SelfDbObjectSerializator, nameSerializator=IgnoreCaseSerializator)
cls.AuthKeys = HashDbField(cls.DbObjectName, None, R_AUTH_KEYS, cls._SelfDbObjectSerializator)
cls.LastLoginDates = SortedSetDbField(cls.DbObjectName, None, R_LAST_LOGIN_DATES, cls._SelfDbObjectSerializator, DateTimeSerializator)
cls.LastActiveDates = SortedSetDbField(cls.DbObjectName, None, R_LAST_ACTIVE_DATES, cls._SelfDbObjectSerializator, DateTimeSerializator)
@classmethod
def Create(cls, nick, email, password, name, surname):
assert nick
assert email
assert password
userDbObject = super(UserDbObject, cls).Create()
def setRefFields():
if not userDbObject.nick.set(nick): return False
if not userDbObject.email.set(email): return False
return True
if not setRefFields():
userDbObject.delete()
return None
userDbObject.generateNewAuthKey()
userDbObject.setPassword(password)
if name: userDbObject.name.set(name)
if surname: userDbObject.surname.set(surname)
return userDbObject
@classmethod
def Get(cls, dbObjectId=None, nick=None, email=None, authKey=None):
if dbObjectId:
return super(UserDbObject, cls).Get(dbObjectId)
if nick:
return cls.Nicks.get(nick)
if email:
return cls.Emails.get(email)
if authKey:
return cls.AuthKeys.get(authKey)
return None
def setPassword(self, password):
salt = generateRandomKey(SALT_LENGTH)
self._passwordHash.set(countCoolHash(password, salt))
self._salt.set(salt)
def checkPassword(self, password):
return self._passwordHash.get() == countCoolHash(password, self._salt.get())
def generateNewAuthKey(self):
while True:
if self.authKey.set(generateRandomKey(AUTH_KEY_LENGTH)): break
def __init__(self, dbObjectId):
super(UserDbObject, self).__init__(dbObjectId)
self.nick = RefValueDbField(self.DbObjectName, self._dbObjectId, F_NICK, self.Nicks, self)
self.email = RefValueDbField(self.DbObjectName, self._dbObjectId, F_EMAIL, self.Emails, self)
self.authKey = RefValueDbField(self.DbObjectName, self._dbObjectId, F_AUTH_KEY, self.AuthKeys, self)
self._passwordHash = ScalarDbField(self.DbObjectName, self._dbObjectId, F_PASSWORD_HASH)
self._salt = ScalarDbField(self.DbObjectName, self._dbObjectId, F_SALT)
self.name = ScalarDbField(self.DbObjectName, self._dbObjectId, F_NAME)
self.surname = ScalarDbField(self.DbObjectName, self._dbObjectId, F_SURNAME)
self.lastLoginDate = ScoreDbField(self.DbObjectName, self._dbObjectId, F_LAST_LOGIN_DATE, self.LastLoginDates, self, DateTimeSerializator)
self.lastActiveDate = ScoreDbField(self.DbObjectName, self._dbObjectId, F_LAST_ACTIVE_DATE, self.LastActiveDates, self, DateTimeSerializator)
self.posts = SortedSetDbField(self.DbObjectName, self._dbObjectId, F_POSTS, self._PostDbObjectSerializator, DateTimeSerializator)
self.followers = SortedSetDbField(self.DbObjectName, self._dbObjectId, F_FOLLOWERS, self._UserDbObjectSerializator, DateTimeSerializator)
self.followingUsers = SortedSetDbField(self.DbObjectName, self._dbObjectId, F_FOLLOWING_USERS, self._UserDbObjectSerializator, DateTimeSerializator)
self.feed = SortedSetDbField(self.DbObjectName, self._dbObjectId, F_FEED, self._PostDbObjectSerializator, DateTimeSerializator)
</code></pre>
<p>How can you help me improve this code? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-15T03:23:47.503",
"Id": "32886",
"Score": "0",
"body": "While we're on the topic of being as pythonic as possible, [PEP-8](http://www.python.org/dev/peps/pep-0008/) recommends lowercase function names with underscores. So `SortedSetDbField.get_score` and `UserDbObject.create`."
}
] |
[
{
"body": "<p>Woah, that's a lot of code.</p>\n\n<p>In Python 3, you can do replace <code>super(DbObjectType, cls)</code> by <code>super()</code>.</p>\n\n<p>Instead of</p>\n\n<pre><code>if not cls._Reg_raw.contains(dbObjectId): return None\n\nreturn cls(dbObjectId)\n</code></pre>\n\n<p>You could do that</p>\n\n<pre><code>if cls._Reg_raw.contains(dbObjectId):\n return cls(dbObjectId)\n</code></pre>\n\n<p>Because Python automatically return None if nothing is returned.\n(Or <code>return None</code> can be changed to <code>return</code> but it's not important)</p>\n\n<p>Instead of using old %-formatting style for strings, you should start using <code>str.format</code> which is preferred since 2.6, like I stated it <a href=\"https://stackoverflow.com/questions/9587560/typeerror-unsupported-operand-types-for-int-and-str/9588046#9588046\">here</a>.</p>\n\n<p>Comparing types is bad so this <code>if type(self) != type(other):</code> is bad.\n<em>At least</em> you should do <code>if not isinstance(self, type(other)):</code> or something along these lines.</p>\n\n<p>Just FYI (just in case you or someone else didn't know), <code>property</code> can be used as a decorator too: <a href=\"http://docs.python.org/3/library/functions.html#property\" rel=\"nofollow noreferrer\">property in Python doc</a> .</p>\n\n<p>Also check <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> for proper naming conventions (how you should name your variables, methods, etc) as raylu said in comment of your question.</p>\n\n<p>I must admit I didn't really analyze how your code works or what does it do: TL;DR.\nI just looked for some piece of code I know could have some minor amelioration to make it more Pythonic.</p>\n\n<p>And I don't know Redis.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T02:53:19.420",
"Id": "26186",
"ParentId": "20175",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T09:17:17.347",
"Id": "20175",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"database",
"redis"
],
"Title": "Model for web applications"
}
|
20175
|
<pre><code>private function getFeatureByParam ($classname, $module, $action) {
$needFeature = array();
foreach ($this->featureConf as $featureIndex => $feature) {
if ($feature['classname'] == $classname &&
$feature['module'] == $module &&
$feature['action'] == $action) {
$needFeature = $feature;
break;
}
}
return $needFeature;
}
private function getFeatureByParam ($classname, $module, $action) {
foreach ($this->featureConf as $featureIndex => $feature) {
if ($feature['classname'] == $classname &&
$feature['module'] == $module &&
$feature['action'] == $action) {
return $feature;
}
}
return array();
}
</code></pre>
<p>The first style of writing is more understandability.</p>
<p>The second style of writing is more clean and efficient.</p>
<p>But witch one is more better? (Or they are too bad....)</p>
|
[] |
[
{
"body": "<p>Personally, option 2.</p>\n\n<p>In option 1, by breaking out of the loop, you have to look down until after the end to see what happens, just to see a return.\nIn option 2, it's obvious what you want and when you get it. Although, I think the condition is a little complex.</p>\n\n<p>There are, of course, other options:</p>\n\n<pre><code>private function getFeatureByParam ($classname, $module, $action) {\n foreach ($this->featureConf as $featureIndex => $feature) {\n if ($feature['classname'] != $classname) continue;\n if ($feature['module'] != $module) continue;\n if ($feature['action'] != $action) continue;\n\n return $feature;\n }\n return array();\n}\n\nprivate function getFeatureByParam ($classname, $module, $action) {\n foreach ($this->featureConf as $featureIndex => $feature) {\n if ( featureMatches( $feature, $classname, $module, $action ) ) {\n return $feature;\n }\n }\n return array();\n}\n</code></pre>\n\n<p>I'm inclined to option 4 :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T07:07:32.813",
"Id": "32296",
"Score": "0",
"body": "Wow,i had never thought the writing style of option 4. It is more clean and packaging the matching operation.Thank you very much~"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T17:44:16.090",
"Id": "32377",
"Score": "0",
"body": "My only issue with this answer is your braceless syntax. But that is more of a point of preference."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T20:13:46.827",
"Id": "32381",
"Score": "0",
"body": "I only have braceless when it's a precondition-style break, continue, or return. Anything else gets one - it's too dangerous not to."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T17:55:10.550",
"Id": "20188",
"ParentId": "20177",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "20188",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T10:03:16.407",
"Id": "20177",
"Score": "1",
"Tags": [
"php"
],
"Title": "A puzzle about how to write more clean and understandability code"
}
|
20177
|
<p>I am trying to use Entity Framework as simple as posible. Use UnitOfWork and Repository patterns seems to be overkill because whole web application will be pretty straightforward. I came with this idea:</p>
<pre><code>public class Entity
{
...
}
public class MyContext : DbContext
{
//Set database connection details here.
public DbSet<Entity> Entities{ get; set; }
}
</code></pre>
<p>Register DBContext with my implementation:</p>
<pre><code>public class PersistenceInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(Component.For<DbContext>()
.ImplementedBy<MyContext>()
.LifestylePerWebRequest()
);
}
}
</code></pre>
<p>And finally I am using DBContext in controller this way:</p>
<pre><code>public class HomeController : Controller
{
private DbContext db;
public HomeController(DbContext db)
{
this.db = db;
}
public ActionResult Index()
{
var entity = new Entity
{
//Set properties here.
};
db.Set<Entity>().Add(entity);
db.SaveChanges();
return View();
}
}
</code></pre>
<p>Is this correct approach? Could there be any memory leaks or potential DBContext lifetime management problems? Could there be any problem with too many database connections opened?</p>
<p>I would say that this could be correct. From my quick testing it looks like it is working even when I need to use DBContext in component which is then used in controller. So DBContext instance will be shared for everything per one request. Which is the way how it should be used, I guess.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T12:11:17.933",
"Id": "32342",
"Score": "0",
"body": "IMO you should'nt depend on DbContext. DbContext is plumbing to supply your own MyContext with underlying functionality. It's not an interface to use throughout your code."
}
] |
[
{
"body": "<p>You're doing it right - <em>per-request</em> lifestyle is exactly what you need, and you got it; this ensures your favorite IoC container disposes your context at the end of each request, and serves a new instance at each new one.</p>\n\n<p>One thing bothers me though, and it's not about your code:</p>\n\n<blockquote>\n <p>Use UnitOfWork and Repository patterns seems to be overkill because whole web application will be pretty straightforward.</p>\n</blockquote>\n\n<p>You're using <strong>Entity Framework</strong>. <code>DbContext</code>, with its <code>DbSet<T></code>'s, <strong>is</strong> a unit-of-work/repository pattern implementation. Some will argue it's <em>done wrong</em> and it's their right to be religious about a design pattern. The point is that <em>if you use it correctly, a DbContext is a perfectly acceptable unit of work</em>, especially if you're looking to <em>get the damn thing done</em> and in-line with KISS. Just make sure you call <code>SaveChanges()</code> as little as possible - once per request, i.e. once per instance.</p>\n\n<p>If you're worried about db connections, open up your favorite SQL profiler against your database server instance, and see for yourself!</p>\n\n<p>Bottomline, a <code>DbContext</code> is an abstraction layer over lots, <em>lots</em> of plumbing already. Abstracting it is often over-the-top, unless you wish to decouple your data layer from the rest of your app (say, swap EF for NHibernate).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-18T00:48:08.630",
"Id": "170968",
"Score": "0",
"body": "I love the bit about UoW and repositories - helped me to justify not using a pointless abstraction in a simple CRUD app when DbContext already does most of what you need!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-05T19:55:46.823",
"Id": "195458",
"Score": "0",
"body": "Old answer, hope you see this and can answer. I'm curious if your advice to call SaveChanges as little as possible is a recommended best practice, and if so could you find a/some links explaining why? My googling has turned up nothing, but a team member is really insisting this is best practice. Also, this best practice has to be weighed when you're using transactions (may need to read something you've updated before you commit). Also also, I'm only concerned about EF6 and onwards, just for context (e.g. this may have changed with EF6). Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-01T16:16:09.977",
"Id": "201518",
"Score": "1",
"body": "here is my 2c. My understanding of UoW is that an entire web request is considered a single unit, i.e. everything must succeed and be saved OR nothing must be saved (i.e. rolled back). In the case were 1 web request results in multiple calls to the db, calling SaveChanges once will be ideal, so that if a failure occurs, all queries will be rolled back. If you have multiple 'SaveChanges', you could end up with a scenario where half the queries are committed to the database, and the other half are rolled back (this is undesirable IMO).i cannot find any implementation with a single SaveChanges"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-17T21:07:25.013",
"Id": "211866",
"Score": "0",
"body": "We have an application where we need to perform multiple saves and use the data further downstream. But we also need it to be transactional. You can achieve that by wrapping multiple context instantiations and SaveChanges() in a TransactionScope (with a using statement)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T01:12:50.407",
"Id": "35653",
"ParentId": "20179",
"Score": "20"
}
}
] |
{
"AcceptedAnswerId": "35653",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T14:13:52.990",
"Id": "20179",
"Score": "20",
"Tags": [
"c#",
"asp.net-mvc-3",
"entity-framework"
],
"Title": "Correct usage of EF's DBContext in ASP.NET MVC application with Castle Windsor"
}
|
20179
|
<p>I created a program to find the largest prime factor for a given number. The program works but unfortunately takes very long time to compute a huge number like 600851475143. </p>
<p>How can I optimise this program to run faster?</p>
<p>I don't know what does this multicore thing is, but I think it is a possible way to improve this program.</p>
<pre><code>// A program to find the largest prime factor for a given number
#include <iostream>
#include <math.h>
using namespace std;
bool IsPrime (int n) {
if (n < 2) return false;
if (n < 4) return true;
if (n % 2 == 0) return false;
for (int i = 3; i <= int(sqrt(n)) + 1; i += 2)
if (n % i == 0)
return false;
return true;
}
int main () {
long long x;
int lpf = 0; //Largest Prime Factor
cin >> x;
for (int n = 0; n <= x; n++)
if (IsPrime(n) && x % n == 0)
lpf = n;
cout << lpf;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T15:36:59.293",
"Id": "32309",
"Score": "0",
"body": "You have optimised your loop by jumping by 2. There is another small improvement that you increment alternatively by 2 and 4. This is the equivalent of removing multiples of 2 and 3 from all tests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T19:16:47.923",
"Id": "32321",
"Score": "0",
"body": "Consider improving question title. It doesn't apply to any techniques that's related with \"for\" loop optimization (nothing related with rewinding or skipping proved conditions with inlining or anything else). My suggestion is \"Largest prime factor algorithm review\""
}
] |
[
{
"body": "<p>First, a couple of suggestions:</p>\n\n<ul>\n<li>If you're using <code><iostream></code>, you might as well use <code>#include <cmath></code> instead of <code>#include <math.h></code>, for consistency if nothing else.</li>\n<li>avoid <code>using namespace std;</code>, it's not worth the loss of readability for saving a couple of instances of <code>std::</code>.</li>\n<li>You already test for 3 (<code>< 4</code>), so why not start your loop from 5?</li>\n<li>Use <code>{}</code> for your loops, even if the content is a single statement. I'm happy enough with the IsPrime <code>if</code>s seeing as they're essentially early-exit preconditions, but anything else should have them as well.</li>\n</ul>\n\n<p>In terms of your algorithm, the biggest issue is that you \"forget\" which are prime numbers for each iteration of the (outer) loop, meaning that you have to work them out every time.</p>\n\n<p>What you could do is to build up a (descending) list of primes previously seen, then check whether each list number is a factor of the current value - if the list is descending, then a match is automatically the LPF. That will give you a much smaller searchspace.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T19:35:48.107",
"Id": "32272",
"Score": "0",
"body": "Thank you for your suggestions. I found that changing the main function to the following helped speeding up the program execution: `int main(){\n \n long long x;\n cin >> x;\n long long lpf = 0;//Largest Prime Factor\n for (long long n = 3; n*n <= x; n++)\n if (IsPrime(n) && x%n == 0)\n lpf = n;\n \n cout << lpf;\n \n}`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T16:35:37.687",
"Id": "20186",
"ParentId": "20180",
"Score": "3"
}
},
{
"body": "<p>As it was already pointed out, in <em>C++</em> you should be including <code>cmath</code> instead of <code>math.h</code>.</p>\n\n<p>The following two checks are bad for performance:</p>\n\n<pre><code>if (n < 2) return false;\nif (n < 4) return true;\n</code></pre>\n\n<p>They will incur in two comparisons that would only <em>return</em> if there was very very little work to do. So its optimizing the already fast cases, and adding work to the already lengthy cases. On the other hand, this check is ok:</p>\n\n<pre><code>if (n % 2 == 0) return false;\n</code></pre>\n\n<p>Moving to your <em>loop</em>, there is no need to calculate <code>sqrt(n)</code> each iteration. You could instead do:</p>\n\n<pre><code>for (int i = 3, top = int(sqrt(n)) + 1; i <= top; i += 2)\n ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T18:34:53.737",
"Id": "32270",
"Score": "0",
"body": "For the two if statements, I don't have much to do with. I edited my for loop as you pointed out. Thank you very much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T15:35:18.593",
"Id": "32308",
"Score": "0",
"body": "Pulling the sqrt(n) out of the test will be unlikely to help. compilers can do that optimization quite well already."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T15:48:12.790",
"Id": "32311",
"Score": "2",
"body": "@Loki Astari: The fact that the compiler can optimize it is no reason to be lazy and express the incorrect intention. Plus, what makes you think this typical homework assignment is being compiled on anything modern? I wouldn't dare go around telling people compilers can figure out externally declared functions produce no side-effects so they can reorder your code and do once what you asked it to do N-times... it doesn't hold for the general case. Eventually this could be changed to work with a 3rd party library for very big numbers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T16:11:32.547",
"Id": "32312",
"Score": "0",
"body": "@K-ballo: I disagree that it is the lazy option. I put it to you that this is the most intuitive version to read and thus should be the default way to write it. Peephole optimizations (done by a human) like this should only be done when you can show that it is sub-optimal and that mangling the code does actual get you an improvement. Also when you do it you should also write a huge comment explaining why you have made the code look messey otherwise somedy will come along and tidy it up after you thus destroying the optimization."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T16:14:31.870",
"Id": "32313",
"Score": "0",
"body": "The rule is intuitive easy to write **first**. Optimize if you have to and **only when you can prove it** and then comment on it. Otherwise the maintenance processes will likely break."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T16:41:57.757",
"Id": "32371",
"Score": "1",
"body": "@LokiAstari: I share your opinion in general, but not for this particular case. Those are two different codes, asking the compiler to do two different things, with different complexity guarantees. They are not conceptually the same thing, even if the optimizer generates the same code for both."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T07:06:46.137",
"Id": "32406",
"Score": "0",
"body": "@K-ballo, by definition optimization is the process when you do not change behavior from functional requirements perspective. So (even with moving focus to `IsPrime` function) both loops have the same intention \"loop to estimation of maximum probable factor of assumed composite number\". BTW, I don't see the reason why `+1` is done. I thought that `sqrt(n)` is upper including boundary (i.e. `sqrt(16)+1 = 5` can't be the factor of `16`, only `4` can) and if upper boundary is fractional it can be replaced by the closest int not bigger than it (`ceil(sqrt(n))`, i.e. `float` to `int` conversion)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T18:05:12.000",
"Id": "20189",
"ParentId": "20180",
"Score": "4"
}
},
{
"body": "<p>You have done the optimization of removing multiples of 2 (by incrementing by 2).</p>\n\n<p>There is another slight improvement that removes multiples of 2 and 3 from the test.</p>\n\n<pre><code>bool IsPrime (int n) {\n if (n == 2) return true;\n if (n == 3) return true;\n if (n < 5) return false;\n if (n % 2 == 0) return false;\n if (n % 3 == 0) return false;\n\n int inc = 4;\n int dec = -2;\n for (int i = 5; i <= int(sqrt(n)) + 1; i += inc)\n {\n if (n % i == 0)\n return false;\n inc = inc + dec; // makes inc go 2/4/2/4/2/4/.....\n dec = dec * -1;\n }\n return true;\n}\n</code></pre>\n\n<p>Another optimization for IsPrime() is that you only need to test using primes. ie no pointing in testing with 6 (its not prime) as all values that are divisible by 6 are also divisible by 3 (is prime). So if your loop only tested by using other primes:</p>\n\n<pre><code>// Assumes you are calling this function with monotimically inreassing\n// values of n so that the `foundPrimes` vector will be constructed in order.\nbool IsPrime (int n) {\n\n static std::vector<int> foundPrimes = { 2, 3, 5, 7, 11 };\n\n for(std::size_t loop = 0; loop < foundPrimes.size(); ++loop)\n {\n if (n == foundPrimes[loop]) { return true;}\n if (n % foundPrimes[loop] == 0) { return false;}\n }\n start = foundPrimes.last() + 2;\n\n for (int i = start; i <= int(sqrt(n)) + 1; i += 2)\n {\n if (n % i == 0)\n return false;\n }\n foundPrimes.push_back(n);\n return true;\n}\n</code></pre>\n\n<p>The next optimization is called the <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\">Sieve of Eratosthenes</a>. This needs a minor re-write but is very efficient. You would use the sieve to calculate all the primes you need first. Then just look up the values be checking if they are in the sieve.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T19:08:49.073",
"Id": "32319",
"Score": "0",
"body": "Last one have error. Consider that `IsPrime(6857); IsPrime(12);`. After storing prime number `6857` you'll start from `6857+5` and thus everything beetween `11` and `6857` will be considered as a prime numbers. As for the first one - I don't know such approach at all and have no idea how it works. Isn't it much easier to just jump in `+6` (skipping all divisors of `2` and `3`). It would be great to hear how that works."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T19:14:05.550",
"Id": "32320",
"Score": "0",
"body": "If first one is variant of [wheel factorization](http://en.wikipedia.org/wiki/Wheel_factorization) please confirm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T03:28:09.400",
"Id": "32329",
"Score": "1",
"body": "@ony: There is no error in the second one. You forgot to read the comments (Assumes you are calling this function with monotonically increasing values). In the first one skipping +6 is not the same. Its a standard optimization for prime: This might explaining it better http://codereview.stackexchange.com/a/7342/507"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T03:34:48.813",
"Id": "32330",
"Score": "0",
"body": "@ony: I don't think it is wheel factorization. As that requires you to use another method to build a set of primes first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T09:24:17.793",
"Id": "32337",
"Score": "0",
"body": "not only monotonically but also without gaps. Consider then `IsPrime(6857) == true; IsPrime(28561 /* 13^4 */) == true;` (`6857, 28561` is monotonically increasing and 13^3 < 6857). Look at the algorithm of wheel factorization it will for analyzing only sequence of `5, 7, 11, 13, 17, 19, 23, 25, 29, 31` - exactly the same as that loop does. You simply change the way you represent wheel addition your wheel is `6` and the only `2` sectors in that wheel may contain primes starting from `5`. Distances between those sectors are `+2` and `+4` which is what that loop does (adds `5` `+2, +4, +2, +4`)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T15:58:28.970",
"Id": "20210",
"ParentId": "20180",
"Score": "6"
}
},
{
"body": "<p>You could use different approach of searching LPF in a single pass (with <code>O(sqrt(n))</code>).</p>\n\n<ul>\n<li>assume your current <code>x</code> as a potential last prime number</li>\n<li>loop <code>n</code> through number <code>2</code> up while your current <code>x</code> is greater</li>\n<li>if you found some <code>n</code> that is factor of <code>x</code> divide your <code>x</code> at it as much as you can.\n<ul>\n<li>if by some reason everything is left from <code>x</code> is <code>1</code> than that <code>n</code> is the largest prime factor</li>\n<li>otherwise you've got your new assumption about largest prime number and continue reducing it through cycle</li>\n</ul></li>\n<li>if you've reached situation when <code>n</code> is larger than <code>x</code> (which is greter than <code>1</code>) then your <code>x</code> is actually the largest prime factor of your original <code>x</code></li>\n</ul>\n\n<p>Sample:\n</p>\n\n<pre><code>#include <iostream>\n#include <cstdlib>\nlong long lpf(long long x) {\n long long n;\n // since x changes anyway I think it's better to use n*n instead of sqrt\n for(n = 2; (n*n) < x ; ++n)\n {\n if ((x%n) == 0)\n {\n x /= n;\n while((x%n) == 0) x /= n;\n if (x == 1) return n;\n }\n }\n return x;\n}\nint main(int argc, char *argv[]) {\n if (argc < 2) return 1;\n long long x = atoll(argv[1]);\n std::cout << \"x = \" << x << std::endl;\n std::cout << \"LPF(x) = \" << lpf(x) << std::endl;\n return 0;\n}\n</code></pre>\n\n<p>This is variation of <a href=\"http://en.wikipedia.org/wiki/Trial_division\" rel=\"nofollow\">Trivial division algorithm</a> without prime numbers at all. See <a href=\"http://en.wikipedia.org/wiki/Integer_factorization#Factoring_algorithms\" rel=\"nofollow\">Factoring algorithms</a> for some more.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-13T21:27:29.890",
"Id": "223279",
"Score": "0",
"body": "It's strange that this answer - which is the only valid answer in this topic (apart from the one by PassingStranger which came much later) - received so little attention (upvotes) from punters. All the other respondents 'optimised' irrelevant fluff and completely missed the boat..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T18:47:10.250",
"Id": "20212",
"ParentId": "20180",
"Score": "2"
}
},
{
"body": "<p>Hmm... Am I the only one who sees complexity of original algorithm nearly <code>O(n^2)</code> even with caching prime numbers in <code>IsPrime</code>? If you still want to stick with prime numbers for factoring consider building lazy primes list and walk over it rather than over integers (it also can be used for algorithm I've posted earlier).</p>\n\n<p>Long time ago I used this sinppet of code (with some fresh updates):</p>\n\n<pre><code>class Primes {\npublic:\n typedef unsigned int Num;\n typedef std::list<Num> list;\n typedef list::const_iterator iterator;\n\n static void init(size_t pagesz = 10)\n {\n page_size = pagesz;\n primes.clear();\n primes.push_back(2);\n primes.push_back(3);\n }\n\n static iterator begin() { return primes.begin(); }\n\n static Num next(iterator &i)\n {\n iterator j = i++;\n if (i == primes.end()) {\n Num x = primes.back();\n size_t k;\n for(x+=2,k=0;k<page_size;x+=2) {\n if (isPrime(x)) {\n primes.push_back(x);\n ++k;\n }\n }\n // move i through end()\n i = j;\n ++i;\n }\n return (*j);\n }\n\nprivate:\n static list primes;\n static size_t page_size;\n\n static bool isPrime(Num v)\n {\n for(iterator i = begin(); i != primes.end(); ++i) {\n const Num p = *i;\n if (p > v) return true;\n if ((v%p) == 0) return false;\n }\n return true;\n }\n};\n</code></pre>\n\n<p>P.S. wheel factorization with more factors than just <code>2</code> can also be used here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T12:25:33.190",
"Id": "20223",
"ParentId": "20180",
"Score": "1"
}
},
{
"body": "<p>Quick answer: Don't optimize IsPrime, optimize main.</p>\n\n<p>First short optimization is to swap </p>\n\n<pre><code>if (IsPrime(n) && x % n == 0) \n</code></pre>\n\n<p>for </p>\n\n<pre><code>if (x % n == 0 && IsPrime(n)) \n</code></pre>\n\n<p>That way you won't even run IsPrime most of the time.</p>\n\n<p>As for the for-loop, every optimization you are doing in IsPrime you should do to that loop.<br>\nThat means that you start with n = 2 as a special case and then only go through odd numbers.<br>\nIf you also used the method described in ony's answer, you could just copy the relevant parts from IsPrime and not call the function at all.</p>\n\n<p>Edit: Here's what it would look like if you put it all in main:</p>\n\n<pre><code>int main () {\n\n long long x;\n int lpf = 1; //Largest Prime Factor\n\n cin >> x;\n\n // Doing division by two separately.\n if (x % 2 == 0) {\n lpf = 2;\n do {\n x /= 2;\n } while (x % 2 == 0)\n }\n\n // The squareroot here allows us to stop when we are down to a single prime.\n for (int n = 3, end = (int)sqrt(x); n <= end; n += 2) {\n if (x % n == 0) {\n lpf = n;\n do {\n // This part will also guarantee that you won't get any composite divisors.\n x /= n;\n } while (x % n == 0)\n end = (int)sqrt(x);\n }\n }\n\n // This snippet will give you the largest prime unless it was caught earlier.\n if (x > 1)\n lpf = x;\n\n cout << lpf;\n}\n</code></pre>\n\n<p>In short, don't just use IsPrime.<br>\nUse the methods in it on the actual problem at hand.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-16T13:03:09.643",
"Id": "93743",
"ParentId": "20180",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T14:19:23.683",
"Id": "20180",
"Score": "6",
"Tags": [
"c++",
"primes"
],
"Title": "Largest prime factor for a given number"
}
|
20180
|
<p>If I create a brush like so</p>
<pre><code>HBRUSH hBrush = CreateSolidBrush(RGB(33, 33, 33));
</code></pre>
<p>and then later on, I want to change the color of the brush, how would I do this?<br>
I googled a bit and found out that creating a bunch of different brushes is not the way to go.</p>
<p>I was thinking that one possibility would be to just set <code>hBrush</code> to a new brush like so</p>
<pre><code>hBrush = CreateSolidBrush(RGB(0, 0, 0));
</code></pre>
<p>everytime I wanted to use a different color, but this seems suspiciously easy, and I'm pretty sure that this would hog resources or something.</p>
<p>Another - presumably bad - idea of mine, was to use the above method, but always use</p>
<pre><code>DeleteObject(hBrush);
</code></pre>
<p>immediately after drawing. I have no idea if this is the right way to do things or not. Any help would be greatly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T18:34:09.407",
"Id": "32269",
"Score": "0",
"body": "Who says creating a bunch of different brushes is not the way to go? You should avoid creating more brushes than needed, but you cannot change their colors once created so you will need to create at least as many as colors you want to use..."
}
] |
[
{
"body": "<p>Assume any Win32 call that returns a handle allocates a struct with <code>malloc</code>. And assume <code>DeleteObject</code> (<code>DestroyWindow</code> etc) frees allocated memory. you should call <code>DeleteObject</code> every time you creare a GDI object.</p>\n\n<p>Calling <code>CreateSolidBrush</code> twice, and losing the first handle without calling <code>Deleteobject</code> on it causes a resource leak.</p>\n\n<p>Since you are using C++ the correct way to do it is RAII. see <a href=\"http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization</a></p>\n\n<p>This site has a good tutorial with clear windows programming examples on the subject.\n<a href=\"http://www.relisoft.com/book/win/index.htm\" rel=\"nofollow\">http://www.relisoft.com/book/win/index.htm</a></p>\n\n<p>This is a good open source library (MIT licence), that you can use in your project directly. Or you can look at gdi.h in the source.\n<a href=\"http://win32-framework.sourceforge.net/index.htm\" rel=\"nofollow\">http://win32-framework.sourceforge.net/index.htm</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T07:30:39.830",
"Id": "32297",
"Score": "0",
"body": "Would \n`HBRUSH hBrush = CreateSolidBrush(RGB(0, 0, 0)); \nHBRUSH hBrOld = hBrush; \nhBrush = CreateSolidBrush(RGB(255, 0, 0)); \nDeleteObject(hBrOld);` \ncause a resource leak?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T14:46:27.710",
"Id": "32307",
"Score": "0",
"body": "Also, couldn't I just create one `HBRUSH`, and then everytime I wanted to change the color, I just called `DeleteObject()` and then `CreateSolidBrush()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T15:47:31.063",
"Id": "32310",
"Score": "0",
"body": "Like I said, code in the first comment is similar to this:\n\n`char * p;`\n\n`p = (char*) malloc(SIZE);`\n\n`char* pOld = p;`\n\n`p = (char*) malloc(SIZE);`\n\n`free(pOld);`\n\nwhich is equivalent to:\n\n`char * p;`\n\n`p = (char*) malloc(SIZE);` // CreateSolidBrush\n\n`free(p);` //DeleteObject\n\n`p = (char*) malloc(SIZE);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T14:20:05.287",
"Id": "32345",
"Score": "0",
"body": "Well.. yeah.. It is.. but does that mean I can use that method..? Also, in the second commment, I'm just allocating and freeing the memory, so there shouldn't be any memory leaks, right? So the second method is safe..?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T15:29:05.567",
"Id": "32354",
"Score": "0",
"body": "If you are writing C++ without exceptions disabled your code will not be safe.\n\nJust use plain C, then you can safely do C style resource management."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T18:15:51.657",
"Id": "20190",
"ParentId": "20181",
"Score": "2"
}
},
{
"body": "<p>Create a new brush for each color that you need, and delete them once you are done.</p>\n\n<p>A BrushCache class could be created. It could have this public function:\n HBRUSH GetColorBrush(COLORREF Color);</p>\n\n<p>And it could have a private std::set, storing the Color as the Key and the brush handle as the value.</p>\n\n<p>And also a destructor, calling DeleteObject for each of the brushes in the std::set.</p>\n\n<p>So you would create an instance of the BrushCache class, and call GetColorBrush everytime you need a color brush. Ex for blue: GetColorBrush(RGB(0, 0, 255));</p>\n\n<p>GetColorBrush would then first check if the set contains an item of Color. If yes, return it, else, create a new brush and store it in the set, then return it.</p>\n\n<p>The BrushCache destructor would destroy all your brushes.</p>\n\n<p>With this you could get a brush using one call, and not worry about creating / destroying them all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T20:10:41.687",
"Id": "20246",
"ParentId": "20181",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20190",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T14:47:30.677",
"Id": "20181",
"Score": "0",
"Tags": [
"c++",
"optimization",
"performance",
"windows",
"garbage-collection"
],
"Title": "Correct way of using HBRUSHes..?"
}
|
20181
|
<p>I have the following function that looks up a mathematical operation that can be applied to a Numeric sequence based on a String</p>
<pre><code>def getAction[T : Fractional]( op : String ) : Seq[T] => String =
op match {
case "add" => seq => seq.sum.toString
case "product" => seq => seq.product.toString
case "mean" => seq => {
implicit def intToFractional(i : Int) =
implicitly[Fractional[T]].fromInt(i);
(seq.sum / seq.length).toString
}
case "sqrt" => seq => seq.map(i => math.sqrt(i.toDouble)).toString
}
</code></pre>
<p>That works fine, except I would prefer to specify the type when applying the returned function rather than at the time or retrieval.</p>
<p>i.e. I want</p>
<pre><code>getAction("sqrt")[Double](Seq(4.0))
</code></pre>
<p>rather than</p>
<pre><code>getAction[Double]("sqrt")(Seq(4.0))
</code></pre>
<p>The only way I have found to do this is by defining a new class/trait with a generic context-bound apply.</p>
<pre><code>abstract class Action {
def apply[T : Fractional](seq : Seq[T]) : String
}
</code></pre>
<p><strong>Edit:</strong> Replaced with whole class rather than just the method because compilable solution was wanted.</p>
<pre><code>object Main extends App {
import scala.math.Fractional
import Fractional.Implicits._
import scala.language.implicitConversions
abstract class Action {
def apply[T : Fractional](seq : Seq[T]) : String
}
def getAction( op : String ) : Action =
op match {
case "add" =>
new Action {
def apply[T : Fractional](seq : Seq[T]) = seq.sum.toString
}
case "product" =>
new Action {
def apply[T : Fractional](seq : Seq[T]) = seq.product.toString
}
case "mean" =>
new Action {
def apply[T : Fractional](seq : Seq[T])= {
implicit def intToFractional(i : Int) =
implicitly[Fractional[T]].fromInt(i);
(seq.sum / seq.length).toString
}
}
case "sqrt" =>
new Action {
def apply[T : Fractional](seq : Seq[T]) =
seq.map(i => math.sqrt(i.toDouble)).toString
}
}
def getAction_v1[T : Fractional]( op : String ) : Seq[T] => String =
op match {
case "add" => seq => seq.sum.toString
case "product" => seq => seq.product.toString
case "mean" => seq => {
implicit def intToFractional(i : Int) =
implicitly[Fractional[T]].fromInt(i);
(seq.sum / seq.length).toString
}
case "sqrt" => seq => seq.map(i => math.sqrt(i.toDouble)).toString
}
}
</code></pre>
<p>However, this seems messy to be because of all the repeated anonymous class definitions and repeated type signatures. This makes the actual math operations less obvious than the first version.</p>
<p>Is there a better way?</p>
<p><strong>Edit:</strong> here is a simple test suite that shows execution of both versions
import org.scalatest.FunSuite</p>
<pre><code>import org.scalatest.FunSuite
class Tests extends FunSuite {
test("v1"){
val act = Main.getAction_v1[Double]("sqrt")
assert(act(Seq(4.0)) === "List(2.0)")
}
test("v2") {
val act = Main.getAction("sqrt")
assert(act[Double](Seq(4.0)) === "List(2.0)")
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T16:26:46.100",
"Id": "32260",
"Score": "0",
"body": "your code won't even compile as given..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T16:54:23.717",
"Id": "32261",
"Score": "0",
"body": "@Kim I have provided a more complete sample for the the second version. Maybe the imports will make a difference for you? It compliles fine for me on 2.10.0-RC5. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T17:03:26.420",
"Id": "32263",
"Score": "1",
"body": "`getAction[Double](\"sqrt\")(Seq(4.0))` still doesn't compile. However, `getAction[Double](\"sqrt\").apply(Seq(4.0))` does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T17:18:13.280",
"Id": "32266",
"Score": "0",
"body": "@Kim Huh, that its unexpected, inlining the result of getAction (see the TestSuite I added) is not safe. I guess now I need to research why that does not work. I my guess is that it wants to use `Seq(4.0)` as the implicit parameter. Thanks for pointing that out! I am just learning scala."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T20:55:05.350",
"Id": "32275",
"Score": "0",
"body": "Yes, that is indeed the reason."
}
] |
[
{
"body": "<p>How about not having to specify the type at all?</p>\n\n<pre><code>implicit class SeqWithAction[T:Fractional](seq:Seq[T]) {\n def getAction( op : String ) : String =\n op match {\n case \"add\" => seq.sum.toString\n case \"product\" => seq.product.toString\n case \"mean\" => {\n implicit def intToFractional(i : Int) =\n implicitly[Fractional[T]].fromInt(i);\n (seq.sum / seq.length).toString\n }\n case \"sqrt\" => seq.map(i => math.sqrt(i.toDouble)).toString\n }\n } \n}\nSeq(4.0).getAction(\"sqrt\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T17:20:10.700",
"Id": "32267",
"Score": "0",
"body": "I like the result with respect to reductin code. Would this be considered good form in Scala? I am coming from mainly a C# background, and there this would likely be considered an abuse of extention methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T20:53:20.887",
"Id": "32273",
"Score": "0",
"body": "I think this is quite common in Scala. It's okay as long as you put your implicits into a separate object so the user of your library can choose whether to import them or not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T20:54:30.123",
"Id": "32274",
"Score": "0",
"body": "You find this kind of thing a lot in DSLs, e.g. for testing."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T17:11:20.230",
"Id": "20187",
"ParentId": "20183",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20187",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T15:50:05.377",
"Id": "20183",
"Score": "4",
"Tags": [
"scala"
],
"Title": "Terser syntax for first-class functions needing a context bound"
}
|
20183
|
<p>I was thinking in a way of implementing a graph in such that would let find a minimum spanning tree.</p>
<p><strong>Graph.h</strong></p>
<pre><code>#ifndef GRAPH_H
#define GRAPH_H
#include <list>
#include <vector>
#include <utility>
#include <iostream>
#include <map>
#include <queue>
using namespace std;
template <class KeyType, class WeightType>
class Graph
{
public:
class Edge;
class Vertex;
typedef typename list<Vertex>::iterator VertexIt;
typedef typename list<Edge>::iterator EdgeIt;
class Vertex
{
friend class Graph;
Vertex(const KeyType& k);
bool addLink(const EdgeIt& e);
list<EdgeIt> incEdges;
KeyType key;
};
class Edge
{
friend class Graph;
Edge(const pair<VertexIt, VertexIt>& vp, const WeightType& w);
VertexIt adjVertexTo(const VertexIt& v);
pair<VertexIt, VertexIt> incVertices;
WeightType weight;
};
struct Link
{
Link(const pair<KeyType, KeyType>& kp, const WeightType& w);
pair<KeyType, KeyType> keyPair;
WeightType weight;
};
template <typename ItType> Graph(ItType lnBegin, const ItType& lnEnd);
~Graph();
bool addLink(const Link& ln);
VertexIt findVertex(const KeyType& k);
void dfs(const VertexIt& v, map<KeyType, bool>& visited);
void dfs();
void bfs();
list<Vertex> vertices;
list<Edge> edges;
};
#include "Graph.cpp"
#endif // GRAPH_H
</code></pre>
<p><strong>Graph.cpp</strong></p>
<pre><code>#ifndef GRAPH_CPP
#define GRAPH_CPP
#include "Graph.h"
using namespace std;
template <class KeyType, class WeightType>
template <typename ItType>
Graph<KeyType, WeightType>::Graph(ItType lnBegin, const ItType& lnEnd)
{
vertices.push_back(Vertex(lnBegin->keyPair.first));
cout << " Adding links:" << endl;
for (; lnBegin != lnEnd; ++lnBegin)
{
if (addLink(*lnBegin) == true)
{
cout << " Adding ";
}
else
{
cout << " Skiping ";
}
cout << lnBegin->keyPair.first
<< "<-" << lnBegin->weight << "->"
<< lnBegin->keyPair.second
<< endl;
}
}
template <class KeyType, class WeightType>
Graph<KeyType, WeightType>::~Graph()
{
//dtor
}
template <class KeyType, class WeightType>
bool Graph<KeyType, WeightType>::addLink(const Link& ln)
{
VertexIt fKey = findVertex(ln.keyPair.first);
VertexIt sKey = findVertex(ln.keyPair.second);
VertexIt missing = vertices.end();
if (fKey != missing || sKey != missing)
{
if (fKey == missing)
{
vertices.push_back(Vertex(ln.keyPair.first));
fKey = --vertices.end();
}
if (sKey == missing)
{
vertices.push_back(Vertex(ln.keyPair.second));
sKey = --vertices.end();
}
edges.push_back(Edge(make_pair(fKey, sKey), ln.weight));
fKey->addLink(--edges.end());
sKey->addLink(--edges.end());
return true;
}
return false;
}
template <class KeyType, class WeightType>
typename Graph<KeyType, WeightType>::VertexIt
Graph<KeyType, WeightType>::findVertex(const KeyType& k)
{
VertexIt it = vertices.begin();
VertexIt itEnd = vertices.end();
for (; it != itEnd; ++it)
{
if (it->key == k)
{
return it;
}
}
return itEnd;
}
template <class KeyType, class WeightType>
Graph<KeyType, WeightType>::Vertex::Vertex(const KeyType& k)
{
key = k;
}
template <class KeyType, class WeightType>
bool Graph<KeyType, WeightType>::Vertex::addLink(const EdgeIt& e)
{
incEdges.push_back(e);
return true;
}
template <class KeyType, class WeightType>
Graph<KeyType, WeightType>::Edge::Edge(const pair<VertexIt, VertexIt>& vp, const WeightType& w) :
incVertices(vp), weight(w) { }
template <class KeyType, class WeightType>
Graph<KeyType, WeightType>::Link::Link(const pair<KeyType, KeyType>& kp, const WeightType& w) :
keyPair(kp), weight(w) { }
template <class KeyType, class WeightType>
typename Graph<KeyType, WeightType>::VertexIt
Graph<KeyType, WeightType>::Edge::adjVertexTo(const VertexIt& v)
{
if (incVertices.first == v)
{
return incVertices.second;
}
return incVertices.first;
}
template <class KeyType, class WeightType>
void Graph<KeyType, WeightType>::dfs()
{
map<KeyType, bool> visited;
dfs(vertices.begin(), visited);
}
template <class KeyType, class WeightType>
void Graph<KeyType, WeightType>::dfs(const VertexIt& v, map<KeyType, bool>& visited)
{
visited[v->key] = true;
cout << " " << v->key;
typename list<EdgeIt>::iterator it = v->incEdges.begin();
typename list<EdgeIt>::iterator itEnd = v->incEdges.end();
for (; it != itEnd; ++it)
{
VertexIt w = (*it)->adjVertexTo(v);
if (!visited[w->key])
{
dfs(w, visited);
}
}
}
template <class KeyType, class WeightType>
void Graph<KeyType, WeightType>::bfs()
{
map<KeyType, bool> visited;
queue<VertexIt> q;
VertexIt v = vertices.begin();
q.push(v);
visited[v->key] = true;
cout << " " << v->key;
typename list<EdgeIt>::iterator it;
typename list<EdgeIt>::iterator itEnd;
while (!q.empty())
{
v = q.front();
q.pop();
it = v->incEdges.begin();
itEnd = v->incEdges.end();
for (; it != itEnd; ++it)
{
VertexIt w = (*it)->adjVertexTo(v);
if (!visited[w->key])
{
cout << " " << w->key;
q.push(w);
visited[w->key] = true;
}
}
}
}
#endif
</code></pre>
<p><strong>Test.cpp</strong></p>
<pre><code>#include <iostream>
#include "Graph.h"
using namespace std;
int main()
{
typedef Graph<char, int> Graph;
typedef Graph::Link Link;
vector<Link> links;
links.push_back(Link(make_pair('A', 'B'), 2));
links.push_back(Link(make_pair('A', 'C'), 2));
links.push_back(Link(make_pair('A', 'E'), 2));
links.push_back(Link(make_pair('B', 'D'), 7));
links.push_back(Link(make_pair('B', 'F'), 7));
links.push_back(Link(make_pair('C', 'G'), 7));
links.push_back(Link(make_pair('E', 'F'), 5));
Graph myGraph(links.begin(), links.end());
myGraph.dfs();
myGraph.bfs();
return 0;
}
</code></pre>
<p>Is this implementation appropriate for finding minimum spanning tree? Could it be better?</p>
|
[] |
[
{
"body": "<ul>\n<li>You can use <code>EdgeIt</code> and <code>VertexIt</code> instead of <code>Edge*</code> and <code>Vertex*</code></li>\n<li>Your algorithm might be turned into class that incrementally update MST while new links added and dropping off rest of edges that isn't improving MST.</li>\n<li>Consider adding lookup <code>std::map<KeyType, Vertex></code> or better <code>std::mapKeyType, Vertexes::iterator></code> to get faster <code>findVertex</code></li>\n<li>Is there any reason why ctor requires <code>const std::vector<Link> &</code> as a source of links? You can use here any collection which you can iterate. Consider taking template iterator begin and end. That will allow you to use:</li>\n</ul>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>Link a[4];\nstd::list<Link> b;\nstd::vector<Link> c;\nGraph ga(a, a + 4);\nGraph gb(b.begin(), b.end());\nGraph gc(c.begin(), c.end());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-16T22:42:03.633",
"Id": "33034",
"Score": "0",
"body": "Hi, thanks for the advices, I modified my code a little."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T20:41:31.053",
"Id": "20215",
"ParentId": "20184",
"Score": "1"
}
},
{
"body": "<p>A few tips:</p>\n\n<ul>\n<li>In Graph.h you <code>#include \"Graph.cpp\"</code>. You should never include an implementation file.</li>\n<li>In Graph.h you have <code>using namespace std</code>. You should never bring in namespaces in a header file (except in rare cases where you put it inside some other scope), otherwise you pollute the namespaces of everyone who <code>#include</code>s it</li>\n<li>In Graph.h <code>VertexIt findVertex(const KeyType& k)</code> should be private, otherwise anyone can mess with the vertex list inside of <code>Graph</code> without going through the interface</li>\n<li>In Graph.cpp, you don't need include guards - these are only needed in header files</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-17T21:10:38.203",
"Id": "20660",
"ParentId": "20184",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T15:54:30.267",
"Id": "20184",
"Score": "2",
"Tags": [
"c++",
"graph"
],
"Title": "Undirected, connected and weighted graph implementation"
}
|
20184
|
<p>I would like a review of how I am comparing two <code>java.util.String</code> in a private method in a <code>java.util.Comparator</code>. Either of the <code>String</code>s could be null or blank, and would be "less than" the other <code>String</code> if that other <code>String</code> were not null/blank.</p>
<p>My gut feeling is that this is at the very least inelegant, probably difficult to read, and at worst inefficient if it had to be done millions of times per second. Oh, and there could even be a flaw in the logic!</p>
<p>Is there a better way to do this?</p>
<pre><code>private Integer compareDateStrings(BeanToDoTask arg0, BeanToDoTask arg1, String strProperty) {
/* Don't worry too much about this part. */
String strDate0 = BeanUtils.getProperty(arg0, strProperty); _logger.debug("strDate0 = " + strDate0);
String strDate1 = BeanUtils.getProperty(arg1, strProperty); _logger.debug("strDate1 = " + strDate1);
/* If strDate0 is null or blank and strDate1 is not, then strDate1 is greater. */
if ((strDate0 == null || strDate0.equals(""))) {
if (strDate1 != null && !strDate1.equals("")) {
return -1;
} else {
/* They both are null or blank! */
return 0;
}
}
/* We know strDate0 is not null or blank. */
if (strDate1 == null || strDate1.equals("")) {
return 1;
}
/* At this point neither strDate0 or strDate1 are null or blank, so let's compare them. */
return strDate0.compareTo(strDate1);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-24T17:32:58.357",
"Id": "370493",
"Score": "0",
"body": "Is `Comparator.nullsFirst(String::compareTo).compare(date0, date1)` not sufficient?"
}
] |
[
{
"body": "<p>You could write the code like this, it is doing the same, but I think it is more readable, you almost don't need any comment, to assume the return value.</p>\n\n<pre><code>private Integer compareDateStrings(BeanToDoTask arg0, BeanToDoTask arg1, String strProperty) {\n String strDate0 = BeanUtils.getProperty(arg0, strProperty);_logger.debug(\"strDate0 = \" + strDate0);\n String strDate1 = BeanUtils.getProperty(arg1, strProperty);_logger.debug(\"strDate1 = \" + strDate1);\n return compareDateStrings(strDate0, strDate1);\n}\n\nprivate Integer compareDateStrings(String strDate0, String strDate1) {\n int cmp = 0;\n if (isEmpty(strDate0)) {\n if (isNotEmpty(strDate1)) {\n cmp = -1;\n } else {\n cmp = 0;\n }\n } else if (isEmpty(strDate1)) {\n cmp = 1;\n } else {\n cmp = strDate0.compareTo(strDate1);\n }\n return cmp;\n}\n\nprivate boolean isEmpty(String str) {\n return str == null || str.isEmpty();\n}\nprivate boolean isNotEmpty(String str) {\n return !isEmpty(str);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T00:45:20.707",
"Id": "32291",
"Score": "2",
"body": "This goes along the lines of what I would've done too. First of all, it's odd to have a method called `compareDateStrings` that doesn't actually take those date strings as its parameters. Then, the `a == null || a.equals(\"\")` is a repeating pattern that should be refactored into a more readable method of its own like @burna did here. I don't like the `isNotEmpty` method though, I'd just use `!isEmpty(...)`. Finally, you might want to take a look at this thread: http://stackoverflow.com/questions/481813/how-to-simplify-a-null-safe-compareto-implementation"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T20:21:49.777",
"Id": "32322",
"Score": "0",
"body": "@burna: That is indeed much more readable. We aren't supposed to say \"Thanks\" in Stack Exchange, so I'll just say \"Cheers\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T11:32:28.697",
"Id": "32413",
"Score": "0",
"body": "I suggest at least to avoid the isNotEmpty method. You could just switch the if and else case and continue using the isEmpty method."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T20:59:38.557",
"Id": "20195",
"ParentId": "20191",
"Score": "3"
}
},
{
"body": "<p>I would use boolean variables to make the code more readable:</p>\n\n<pre><code>private int compareDateStrings(BeanToDoTask arg0, BeanToDoTask arg1, String strProperty) {\n /* Don't worry too much about this part. */\n String strDate0 = BeanUtils.getProperty(arg0, strProperty); _logger.debug(\"strDate0 = \" + strDate0);\n String strDate1 = BeanUtils.getProperty(arg1, strProperty); _logger.debug(\"strDate1 = \" + strDate1);\n\n boolean isStrDate0Empty = (strDate0 == null || strDate0.isEmpty());\n boolean isStrDate1Empty = (strDate1 == null || strDate1.isEmpty());\n\n if (isStrDate0Empty && isStrDate1Empty)\n return 0;\n // at least one of them is not empty \n if (isStrDate0Empty)\n return -1;\n if (isStrDate1Empty)\n return 1;\n //none of them is empty\n return strDate0.compareTo(strDate1);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T13:45:09.737",
"Id": "32425",
"Score": "0",
"body": "+1 good idea to record once the null/empty evaluation in a boolean, and use it to scan/validate all result possibilities."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T11:30:59.710",
"Id": "20268",
"ParentId": "20191",
"Score": "6"
}
},
{
"body": "<p>Consider first testing if the strings point to the same object. You can drop the <code>caseSensitive</code> argument, this is directly from my <code>Util</code> class.</p>\n\n<pre><code>public static int compare(String s1, String s2, boolean caseSensitive) {\n if (s1 == s2) {\n return 0;\n } else if (s1 == null) {\n return -1;\n } else if (s2 == null) {\n return 1;\n } else {\n return caseSensitive?s1.compareTo(s2):s1.compareToIgnoreCase(s2);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T23:05:57.980",
"Id": "20303",
"ParentId": "20191",
"Score": "4"
}
},
{
"body": "<p>A simpler strategy is to just canonicalize your strings that you plan to compare, then let <code>compareTo()</code> do it's thing. In this case, turn null strings into the empty string.</p>\n\n<p>This code is untested, but conveys the idea.</p>\n\n<pre><code>private Integer compareDateStrings(BeanToDoTask arg0, BeanToDoTask arg1, String strProperty) {\n String strDate0 = getCanonicalProperty(arg0, strProperty); _logger.debug(\"strDate0 = \" + strDate0);\n String strDate1 = getCanonicalProperty(arg1, strProperty); _logger.debug(\"strDate1 = \" + strDate1);\n return strDate0.compareTo(strDate1); // neither strDateX can be null\n}\n\nprivate String getCanonicalProperty(BeanToDoTask arg, String strProperty) {\n String prop = BeanUtils.getProperty(arg, strProperty);\n return ( null == prop ) ? \"\" : prop;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-24T16:52:05.233",
"Id": "192851",
"ParentId": "20191",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20195",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T18:24:13.973",
"Id": "20191",
"Score": "5",
"Tags": [
"java"
],
"Title": "Comparing two Strings which could be null or blank in a Comparator"
}
|
20191
|
<p>I tried to implement an answer for the algorithm question given below. I implemented two different solutions. I couldn't decide which one is better. ( Maybe none )</p>
<p>Note: Node class and ZigZag interface are given along with the question.</p>
<p><strong>Problem Definition</strong> A binary tree is given. Return a list of nodes in Zig Zag manner. state the Big-O runtime and space complexity of your implementation.</p>
<pre><code>import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
import java.util.Stack;
import java.util.Queue;
import java.util.Collections;
/**
* Print a binary tree in zig zag way... that is:
* ......a.........
* ....b....c.......
* ..d...e...f...g..
* .h.i.j.k.l.m.n.o.
*
* should be printed as a-c-b-d-e-f-g-o-n-m-l-k-j-i-h
*
* what data structure will u use for that?
*
*/
public class BinaryZigZagTraversal {
/* ------------------------------------------------------------- */
/* DATA DEFINITION(S) */
/* ------------------------------------------------------------- */
/**
* ZigZag interface instance
*/
private ZigZag zigZagInstance;
/**
* Tree node
*
*/
public class Node {
private int value;
private Node left;
private Node right;
public Node(int value, Node left, Node right) {
this.value = value;
this.left = left;
this.right = right;
}
public int getValue() {
return this.value;
}
public Node getLeft() {
return this.left;
}
public Node getRight() {
return this.right;
}
protected void setLeft(Node leftNode) {
this.left = leftNode;
}
protected void setRight(Node rightNode) {
this.right = rightNode;
}
@Override
public String toString() {
return String.valueOf( getValue() );
}
}
/**
* ZigZag interface
*
*/
public interface ZigZag {
public List<Node> GetZigZagOrder(Node rootNode);
}
/* ------------------------------------------------------------- */
/* SOLUTION- 1 */
/* ------------------------------------------------------------- */
/**
* My BFS-like Implementation
*
* @author ozkansari
*
* Total Time complexity: O(2n) -> n+n+(n/8)
* Total Space complexity: O(3n) -> size(bfsQueue) + size(resultList) + size(levelNodes)
*/
public class ZigZagBFSImpl implements ZigZag {
@Override
public List<Node> GetZigZagOrder(Node rootNode) {
Queue<Node> bfsQueue = new LinkedList<Node>();
List<Node> resultList = new ArrayList<Node>();
bfsQueue.add(rootNode);
int currentLevel = 1;
while(!bfsQueue.isEmpty()) {
// O(n)
// Remove all first
List<Node> levelNodes = new ArrayList<Node>();
while(!bfsQueue.isEmpty()) {
Node n = bfsQueue.remove();
levelNodes.add(n);
}
// O(n)
boolean hasChildNode = false;
for (Node currentNode : levelNodes) {
Node firstNode = currentNode.getLeft();
Node secondNode = currentNode.getRight();
if(firstNode!=null) {
bfsQueue.add( firstNode );
hasChildNode=true;
}
if(secondNode!=null) {
bfsQueue.add( secondNode );
hasChildNode=true;
}
}
// O(n/8)
if(currentLevel%2==0) {
Collections.reverse(levelNodes);
}
resultList.addAll(levelNodes);
if(hasChildNode) {
currentLevel++;
}
}
return resultList;
}
}
/* ------------------------------------------------------------- */
/* SOLUTION- 2 */
/* ------------------------------------------------------------- */
/**
* My ZigZag Implementation
*
* @author ozkansari
*
* Total Time complexity: O(n) -> n+n
* Total Space complexity: O(n) -> size(levels)
*/
public class ZigZagStackImpl implements ZigZag {
/**
* Map of stacks to represent tree levels
*/
Map<Integer,Stack<Node>> levels=new HashMap<Integer,Stack<Node>>();
@Override
public List<Node> GetZigZagOrder(Node rootNode) {
// Initialize next level
initLevels(rootNode, 1);
// Find result list
List<Node> resultList = new ArrayList<Node>();
for (int i=1; ; i++) {
Stack<Node> levelStack = levels.get(i);
if(levelStack==null) break;
while(!levelStack.empty()) {
Node currentNode = null;
if(i%2==0) { // right side
currentNode = levelStack.pop();
} else {
currentNode = levelStack.firstElement();
levelStack.remove(currentNode);
}
resultList.add(currentNode);
}
}
return resultList;
}
/**
* Helper recursive method
*
* @param currentNode
* @param currentLevel
*/
private void initLevels(Node currentNode, Integer levelIndex) {
if(levelIndex<=0) {
levelIndex=1;
}
// Initialize first root level if required
if(levelIndex==1){
Stack<Node> rootLevel = new Stack<Node>();
rootLevel.add(currentNode);
levels.put(1,rootLevel);
levelIndex=2;
}
Node leftNode = currentNode.getLeft();
Node rightNode = currentNode.getRight();
if(leftNode==null && rightNode==null) {
return;
}
Stack<Node> currentLevel = levels.get(levelIndex);
if(currentLevel==null) {
currentLevel = new Stack<Node>();
levels.put(levelIndex,currentLevel);
}
if(leftNode!=null) {
currentLevel.push(leftNode);
if(leftNode.getLeft()!=null || leftNode.getRight()!=null) {
initLevels(leftNode,levelIndex+1);
}
}
if(rightNode!=null) {
currentLevel.push(rightNode);
if(rightNode.getLeft()!=null || rightNode.getRight()!=null) {
initLevels(rightNode,levelIndex+1);
}
}
}
}
/**
*
* @return ZigZag instance
*/
public ZigZag getZigZagInstance(){
if(zigZagInstance==null) {
zigZagInstance = new ZigZagBFSImpl();
}
return zigZagInstance;
}
/* ------------------------------------------------------------- */
/* TEST METHOD(S) */
/* ------------------------------------------------------------- */
/**
* Main method to test the ZigZag coding sample.
* I actually prefer to test my code using JUnit but the result is requested to be in one file.
*
* @author ozkansari
*
*/
public String test(int nodeCount) {
ZigZag zigZagImpl = getZigZagInstance();
List<Node> zigZagOrderedList = zigZagImpl.GetZigZagOrder(generateDummyBinaryTree(nodeCount));
StringBuffer sbf = new StringBuffer();
for (Node node : zigZagOrderedList) {
sbf.append(node + " ");
}
System.out.println(sbf.toString());
return sbf.toString();
}
/**
* Generates a dummy binary tree and returns its root node
*
*/
private Node generateDummyBinaryTree(int nodeCount){
List<Node> sampleData = new ArrayList<Node>();
for(int i=1;i<=nodeCount;i++) {
Node currentNode = new Node(i,null,null);;
sampleData.add(currentNode);
}
int j=1;
for (Node node : sampleData) {
int index = j*2;
Node rightNode = index+1<=sampleData.size() ? sampleData.get(index) : null;
Node leftNode = index<=sampleData.size() ? sampleData.get(index-1) : null;
node.setRight(rightNode);
node.setLeft(leftNode);
j++;
}
return sampleData.get(0);
}
/**
* Main method to test my sample code.
*
* @param args
*/
public static void main(String[] args) {
BinaryZigZagTraversal z = new BinaryZigZagTraversal ();
System.out.println( z.test(1).equals("1 ") );
System.out.println( z.test(2).equals("1 2 ") );
System.out.println( z.test(4).equals("1 3 2 4 ") );
System.out.println( z.test(12).equals("1 3 2 4 5 6 7 12 11 10 9 8 ") );
System.out.println( z.test(16).equals("1 3 2 4 5 6 7 15 14 13 12 11 10 9 8 16 ") );
System.out.println( z.test(24).equals("1 3 2 4 5 6 7 15 14 13 12 11 10 9 8 16 17 18 19 20 21 22 23 24 ") );
}
</code></pre>
<p>}</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T10:03:43.073",
"Id": "32340",
"Score": "1",
"body": "Time and Space complexity is never stated as O(3n) or O(2n).\n\nO(a*n + b) = O(n)."
}
] |
[
{
"body": "<ol>\n<li>First of all you are not really using Queue and Stack in any specific way.</li>\n<li><p>The following :</p>\n\n<pre><code>currentNode = levelStack.firstElement();\nlevelStack.remove(currentNode);\n</code></pre>\n\n<p>can be more concisely expressed as:</p>\n\n<pre><code>currentNode = levelStack.remove(0);\n</code></pre></li>\n<li><p>In any case removing the first element of a <code>Stack</code> is slow.</p></li>\n<li><p>If you are going to remove elements from both ends of a list (as is the case with <code>levelStack</code>) you should use a <code>Deque</code>. LinkedList implements Deque. </p></li>\n<li><p>The following : </p>\n\n<pre><code>List<Node> levelNodes = new ArrayList<Node>();\nwhile(!bfsQueue.isEmpty()) {\n Node n = bfsQueue.remove();\n levelNodes.add(n);\n}\n</code></pre>\n\n<p>can be more concisely expressed as:</p>\n\n<pre><code>List<Node> levelNodes = new ArrayList<Node>(bfsQueue);\n</code></pre></li>\n<li><p>ZigZagBFSImpl is O(n), but ZigZagStackImpl is > O(n) (due to stack.remove(first-element) being O(stack-size))</p></li>\n<li><p>Generally avoid <code>StringBuffer</code> in favor of <code>StringBuilder</code> , because of synchronization overhead.</p></li>\n<li><p>Throw <code>IllegalArgumentException</code> for illegal arguments instead of continuing execution with unexpected behaviour :</p>\n\n<pre><code>if(levelIndex<=0) {\n levelIndex=1;\n}\n</code></pre></li>\n<li><p><code>Integer levelIndex</code> should be <code>int levelIndex</code> since passing in <code>null</code> causes an exception, and therefore not a valid argument.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T15:09:22.033",
"Id": "20227",
"ParentId": "20192",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20227",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T19:43:44.580",
"Id": "20192",
"Score": "3",
"Tags": [
"java",
"binary-search"
],
"Title": "Returning Binary Search Tree Nodes in Zig Zag manner"
}
|
20192
|
<p>I am a newbie to C++ programming and am currently reading this book called <em>Jumping to C++</em> by Alex Allain. I have finished the pointers chapter and I am doing the exercises at the end of the chapter.</p>
<p>The following paragraphs are the exercises and included are my own solutions:</p>
<blockquote>
<p>Write a function that prompts the user to enter his or her first name and last name, as two separate values. This function should
return both values to the caller via additional pointer (or reference)
parameters that are passed to the function. Try doing this first with
pointers and then with references. (Hint: the function signature will
look be similar to the swap function from earlier!)</p>
</blockquote>
<pre><code>// pointersExercise01.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
void printName(string *pointFirstName, string *pointLastName){
cout << endl << "Hello " << *pointFirstName << " " << *pointLastName;
}
void printName(string &pointFirstName, string &pointLastName){
cout << endl << "Hi " << pointFirstName << " " << pointLastName;
}
int _tmain(int argc, _TCHAR* argv[])
{
string firstName, lastName;
cout << "Enter First Name ";
cin >> firstName;
cout << endl << "Enter Last Name ";
cin >> lastName;
/*FUNCTION POINTERS*/
printName(&firstName, &lastName); // print out using pointers
/*REFERENCE POINTERS*/
printName(firstName, lastName);
system("pause");
return 0;
}
</code></pre>
<blockquote>
<p>The next exercise is to modify the program I wrote for exercise 1 so that instead of always prompting the user for a last name, it does
so only if the caller passes in a NULL pointer for the last name.</p>
</blockquote>
<pre><code>// nullPointerExercise3.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
#include "string"
using namespace std;
void userNames(string *pointerFirstName, string *pointerLastName){
string firstN = *pointerFirstName;
string LastN = *pointerLastName;
bool flag;
do{
if(LastN == "NULL" ){
cout << "Again what is your last name? ";
cin >> LastN;
flag = true;
}else{
flag = false;
}
}while(flag != false);
}
int _tmain(int argc, _TCHAR* argv[])
{
string firstName, lastName;
cout << "FIRSTNAME: ";
cin >> firstName;
cout << "\n" << "LASTNAME: ";
cin >> lastName;
userNames(&firstName, &lastName);
system("pause");
return 0;
}
</code></pre>
<p>If possible, I'd like to know if I did right for both of the exercise and if I am in the right direction. Comments and tips will be helpful.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T22:10:44.463",
"Id": "32276",
"Score": "1",
"body": "You are not implementing pointers, you are merely using them..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T22:16:40.333",
"Id": "32278",
"Score": "0",
"body": "Hi thanks for the comment, I don't quite get what your saying. can you please point out which are the flaws of my solutions, it will help me a lot to understand pointers much better."
}
] |
[
{
"body": "<p>I'm not sure whether this should be reviewed yet or not. I can't decide what critiques are things that you haven't learned yet but will, and things that you haven't learned yet and might not. (Also, there's a handful of errors that should have been found with basic testing.)</p>\n\n<p>Anyway here's a few things that jumped out at me:</p>\n\n<ul>\n<li>There's no notion of const correctness at all in your code</li>\n<li><code>system(\"pause\")</code> is bad -- it's slow, and implementation dependent\n<ul>\n<li>if you want to see the output, run it in a shell directly instead of using <code>system(\"pause\")</code> as a hack</li>\n</ul></li>\n<li>When <code>pointerLastName</code> is <code>NULL</code>, <code>string LastN = *pointerLastName;</code> is undefined behavior and will probably crash.</li>\n<li><code>if(LastN == \"NULL\" )</code> makes no sense\n<ul>\n<li>a <code>NULL</code> pointer being dereferences does not turn into the string <code>\"NULL\"</code> -- it crashes (typically)</li>\n</ul></li>\n<li>Your <code>do {} while()</code> loop in the second program is broken</li>\n<li><code>using namespace std;</code> pollutes the global namespace. It's typically better to just qualify it directly like <code>std::string</code> or import specific things <code>using std::string;</code>.\n<ul>\n<li>In small, simple programs, it tends to not matter. It can become a bad habit though.</li>\n<li><code>#include \"iostream\"</code> should be <code>#include <iostream></code> -- I'm actually a bit surprised that compiles.</li>\n</ul></li>\n</ul>\n\n<p>Also, for what it's worth, I wouldn't use pointers in either of these two programs. References are a better choice. Obviously this is a learning exercise though, so this critique doesn't really apply.</p>\n\n<hr>\n\n<p>Based on our comments back and forth, there seems to be some confusion surrounding pointers. I'm not sure if it's me misunderstanding what your saying, or a misunderstanding of pointers, but either way, I figure I'll elaborate a bit.</p>\n\n<pre><code>if(LastN == \"NULL\" )\n</code></pre>\n\n<p>That is checking if <code>LastN</code> is equal to the string <code>\"NULL\"</code>. That is not the same thing as checking for a NULL pointer:</p>\n\n<pre><code>string* pNullStr = NULL;\nstring nullStr = *pNullStr; //undefined behavior (almost certainly a crash)\n</code></pre>\n\n<p>The only way a string is going to have a value of NULL is if it is actually set to NULL:</p>\n\n<pre><code>string ns = \"NULL\";\nif (ns == \"NULL\") {\n //this will happen\n}\n</code></pre>\n\n<p>In other words, your <code>userNames</code> function isn't prompting the user for a last name only \"if the caller passes in a NULL pointer for the last name\" (as your instructions say). What it's doing is prompting for a last name only if the caller passes in a string (<em>not</em> a pointer to a string) equivalent to <code>\"NULL\"</code>.</p>\n\n<p>Based on your code, the only way a last name is going to be prompted for is if you type \"NULL\" in when prompted for a last name (in the <code>main</code> code).</p>\n\n<p>Perhaps this was by design, but it directly contradicts your exercise instructions.</p>\n\n<hr>\n\n<p>Also, while I'm at it with the editing, if you wanted to be really careful, you could check all of the input operations. In fact, really you should always check, but in a program this simple, it would be a bit of a pain.</p>\n\n<p>To clarify:</p>\n\n<pre><code>cout << \"FIRSTNAME: \";\ncin >> firstName;\n</code></pre>\n\n<p>That can fail. What if the user writes EOF or if the user pipes in an empty file? That means the read is going to fail.</p>\n\n<pre><code>if (!(std::cin >> firstName)) {\n std::cerr << \"Fatal error: reading last name failed\";\n return EXIT_FAILURE; //(defined in cstdlib)\n}\n</code></pre>\n\n<hr>\n\n<p>On a stylistic note, not sure why I didn't spot this before: if your loop in userNames is actually what you meant it to be, you can write it much more cleanly:</p>\n\n<pre><code>while (lastN == \"NULL\") {\n std::cout << \"Again what is your last name? \";\n std::cin >> lastN; //Once again, this should be checked\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T22:33:40.090",
"Id": "32280",
"Score": "0",
"body": "Hi thanks for the answer I'm using Visual C++ 2012, I notice that if I do not put in the 'system(\"pause\")' when I compile it the shell itself run for a 1 second then exits, very hard to see the output. I'd like to know why my do while loop broken."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T22:49:11.507",
"Id": "32282",
"Score": "0",
"body": "@Rojee You can navigate to the folder in a cmd prompt shell to execute it, and you can see the output without using pause. There may also be some kind of VS feature. Not sure. You might find: http://stackoverflow.com/questions/1107705/systempause-why-is-it-wrong helpful. As for why the do-while loop is wrong: it's more of the entire function is wrong. If pointerLastName is NULL as the exercise said, that function will crash. It actually won't ever be NULL though since the way it's called in main. (Or did you interpret the exercise to mean the string \"NULL\"? Maybe we read that differently.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T22:58:31.077",
"Id": "32283",
"Score": "0",
"body": "It says in the book that you should always initialize pointers or else the program crashes is it same as what your saying about NULL, I put in that NULL to test if the do while will actually work and am I reading an old tutorial or are there any newer versions out there which has new techniques and implementations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T23:02:46.287",
"Id": "32284",
"Score": "0",
"body": "It's perfectly fine from a technical perspective to not initialize a pointer. You just can't dereference a pointer that doesn't point to memory the program owns (and an unitialized pointer has an *extremely* low chance of that actaully magically working -- and non-determinism tends to be bad). From a best-practices point of view, it is widely standard to initialize a pointer to a known value (either NULL or to actually point to something). The issues are vaguely related, but not the same. Are you trying to test for a NULL pointer, or a string containing \"NULL\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T23:32:31.783",
"Id": "32286",
"Score": "0",
"body": "yes I'm trying to test a string containing NULL, I guess I need to read that chapter again so I can understand it much better, so far my knowledge about C++ isn't enough I need to learn it for my final project about network programming. thanks man."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T23:38:53.310",
"Id": "32288",
"Score": "0",
"body": "@Rojee Ah, in that case, your description was was: \" it does so only if the caller passes in a NULL pointer for the last name.\" A NULL pointer means a pointer with a value of NULL, not a pointer to a string with a value of NULL."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T23:49:19.153",
"Id": "32290",
"Score": "0",
"body": "yes because the pointer itself is a `string` type and I tried putting in `NULL` and it won't work, correct me if I'm wrong I think `NULL` only work with `int` type. here's a sample code snippet from the book: `int p_int = NULL;\n// code that might or might not set p_int\nif ( p_int != NULL )\n{\n*p_int = 2;\n}`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T05:10:47.207",
"Id": "32295",
"Score": "0",
"body": "@Rojee `p_int` in that example is not a pointer. It's an int being abused as a pointer. On systems where `sizeof(int) != sizeof(*int)` that will break (and even when not different sizes, it's not standard -- I don't think so anyway). I can't at the moment, but in a bit I'll edit the question to include a bit more information."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T22:16:18.450",
"Id": "32325",
"Score": "0",
"body": "@Rojee have expanded my answer a bit to elaborate on what I was saying. Also, have added a few things that I noticed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T09:23:27.763",
"Id": "32336",
"Score": "0",
"body": "thanks man for taking your time answering my question, I really appreciate it and I am learning a lot. Also, want to upvote your answer unfortunately my reputation is not over 15."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T09:46:50.113",
"Id": "32339",
"Score": "0",
"body": "@Rojee No problem. Glad I could help."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T22:19:55.437",
"Id": "20197",
"ParentId": "20196",
"Score": "4"
}
},
{
"body": "<p>You haven't done what the first exercise asked. It asks you to write a function that prompts the user for the name. You have written a function that prints the user's name. Effectively, you have done the opposite of what you were asked to do. As a result you've missed the point of the excersize. </p>\n\n<p>The second one does what the excersize says, but the excersize did not ask you to keep asking. To simply follow the excersize you should not have a loop. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T23:41:35.717",
"Id": "32289",
"Score": "0",
"body": "thanks man, next time I should read and understand the question much carefully."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T23:22:52.657",
"Id": "20200",
"ParentId": "20196",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20197",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T22:09:08.317",
"Id": "20196",
"Score": "3",
"Tags": [
"c++",
"beginner",
"pointers",
"reference"
],
"Title": "Am I using C++ pointers and references correctly?"
}
|
20196
|
<p>I would like to get an advice regarding how to test the same code with different input data.</p>
<p>I would like to test that method <code>operationSucceeded</code> will be invoked for all successful status codes. Here is how I can test (with <a href="https://github.com/allending/Kiwi" rel="nofollow">Kiwi</a>) single status code (i.e. 200):</p>
<pre><code>it(@"should call operationSucceeded", ^{
MKNetworkOperation *op =[[MKNetworkOperation alloc] initWithURLString:@"http://example.com/api" params:nil httpMethod:@"GET"];
[op stub:@selector(notifyCache)];
NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:nil
statusCode:200
HTTPVersion:nil
headerFields:nil];
[op stub:@selector(response) andReturn:response];
[[op should] receive:@selector(operationSucceeded)];
[op connectionDidFinishLoading:[NSURLConnection nullMock]];
});
</code></pre>
<p>For now I do next:</p>
<pre><code>it(@"should call operationSucceeded", ^{
NSArray *successCodes = @[@200, @201, @202, @203, @204, @205, @206];
for (NSNumber *statusCode in successCodes) {
MKNetworkOperation *op =[[MKNetworkOperation alloc] initWithURLString:@"http://example.com/api" params:nil httpMethod:@"GET"];
[op stub:@selector(notifyCache)];
NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:nil
statusCode:[statusCode intValue]
HTTPVersion:nil
headerFields:nil];
[op stub:@selector(response) andReturn:response];
[[op should] receive:@selector(operationSucceeded)];
[op connectionDidFinishLoading:[NSURLConnection nullMock]];
}
});
</code></pre>
<p>But the main problem here is that if my test fail for one of status codes it will say something like: "'Operation, should call operationSucceeded' [FAILED], expected subject to receive -operationSucceeded exactly 1 time, but received it 0 times" which is not very useful.</p>
<p>You can find full source code <a href="https://github.com/MugunthKumar/MKNetworkKit/blob/fe92e9df7b77afd2f261a6607d4f04bfa6e69cd1/MKNetworkKit-Tests/MKNetworkKit-Tests/MKNetworkOperationSpec.m#L101-L130" rel="nofollow">here</a>.</p>
<p>Any advices are very welcome! =)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T14:35:13.907",
"Id": "32346",
"Score": "0",
"body": "This site is dedicated for code review: you can present working code and ask for possible improvements. However if the code is faulty it isn't in the scope of this site and you should post it on stackoverflow. Also the audience over there is much bigger."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T14:51:28.090",
"Id": "32347",
"Score": "0",
"body": "but this code is working. I just want to improve it to provide better error explanation. This code isn't faulty."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T14:52:54.317",
"Id": "32348",
"Score": "0",
"body": "than you should work on the question's text, as I understood as if it isnt doing what you expect. probably others will misread it as-well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T15:00:09.020",
"Id": "32349",
"Score": "0",
"body": "@vikingosegundo do you have any thoughts regarding the question itself?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T15:02:26.230",
"Id": "32351",
"Score": "0",
"body": "Nope, I never worked with Kiwi. But sure I will try it out soon. +1"
}
] |
[
{
"body": "<p>I've got one possible solution from Max Lunin:</p>\n\n<pre><code>NSArray *successCodes = @[@200, @201, @202, @203, @204, @205, @206];\nfor (NSNumber *statusCode in successCodes) {\n it([NSString stringWithFormat:@\"should call operationSucceeded for status code %@\", statusCode], ^{\n MKNetworkOperation *op =[[MKNetworkOperation alloc] initWithURLString:@\"http://example.com/api\" params:nil httpMethod:@\"GET\"];\n [op stub:@selector(notifyCache)];\n NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:nil\n statusCode:[statusCode intValue]\n HTTPVersion:nil\n headerFields:nil];\n [op stub:@selector(response) andReturn:response];\n [[op should] receive:@selector(operationSucceeded)];\n [op connectionDidFinishLoading:[NSURLConnection nullMock]];\n });\n}\n</code></pre>\n\n<p>It solves the problem with error explanation. It will tell something like: <code>'Operation, should call operationSucceeded for status code 202' [FAILED], expected subject to receive -operationSucceeded exactly 1 time, but received it 0 times</code></p>\n\n<p>Any other more clear solutions?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T14:58:00.360",
"Id": "20226",
"ParentId": "20198",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-05T22:42:10.340",
"Id": "20198",
"Score": "2",
"Tags": [
"objective-c",
"unit-testing",
"ios"
],
"Title": "Testing the same code with different input data"
}
|
20198
|
<p>At the end of the immediately-invoked function expression, there is an if statement that checks the screen width and loads in some resources. I'm curious if it is best practice to include this logic inside my IIFE, or outside. Both seem to function the same as far as I can tell, though I'm curious if there is preferred/best way this should be done.</p>
<p>Also of interest to me, inside the IIFE I have a if/if else/else statement. I'm curious if the last else, with the return in it is necessary. Does it offer any benefits or should I remove it.</p>
<p>Feedback is much appreciated!</p>
<p>Below is the code I'm working with:</p>
<pre><code>(function(w){
w.loader = function(filetype, filename, mediaquery){
var head = document.getElementsByTagName("head")[0],
stylesheet = document.createElement('link'),
script = document.createElement('script'),
filetype = filetype.toLowerCase(); // normalize filetype data for use in conditions
// If file type is set to CSS, create dynamic stylesheet link element
if (filetype === 'css'){
stylesheet.type = 'text/css';
stylesheet.rel = 'stylesheet';
stylesheet.href = (filename + '.css');
stylesheet.media = (mediaquery) ? mediaquery : 'screen'; // Use screen for media unless otherwise specified
// If a file name has been specified, append dynamic stylesheet link element
if (filename.length){
head.appendChild(stylesheet);
}
}
// If file type is set to JS, create dynamic script element link
else if(filetype === 'js'){
script.type = 'text/javascript';
script.src = (filename + '.js');
// If a file name has been specified, append dynamic script element
if (filename.length){
head.appendChild(script);
}
}
else{
return;
}
};
if(Math.max(screen.width,window.outerWidth) > 600 ){
alert("Large Screen");
loader('CSS', 'large-screen');
loader('JS', 'large-screen');
}
}(this));
/*
if(Math.max(screen.width,window.outerWidth) > 600 ){
alert("Large Screen");
loader('CSS', 'large-screen');
loader('JS', 'large-screen');
}
*/
</code></pre>
|
[] |
[
{
"body": "<p>In this case, it makes no difference at all. This IIFE really has no reason for even being there because all it contains is a single function. Your code does use any of the usual benefits of an IIFE (like a local and protected scope) or capturing the arguments in a closure. </p>\n\n<p>So the additional code that doesn't have any local variables of its own and doesn't use the passed in argument does not benefit at all from being in the IIFE, but there is no harm in putting it in the IIFE either.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T03:52:46.690",
"Id": "20204",
"ParentId": "20202",
"Score": "1"
}
},
{
"body": "<p>jfriend00 is 100% right about the first part of your question.</p>\n\n<p>To answer the second part of your question the return serves no purpose in the code your presented.</p>\n\n<p>A better approach would actually be to throw an exception for the unhandled case. This way, if the user of this function tries to include something that the loader cannot handle they will know about it right away instead of having it fail silently.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-12T01:37:39.587",
"Id": "20453",
"ParentId": "20202",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20453",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T01:42:57.263",
"Id": "20202",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "New to immediately-invoked function expression with JavaScript, curious about placement"
}
|
20202
|
<p>At first I tried using a timedelta but it doesn't accept months as an argument, so my next working example is this:</p>
<pre><code>from datetime import datetime
current_date = datetime.now()
months = []
for month_adjust in range(2, -3, -1): # Order by new to old.
# If our months are out of bounds we need to change year.
if current_date.month + month_adjust <= 0:
year = current_date.year - 1
elif current_date.month + month_adjust > 12:
year = current_date.year + 1
else:
year = current_date.year
# Keep the months in bounds.
month = (current_date.month + month_adjust) % 12
if month == 0: month = 12
months.append(current_date.replace(year, month=month, day=1))
</code></pre>
<p>Is there a cleaner way?</p>
|
[] |
[
{
"body": "<p>Based on <a href=\"https://stackoverflow.com/questions/546321/how-do-i-calculate-the-date-six-months-from-the-current-date-using-the-datetime\">this answer</a>, I would do something like :</p>\n\n<pre><code>from datetime import date\nfrom dateutil.relativedelta import relativedelta\ntoday = date.today()\nmonths = [today + relativedelta(months = +i) for i in range(2,-3,-1)]\n</code></pre>\n\n<p>It's always better not to have to play with the dates manually as so many things can go wrong.</p>\n\n<p>(I don't have access to a machine with relativedelta here so it's not tested but I'm pretty confident it should work)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T23:35:41.697",
"Id": "32326",
"Score": "0",
"body": "That is wonderful, thanks! BTW you can drop the `+` in `+i`. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T23:41:46.643",
"Id": "32327",
"Score": "0",
"body": "Also you don't need the `.month` in the list compression as I need the date object."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T23:33:25.933",
"Id": "20217",
"ParentId": "20216",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20217",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T22:31:19.160",
"Id": "20216",
"Score": "1",
"Tags": [
"python"
],
"Title": "Is there a cleaner way of building a list of the previous, next months than this?"
}
|
20216
|
<p>I am fetching rows from the DB and returning the result in JSON. The output needs to be an array of associative arrays.</p>
<pre><code>$i = 0;
foreach($resultSet as $r)
{
$output[$i]['key1'] = $r['col1'];
$output[$i]['key2'] = $r['col2'];
...
$output[$i]['keyN'] = $r['colN'];
$i++;
}
</code></pre>
<p>Is there a more elegant way to do this? Is there anything wrong with this approach? If yes, what is it?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T05:33:22.000",
"Id": "32332",
"Score": "0",
"body": "Which DB API are you using? If PDO, your best bet will be to alias the columns to whatever you want their names to be (`SELECT a as b` or `SELECT a b`) and then use `fetchAll()`. Not sure what other APIs have a method like that."
}
] |
[
{
"body": "<p>Instead of declaring <code>$i=0;</code> before the loop, you can also write :</p>\n\n<pre><code>foreach($resultSet as $i => $r)\n{\n $output[$i]['key1'] = $r['col1'];\n $output[$i]['key2'] = $r['col2'];\n ...\n $output[$i]['keyN'] = $r['colN'];\n}\n</code></pre>\n\n<p>Also, if you could rename your column in the DB query, you could have :</p>\n\n<pre><code>foreach($resultSet as $i => $r)\n{\n $output[$i] = $r;\n}\n</code></pre>\n\n<p>Which is pretty much like doing <code>$output = $resultSet;</code></p>\n\n<p><strong>Edit :</strong>\nIf you do need to do some processing on <code>$resultSet</code> for whatever reason and you'd rather have different names, you can consider doing :</p>\n\n<pre><code>for (array('key1' => 'col1', ... 'keyN' => 'colN' as key => col)\n{\n $output[$i][$key] = $r[$col];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T06:41:17.227",
"Id": "32333",
"Score": "0",
"body": "The $i IS outside the loop in my actual code. I have updated the question. The reason I am not using the resultset directly is that I do some operation on the resultset array before output. But I think, I might as well think about modifying my query and do all the operatrions in the SQL itself, so that I could simply return the resultset. Isn't it ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T06:44:35.497",
"Id": "32334",
"Score": "0",
"body": "Oops I messed up when I copy-pasted in my editor. You can consider my first comment then."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T06:49:24.023",
"Id": "32335",
"Score": "0",
"body": "I edited my post. Not sure if it would help."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T05:36:13.773",
"Id": "20221",
"ParentId": "20220",
"Score": "2"
}
},
{
"body": "<p>Perhaps something like this? </p>\n\n<pre><code>$i = 0;\nforeach($resultSet as $key => $value){\n $output[$i++][$key] = $value;\n}\n</code></pre>\n\n<p>Given a <code>$resultSet</code> like this:</p>\n\n<pre><code>$resultSet['key0'] = 'value0';\n$resultSet['key1'] = 'value1';\n$resultSet['key2'] = 'value2';\n$resultSet['key3'] = 'value3';\n$resultSet['key4'] = 'value4';\n$resultSet['key5'] = 'value5';\n</code></pre>\n\n<p>The above code will produce something as follows:</p>\n\n<pre><code>Array (\n [0] => Array ( [key0] => value0 )\n [1] => Array ( [key1] => value1 )\n [2] => Array ( [key2] => value2 )\n [3] => Array ( [key3] => value3 )\n [4] => Array ( [key4] => value4 )\n [5] => Array ( [key5] => value5 )\n)\n</code></pre>\n\n<p>Echoing <code>$output[0]['key0]</code> will output <code>value0</code> (or an array if value0 is an array). </p>\n\n<p>As a side note, you could actually get completely rid of $i, and just do the following:</p>\n\n<pre><code>foreach($resultSet as $key => $value){\n $output[][$key] = $value;\n}\n</code></pre>\n\n<p>Do let me know if I completely misunderstood the question at hand though :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T16:04:20.160",
"Id": "20236",
"ParentId": "20220",
"Score": "0"
}
},
{
"body": "<p>Assuming you are trying to map Columns from the resulting rows such that:</p>\n\n<pre><code>Row | Column 1 | Column 2\n1 | Value 1 | Value 2\n2 | Value 2 | Value 2\n</code></pre>\n\n<p>Results in:</p>\n\n<pre><code>$rows = array(\n 1 => array(\n 'Column 1' => 'Value 1',\n 'Column 2' => 'Value 2'\n ),\n 2 => array(\n 'Column 1' => 'Value 1',\n 'Column 2' => 'Value 2'\n ),\n);\n</code></pre>\n\n<p>If your PDO returns the values in numerical position, you can do this:</p>\n\n<pre><code>$columns = array(\n 'Column 1',\n 'Column 2'\n);\n\n$rows = array_map(function($row) use ($columns) {\n return array_combine($columns, $row);\n}, $resultSet);\n</code></pre>\n\n<p>Or, if the <code>$resultSet</code> is associative, and you want to keep the names:</p>\n\n<pre><code>$columns = array_flip(array(\n 'Column 1',\n 'Column 2'\n));\n\n$rows = array_map(function($row) use ($columns) {\n return array_intersect_key($row, $columns);\n}, $resultSet);\n</code></pre>\n\n<p>OR, if your PDO returns them in an Associative array, but the Column names need to be change:</p>\n\n<pre><code>$columns = array(\n 'Column 1' => 'Key 1',\n 'Column 2' => 'Key 1'\n);\n\n$rows = array_map(function($row) use ($columns) {\n $return = array();\n foreach($columns as $from => $to) {\n $return[$to] = !empty($row[$from]) ? $row[$from] : NULL;\n }\n return $return;\n}, $resultSet);\n</code></pre>\n\n<p>That last one would work for either situation, really, as it will take the value at <code>$row[$from]</code> and place it at <code>$result[$to]</code>, which would account for numerical indices or string indices. Also, the <code>empty()</code> check will suppress PHP errors, and will ensure that you have a value at each position.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-30T19:45:28.400",
"Id": "115456",
"ParentId": "20220",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T05:26:45.603",
"Id": "20220",
"Score": "1",
"Tags": [
"php",
"performance"
],
"Title": "Creating an array of associative arrays in PHP"
}
|
20220
|
<p>This is my solution to <a href="https://www.spoj.com/problems/INTEST/" rel="nofollow">SPOJ Problem 442</a>. How can I make this code run faster? What are some techniques that can be used to make this faster? I am getting a Time Limit Exceed Error here.</p>
<pre><code>import java.util.Scanner;
class main{
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int n,k,m=0;
n = input.nextInt();
k = input.nextInt();
for(int c = 0 ; c < n ; c++){
if(input.nextInt() % k == 0) m++;
}
System.out.println(m);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T12:26:03.647",
"Id": "32343",
"Score": "1",
"body": "`You are expected to be able to process at least 2.5MB of input data per second at runtime.` Are you expecting your user to be able to type that much data that fast into the console? Because that sounds impossible to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T17:10:58.107",
"Id": "32374",
"Score": "0",
"body": "How are you getting the `Time Limit Exceed Error`"
}
] |
[
{
"body": "<p>According to <a href=\"https://stackoverflow.com/questions/4960736/which-is-the-most-efficient-way-of-taking-input-in-java\">this question</a> on SO, the issue is with Scanner's nextInt method. Use a BufferedReader, then manually convert the string into an int.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T18:47:30.763",
"Id": "20241",
"ParentId": "20222",
"Score": "1"
}
},
{
"body": "<p>The main reasons are</p>\n\n<ul>\n<li><code>Scanner</code> is pretty slow</li>\n<li><code>System.in</code> is unbuffered</li>\n</ul>\n\n<p>By using a <code>BufferedReader</code> instead of the <code>Scanner</code> you get it to barely acceptable levels. The following approach runs in roughly 8.2 seconds and get's accepted.</p>\n\n<pre><code>public class Main {\n public static void main(String args[]) throws java.io.IOException {\n java.io.InputStreamReader isr = new java.io.InputStreamReader(System.in);\n java.io.BufferedReader br = new java.io.BufferedReader(isr, 16 * 1024);\n String[] line0 = br.readLine().split(\" \");\n int n, k, m = 0;\n n = Integer.parseInt(line0[0]);\n k = Integer.parseInt(line0[1]);\n for (int c = 0; c < n; c++) {\n if (Integer.parseInt(br.readLine()) % k == 0)\n m++;\n }\n\n System.out.println(m);\n }\n}\n</code></pre>\n\n<p>But it's still really slow compared to the top scoring solutions that run in under 2 seconds.</p>\n\n<p>I've got it down to a bit over 2 seconds by reading into a <code>byte[]</code> buffer and doing custom number parsing based on that buffer roughly like the following incomplete piece (which just prints the parsed numbers)</p>\n\n<pre><code>public class Main {\n public static void main(String args[]) throws java.io.IOException {\n byte[] buffer = new byte[16 * 1024];\n int currentNumber = 0;\n boolean inNumber = false;\n int read;\n while((read = System.in.read(buffer)) >= 0) {\n for (int i = 0; i < read; i++) {\n char c = (char) buffer[i];\n if (c >= '0' && c <= '9') {\n inNumber = true;\n currentNumber = currentNumber * 10 + (c - '0');\n } else if (inNumber) {\n inNumber = false;\n System.out.println(\"I've read number: \" + currentNumber);\n currentNumber = 0;\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>See <a href=\"http://ideone.com/lQ4ImB\" rel=\"nofollow\">http://ideone.com/lQ4ImB</a> for above code with input</p>\n\n<p>The reason why this is so much faster is basically that there is almost 0 overhead in reading & parsing the input into numbers. <code>BufferedReader</code> in comparison is transforming each line into a <code>String</code> (thus creating a new Object), then parses that String. Above approach allocates no new Objects besides the single <code>byte[]</code> buffer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T11:41:34.623",
"Id": "32415",
"Score": "0",
"body": "I wrote last night nearly the same answer. I just want to add an additional idea, which does not fit in a separate answer anymore in my opinion. One could make the reading and checking asynchron. This means, use 2 threads. One is parsing the input and providing integers, the other one is doing the modulo. Use a good block size for the work packet to transfer between the threads and you should have some speed up. (Other improvements involve native methods and unsafe operations, but this will go too far)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T12:59:26.397",
"Id": "32419",
"Score": "0",
"body": "@tb- not sure if multi-threading would improve times since the test is executed on an old single core PIII machine. Native code should not work as well since you can't submit it. Unsafe could indeed prove useful. I also found that optimizing `if (number % div == 0)` to `if (number >= div && number % div == 0)` to help a bit since there seem to be enough numbers that the extra instructions are compensated by the faster first check. Also buffer sizes of ~16k-32k seem to perform best. Got it to under 1.9 seconds with stripping every extra operation in the loop I could find"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T13:02:14.873",
"Id": "32420",
"Score": "0",
"body": "@tb- it also requires some luck to produce code that is getting optimized better. Some restructuring (adding an e.g. additional `final` variable before the loop) proved to turn out slower although it should not impact performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T13:58:08.393",
"Id": "32426",
"Score": "0",
"body": "yes, optimizations always depends on measurements. Which can not be done because the real data are not accessible. For the multithreading: It is not about using different cores. The plan is to avoid stalls from I/O. Sadly, it would take me too much time to do a carefully tweaked implementation, so it is only an idea which can work in theory."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T19:12:06.173",
"Id": "20242",
"ParentId": "20222",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20242",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T12:16:17.033",
"Id": "20222",
"Score": "2",
"Tags": [
"java",
"performance",
"programming-challenge"
],
"Title": "Enormous Input Test - reducing program runtime"
}
|
20222
|
<pre><code>def users_list
html = ''
self.users.each do |user|
html << user.link_avatar_tag
end
html.html_safe
end
</code></pre>
<p>I feel that it is possible to write shorter.</p>
<p>Is it possible get rid of the temporary variable(html)?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T15:08:55.900",
"Id": "32352",
"Score": "0",
"body": "What class is user? `html_safe` is no standard method for String - What gems are you using? Or in short: Can you provide a MWE? And to answer: It looks ok for me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T15:30:57.517",
"Id": "32355",
"Score": "0",
"body": "Main topic of my question:\n\nIs it possible get rid of the temporary variable(html)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T16:41:38.070",
"Id": "32369",
"Score": "0",
"body": "I'll tag this rails, that's where `html_safe` comes from."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T08:39:18.687",
"Id": "32408",
"Score": "0",
"body": "one question about `self.users`, is this a model? a helper?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T12:54:17.310",
"Id": "32417",
"Score": "0",
"body": "This is TaskDecorator. \nTask has_and_belongs_to_many :users \nhttps://github.com/drapergem/draper"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T12:58:57.243",
"Id": "32418",
"Score": "0",
"body": "@Fant: ok, I was unsure because you have `self` (not in helpers) but used `html_safe` (not in models). You can drop the `self` then"
}
] |
[
{
"body": "<p>You should use <code>map</code> (don't use <code>each</code> to accumulate. Check <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">this page about functional programming</a>):</p>\n\n<pre><code>def users_list \n users.map(&:link_avatar_get).join.html_safe\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T16:47:14.060",
"Id": "32372",
"Score": "1",
"body": "I change code a bit & that works: \n \n self.users.map(&:link_avatar_tag).join.html_safe"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T17:05:46.803",
"Id": "32373",
"Score": "0",
"body": "mmm, yes, you are right, here `safe_join` is not necessary, edited."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T16:36:02.480",
"Id": "20237",
"ParentId": "20224",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "20237",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T13:43:49.017",
"Id": "20224",
"Score": "3",
"Tags": [
"ruby",
"html",
"ruby-on-rails"
],
"Title": "Refactor ruby each-code"
}
|
20224
|
<p>A few days ago I've faced an annoying problem.
Let's imagine we have 3 classes: Base, System, Handler.</p>
<p>The classes Systen and Handler both inherit from the class Base.
I want to access those classes this way: System::DoStuff();
I also need the Handler be available in the System, but do not want to instantiate it there, use any kind of reference injection.</p>
<p>I could simply design the System and the Handler class to be static. The problem would be:
They need to inherit form the Base class, which should be static too, because if it's not, it won't work with the System and Hanlder because they ARE static. If is set Base to static, it won't work either, because once a child changes some parameter in it's parent, the parent would change for ALL children.</p>
<p>After some testing, I've came up with this solution:</p>
<pre><code>class Wire
{
//List of classes I'll have to load
private static $load = array("Foo", "Hello");
//Template of the Bootstrap class
private static $template = NULL;
//Wire everything up
public function Up()
{
//Get the bootstrap template
self::GetTemplate();
//Get each class
foreach(self::$load as $class)
{
//Load it...
require_once "./class/" . $class . ".php";
//Build the static shell
$bootstrap = str_replace("%CLASS%", $class, self::$template);
eval($bootstrap);
}
}
//Get the tempalte of the bootstrap class
private function GetTemplate()
{
if(self::$template === NULL)
{
//I've stored it in a separate file
self::$template = file_get_contents("./class/Bootstrap.php");
}
}
}
Wire::Up();
</code></pre>
<p>I'me using the Wire class to load the classes I need. And use this Bootstrap file to create a static shell for each instatiated class.</p>
<pre><code>//This is the Bootstrap class
//It offers a static shell for other instatiated classes
class %CLASS%
{
public static $instance = NULL;
public function __callStatic($method, $arguments)
{
if(self::$instance === NULL)
{
$class = get_called_class() . "Controller";
self::$instance = new $class();
}
call_user_func_array(array(self::$instance, $method), $arguments);
}
}
</code></pre>
<p>That's the Base class, for testing purpouses only</p>
<pre><code>class Base
{
public $value = 1;
}
</code></pre>
<p>Here are the classes Foo and Hello that I've used above</p>
<pre><code>class FooController extends Base
{
public function Bar($args)
{
print $args . " " . $this->value . "<br>";
}
}
class HelloController extends Base
{
public function World($args)
{
$this->value = 10;
print $args . " " . $this->value . "<br>";
}
}
</code></pre>
<p>Now, if you call</p>
<pre><code>Hello::World("Hello World") //Hello World 10
Foo::Bar("Foo Bar") //Foo Bar 1
//If Foo and Base would be static, whitout the Bootstrap shell, you would see "Foo Bar 10"
</code></pre>
<p>What do you think about that solution? Am I hunting a mouse with a shotgun? Or maybe there are better solutions, for this scenario? I'd appreciate costructive critics!!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T21:27:56.383",
"Id": "32390",
"Score": "2",
"body": "Static classes tend to quickly move you in the exact opposite direction as OOP. I have a feeling that there's a much better way to accomplish what you're doing, but after reading your post 3 times, I'm not quite sure I understand what it is that you are doing. Why do you need to wrap some objects in a static 'shell'? Is it for convenience? Abusing them as globals? Or what? It seems like dependency injection is the right approach here, even if it is less convenient. (Once again though, maybe I'm missing something -- not sure I quite get what the end goal is.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T23:10:18.410",
"Id": "32397",
"Score": "0",
"body": "Read my post below, please."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-06T09:24:56.907",
"Id": "49118",
"Score": "0",
"body": "Rule of thumb: If it has mutable state it shouldn't be static"
}
] |
[
{
"body": "<p>I don't know if I'm just not understanding your situation properly or what, but I don't think converting three classes to static for one static method is really the right thing to do here. Why would you need to call <code>System::DoStuff()</code> statically? Why not just <code>$system->DoStuff()</code>? I would refactor the one method before I refactored the three classes. At most I would convert your base class to an abstract class to prevent its instantiation and I would define the value for the <code>$value</code> property in each individual class.</p>\n\n<pre><code>abstract class Base {\n public $value;\n}\n\nclass FooController extends Base {\n public $value = 1;\n\n //etc...\n}\n\nclass HelloController extends Base {\n public $value = 10;\n\n //etc...\n}\n</code></pre>\n\n<p>You should use doccomments instead of those normal comments. They're more useful and can be read by your IDE.</p>\n\n<pre><code>/** List of classes I'll have to load */\nprivate static $load = array( 'Foo', 'Hello' );\n</code></pre>\n\n<p>\"Up\" is not a very descriptive method name. What is it supposed to do? From your comments and your code it looks like its instantiating the class. So normally this would be in the constructor. I would suggest renaming this to something like <code>instantiate()</code>, or maybe <code>getInstance()</code>; And then I would make this a private method, or at the very least ensure that it hasn't already been instantiated so you don't end up doing it again.</p>\n\n<p><code>eval()</code> is evil. No seriously, it is. It is a horrible security risk. The only saving grace in this instance is that you have not written this in such a way that user input could be used. If you need to dynamically load a class, then you should just do so like this:</p>\n\n<pre><code>foreach( $load AS $class ) {\n require \"./class/$class.php\";\n $instance = new $class();\n}\n</code></pre>\n\n<p>The <code>*_once()</code> versions of <code>require</code> and <code>include</code> should be avoided if at all possible. With a small number of files it isn't as noticeable, but PHP has to run a special check on each request to ensure that the file hasn't already been included, this means that it will run slower. Again, this is negligible in this case, but it could become an issue later.</p>\n\n<p>I hope this helps, but I really don't know if I understood your issue well enough.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T21:24:33.973",
"Id": "32389",
"Score": "1",
"body": "+1, but a small nitpick: Auto loading tends to be much more flexible down the road than explicit `require`/`include`. (And it can have very similar performance with a simple autoloader.) The problem essentially boils down to that the `$class` may have already been loaded. Not likely in a simple case like this though. (And in all but a few edge cases, attempting to double load classes is a very bad sign.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T22:05:05.700",
"Id": "32393",
"Score": "0",
"body": "I wasn't sure whether I should mention autoloading or not, but you are correct, it would be."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T23:10:01.827",
"Id": "32396",
"Score": "0",
"body": "Read my post below, please."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T15:08:20.420",
"Id": "32429",
"Score": "1",
"body": "@maximkott: You should remove your \"answer\" and edit your question with that information. I don't understand why you would not want to instantiate a class. That single limitation, and your static solution, is the root of all your problems. \"I want some classes be accessible as static ones, but behave like regular classes.\" That's contradictory, and I cannot imagine a situation where it would be necessary. It really sounds like you want a shared instance of a normal class, (persistence through sessions, cache, etc...) or maybe helper functions. As Corbin said, static is very much anti-OOP."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T20:19:04.847",
"Id": "20247",
"ParentId": "20225",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20247",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T13:58:01.607",
"Id": "20225",
"Score": "1",
"Tags": [
"php",
"singleton",
"static"
],
"Title": "PHP my way of threating static classes"
}
|
20225
|
<p>I made the popular Guess-The-Number game and included an AI version that picks random numbers. The AI version has slightly different <code>Console</code> output that differ slightly, for example:</p>
<pre><code>I generated a number between 1 and 100. Can you guess it?
You generated a number between 1 and 100. Let me try
</code></pre>
<p>First I did this:</p>
<pre><code>Console.WriteLine("{0} generated a number between 1 and 100. {1}", ai? "I" : "You", ai? "Can you guess it?", "Let me try");
</code></pre>
<p>As this needed to be done a few more times, it looked very clumsy, but could implement both versions in one medium length method. After that I seperated the different versions and made two shorter methods <code>GuessUser</code> and <code>GuessAI</code> which are cleaner, but both share a lot of similar code, <em>almost</em> everything besides <code>Console.WriteLine(x)</code>.</p>
<p>Is there a smart way to combine those two versions into a small method?</p>
<p><a href="https://gist.github.com/4475657" rel="nofollow">Complete version</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T15:57:59.707",
"Id": "32364",
"Score": "2",
"body": "Could you post the relevant code directly here?"
}
] |
[
{
"body": "<p>I can't say that it's going to be more efficient, or better designed, but one option is to take advantage of polymorphism by creating a set of classes for this.</p>\n\n<pre><code>public abstract class GuessBase\n{\n protected abstract string GuessMessage { get; }\n protected abstract string WrongMessage { get; }\n protected abstract string RightMessage { get; }\n\n protected abstract int GetGuess();\n\n public void DoGuessing()\n {\n Console.WriteLine(GuessMessage);\n while (guess != number)\n {\n if (GetGuess() != number)\n Console.WriteLine(WrongMessage, guess);\n tries++;\n }\n Console.WriteLine(RightMessage, number, tries);\n Console.ReadLine();\n } \n}\npublic class AIGuess : GuessBase\n{\n protected override string GuessMessage\n {\n get\n {\n return \"You generated a number between 1 and 100. Let me try\";\n }\n }\n // Similar for WrongMessage and RightMessage\n\n protected override int GetGuess()\n {\n return Pick(number, ref guess);\n }\n // Put Pick() method here.\n}\npublic class UserGuess : GuessBase\n{\n protected override string GuessMessage\n {\n get\n {\n return \"I generated a number between 1 and 100. Can you guess it?\";\n }\n }\n // Similar for WrongMessage and RightMessage\n\n protected override int GetGuess()\n {\n int guess;\n int.TryParse(Console.ReadLine(), out guess); // This won't do what you want if the user doesn't provide a valid number.\n return guess;\n }\n}\n</code></pre>\n\n<p>Then, in your main code, do this:</p>\n\n<pre><code>GuessBase guess;\nif (/* AI */) guess = new AIGuess();\nelse guess = new UserGuess();\nguess.DoGuessing();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T18:05:28.040",
"Id": "20240",
"ParentId": "20229",
"Score": "4"
}
},
{
"body": "<p>While I do like the polymorphism way a bit more, you could opt for something along the following lines. Notice I've cut out a bit of the sczizophrenic talking to itself, and improved on the use of variables aswell.</p>\n\n<pre><code>class Program\n{\n static readonly Random Rng = new Random();\n static int min;\n static int max = 100;\n\n private static void Main()\n {\n var number = Rng.Next(1, 100);\n Console.WriteLine(\"Do you want to [g]uess or [c]hoose?\");\n\n string choice = Console.ReadLine() ?? \"\";\n\n if (choice.StartsWith(\"c\"))\n {\n Console.WriteLine(\"Insert your number between 1 and 100:\");\n int.TryParse(Console.ReadLine(), out number);\n\n Console.WriteLine(\"You generated a number between 1 and 100. Let me try\");\n int previousGuess = 0;\n var tries = Guess(number, () => Pick(number, ref previousGuess));\n Console.WriteLine(\"Great, the answer was {0}. It took me {1} tries.\", number, tries);\n }\n else\n {\n Console.WriteLine(\"I generated a number between 1 and 100. Can you guess it?\");\n var tries = Guess(number, () => int.Parse(Console.ReadLine()));\n Console.WriteLine(\"Great, the answer was {0}. It took you {1} tries.\", number, tries);\n }\n\n Console.ReadLine();\n }\n\n private static int Guess(int number, Func<int> guessMethod)\n {\n int tries = 1;\n while(true)\n {\n var guess = guessMethod();\n if (guess != number)\n {\n Console.WriteLine(\"No, it's {0} than {1}.\", guess < number ? \"higher\" : \"lower\", guess);\n tries++;\n }\n else\n {\n return tries;\n }\n } \n }\n\n private static int Pick(int number, ref int guess)\n {\n if (guess > number)\n max = guess;\n else\n min = guess;\n return guess = Rng.Next(min, max);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T22:58:09.333",
"Id": "20253",
"ParentId": "20229",
"Score": "3"
}
},
{
"body": "<p>Well, I combined both everything into one method that I think is both elegant and suffices for this short program. I'm aware of abstractions similar to Bobson proposed, but I think that would be overkill for this. Any comments?</p>\n\n<pre><code>Random rng = new Random();\nint min = 0, guess = 0, tries = 0, max = 100, number = rng.Next(1, 100);\nbool ai = false;\n\nConsole.WriteLine(\"Do you want to [g]uess or [c]hoose?\");\nstring choice = Console.ReadLine();\nif (choice.StartsWith(\"c\"))\n{\n Console.WriteLine(\"Insert your number between 1 and 100:\");\n int.TryParse(Console.ReadLine(), out number);\n ai = true;\n}\n\nstring message = ai ? \"You generated a number between 1 and 100. Let me try\"\n : \"I generated a number between 1 and 100. Can you guess it?\";\nConsole.WriteLine(message);\n\nwhile (guess != number)\n{\n int.TryParse(ai ? (guess > number ? rng.Next(min, max = guess) : rng.Next(min = guess, max)).ToString()\n : Console.ReadLine(),\n out guess);\n if (guess != number)\n Console.WriteLine(\"No, it's {0} than {1}. Try again.\", guess < number ? \"higher\" : \"lower\", guess);\n tries++;\n}\nmessage = ai ? \"Great, the answer was {0}. It took me {1} tries.\"\n : \"Great, the answer was {0}. It took you {1} tries.\";\nConsole.WriteLine(message, number, tries);\nConsole.ReadLine();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T03:01:02.920",
"Id": "20264",
"ParentId": "20229",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "20240",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T15:11:46.187",
"Id": "20229",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Combine similar methods with different text?"
}
|
20229
|
<p>I have some sample code where I used <code>string.Format</code> but after reading about benchmark performances by other people I believe that it may be better to do multiple <code>appends</code> by a <code>StringBuilder</code></p>
<p>Here is the scenario:</p>
<p>In my <code>gridView</code>, I have a function called before a <code>databind</code>. The function looks like such:</p>
<pre><code>public string getColumnText(String myParam)
{
StringBuilder sb = new StringBuilder();
return sb.Append(string.Format("<a href='javascript:Global.someFunction(\"{0}\");'>{1}</a>", myParam).ToString();
}
</code></pre>
<p>Is this a better alternative?</p>
<pre><code>StringBuilder sb = new StringBuilder();
sb.Append("<a href = 'javascript:Global.someFunction(\"");
sb.Append(myParam"); etc...
</code></pre>
<p>Let's assume that this function will be called 10,000 times.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T15:55:55.430",
"Id": "32363",
"Score": "0",
"body": "It doesn't directly matter how many times the function will be called. (And it's not even clear what exactly do you mean by that: Is that 10,000 times per year? Or per second? Or something completely else?) What matters is whether the first method is too slow for your performance requirements."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T16:17:08.153",
"Id": "32366",
"Score": "0",
"body": "I would suggest running benchmarks on both and see what the results are."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T16:38:25.410",
"Id": "32368",
"Score": "0",
"body": "@svick I don't see how its not clear. I mentioned that my function is going to be performed before `gridview.databind()` is called so implying that 10K cooresponds to the number of entries in my gridView"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T16:41:55.320",
"Id": "32370",
"Score": "0",
"body": "@Rhs Ok, but that wasn't the main point I was making. The most important thing is: is this actually too slow for you? If not, write what's most readable and don't worry about performance."
}
] |
[
{
"body": "<p>A <code>StringBuilder</code> is useful when you're constructing a <code>string</code> where a loop will be directly effecting it, i.e. if you were appending several strings together within a loop, I'd recommend using a <code>StringBuilder</code>. Here's an example of where you might use a <code>StringBuilder</code>.</p>\n\n<pre><code>StringBuilder sb = new StringBuilder()\nfor (int i = 0; i < someItems.length; i++)\n{\n sb.AppendFormat(\"{0} is item index {1}\\n\", someItems[i], i);\n}\nreturn sb.ToString();\n</code></pre>\n\n<p>There are some overheads with <code>string.Format</code>, however they aren't huge, especially not in your case. Unless you're concerned about micro-optimisations, I think in this scenario it all falls down to readability, and which you prefer.</p>\n\n<p>An alternative method, which would be slightly faster than <code>string.Format</code> is to simply concatenate the string together, like so:</p>\n\n<pre><code>public string getColumnText(String myParam)\n{\n return \"<a href='javascript:Global.someFunction(\\\"\" + myParam + \"\\\");'>\" + myParam + \"</a>\";\n}\n</code></pre>\n\n<p>You may also want to consider ensuring it's <em>safe</em> for your desired output, i.e. do you need to escape quotation marks for <code>myParam</code>, or does it need to be HTML encoded?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T21:11:29.427",
"Id": "32466",
"Score": "0",
"body": "I disagree, string.Format is much easier for my eyes too parse. Having a concatenated mess of variables and text is hard to look at and a pain to manage down the road."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T09:25:54.880",
"Id": "32516",
"Score": "0",
"body": "I agree; I didn't imply using string concatenation with `+` was easier to read, I said it was slightly faster. I personally prefer `string.Format` for readability."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T15:53:44.540",
"Id": "20235",
"ParentId": "20230",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "20235",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T15:15:18.153",
"Id": "20230",
"Score": "3",
"Tags": [
"c#",
"strings"
],
"Title": "Inefficient usage of string.format?"
}
|
20230
|
<p>I have this working code. I think this must be easier with a while loop.</p>
<pre><code>if not c.e1.nil?
extrapreis = number_to_currency Extra.find(c.e1).aufschlag, :unit=>"EUR "
array.push Extra.find(c.e1).name + " (" + extrapreis.to_s + ")"
extpreis = extpreis + Extra.find(c.e1).aufschlag
end
if not c.e2.nil?
extrapreis = number_to_currency Extra.find(c.e2).aufschlag, :unit=>"EUR "
array.push Extra.find(c.e2).name + " (" + extrapreis.to_s + ")"
extpreis = extpreis + Extra.find(c.e2).aufschlag
end
if not c.e3.nil?
extrapreis = number_to_currency Extra.find(c.e3).aufschlag, :unit=>"EUR "
array.push Extra.find(c.e3).name + " (" + extrapreis.to_s + ")"
extpreis = extpreis + Extra.find(c.e3).aufschlag
end
if not c.e4.nil?
extrapreis = number_to_currency Extra.find(c.e4).aufschlag, :unit=>"EUR "
array.push Extra.find(c.e4).name + " (" + extrapreis.to_s + ")"
extpreis = extpreis + Extra.find(c.e4).aufschlag
end
if not c.e5.nil?
extrapreis = number_to_currency Extra.find(c.e5).aufschlag, :unit=>"EUR "
array.push Extra.find(c.e5).name + " (" + extrapreis.to_s + ")"
extpreis = extpreis + Extra.find(c.e5).aufschlag
end
</code></pre>
<p>It is always the same code, except for the variable <code>e</code> (<code>1</code>, <code>2</code>, <code>3</code>, <code>4</code>, <code>5</code>). How can I put this in a while loop and put the counter together with <code>e</code>?</p>
|
[] |
[
{
"body": "<p>I'd start with this untested code:</p>\n\n<pre><code>[c.e1, c.e2, c.e3, c.e4, c.e5].each do |e|\n if e\n extrapreis = number_to_currency(Extra.find(e).aufschlag, unit: 'EUR ')\n array << Extra.find(e).name + ' (' + extrapreis.to_s + ')'\n extpreis += Extra.find(e).aufschlag\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T21:17:01.733",
"Id": "32356",
"Score": "0",
"body": "Maybe `unless` instead of `if !`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T21:20:45.277",
"Id": "32357",
"Score": "0",
"body": "I don't like `unless`, especially at the start of a conditional block. It's one of those programmer-choice, often argued, syntax things."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T21:24:03.067",
"Id": "32358",
"Score": "0",
"body": "Fair enough - in fact [this article](http://railstips.org/blog/archives/2008/12/01/unless-the-abused-ruby-conditional/) would advocate a simple `if e` instead :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T21:36:08.193",
"Id": "32359",
"Score": "0",
"body": "That's true, `if e` is how I'd normally write it if I was doing a refactor or review. :-) I'll adjust it. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T21:39:09.570",
"Id": "32360",
"Score": "1",
"body": "You'd probably like [Ruby Best Practices](https://github.com/sandal/rbp-book)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T21:15:02.357",
"Id": "20233",
"ParentId": "20232",
"Score": "1"
}
},
{
"body": "<pre><code>(1..5).each do |i|\n e = c.send(\"e#{i}\")\n next if e.nil?\n found = Extra.find(e)\n array.push(\"#{found.name} (#{number_to_currency(found.aufschlag, unit: \"EUR \")})\")\n extpreis += found.aufschlag\nend\n</code></pre>\n\n<p>If you can be certain that <code>c.e1</code> etc. never becomes <code>false</code>, then:</p>\n\n<pre><code>(1..5).each do |i|\n next unless e = c.send(\"e#{i}\")\n found = Extra.find(e)\n array.push(\"#{found.name} (#{number_to_currency(found.aufschlag, unit: \"EUR \")})\")\n extpreis += found.aufschlag\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T21:40:10.267",
"Id": "32361",
"Score": "0",
"body": "Thank you very much. So I learn a little more about rails ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T21:42:47.270",
"Id": "32362",
"Score": "0",
"body": "It is not Rails. It's all plain Ruby. Actually, I barely know anything about Rails."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T21:27:04.277",
"Id": "20234",
"ParentId": "20232",
"Score": "2"
}
},
{
"body": "<p>Notes on your code:</p>\n\n<ul>\n<li><p>Use of parentheses: Ruby allows you to drop them, but the community seems to have reached a consensus it may harm readability, restrict its usage to DSL-style code.</p></li>\n<li><p><code>extrapreis</code>: this may be \"private\" code (well, it's not anymore since you publicly asked about it), but it's good practice to use the commonly accepted language in the programming world (for script names, variable names, comments, everything).</p></li>\n<li><p><code>array.push</code>, <code>x = x + y</code>, ...: you may use this but being aware about functional programming and why inplace updates are considered (by some) bad practice. <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">More on this issue</a>.</p></li>\n<li><p><code>if not c.e1.nil?</code> -> <code>if c.e1</code>.</p></li>\n<li><p><code>Extra.find(c.e1).aufschlag</code>. In each block you call this twice, why? use a variable to store the value.</p></li>\n</ul>\n\n<hr>\n\n<p>For a novice programmer a functional approach may be a little difficult to grasp at first, but it introduces important concepts that will (hopefully) prove useful later on:</p>\n\n<pre><code>strings, values = [c.e1, c.e2, c.e3, c.e4].compact.map do |e|\n value = Extra.find(e).aufschlag\n extra_price = number_to_currency(value, :unit => \"EUR\")\n name = Extra.find(e).name \n [\"#{name} (#{extra_price})\", value]\nend.transpose\nextra_price_total = values.inject(0, :+)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T16:52:39.000",
"Id": "20238",
"ParentId": "20232",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "20234",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T20:58:40.077",
"Id": "20232",
"Score": "1",
"Tags": [
"ruby"
],
"Title": "Dynamic variables in loop"
}
|
20232
|
<p>This is intended to be a simpler replacement of <code>std::vector</code>, written for entertainment.
It should be as fast or faster than <code>std::vector</code>, but does not need to have as many features.</p>
<p>It should also be simple to use.</p>
<p>I am looking for a review on the following:</p>
<ul>
<li>Bugs</li>
<li>Performance</li>
<li>Class/Functions/Variables Naming</li>
<li>Useful features to add</li>
<li>Code structure</li>
<li>Anything else</li>
</ul>
<p>Here is the header file Vector.hpp</p>
<pre><code>#pragma once
#include "../Types.hpp"
#include "../System/Memory/Memory.hpp"
namespace Core
{
namespace DataStruct
{
template<class ItemType> class Vector
{
ItemType* VecPtr;
UInt Capacity;
UInt Length;
void AllocSpace();
void DestroyAll();
public:
typedef ItemType* Iterator;
typedef ItemType const * ConstIterator;
Vector();
~Vector();
void Reserve(UInt Capacity);
void Add(ItemType const & Value);
void Insert(UInt Position, ItemType const & Value);
void Remove(UInt Position);
void Clear();
void Free();
UInt GetCapacity() const;
UInt GetLength() const;
ItemType operator[](UInt Position) const;
Iterator Begin();
Iterator End();
ConstIterator Begin() const;
ConstIterator End() const;
ConstIterator CBegin() const;
ConstIterator CEnd() const;
};
#include "Vector.cpp"
}
}
</code></pre>
<p>And the implementation Vector.cpp, excluded from the build and included from Vector.hpp since it is a template.</p>
<pre><code>template <class ItemType> void Vector<ItemType>::AllocSpace()
{
if(Capacity == 0U)
Reserve(2U);
else if(Capacity == Length)
Reserve(Capacity << 1U);
}
template <class ItemType> void Vector<ItemType>::DestroyAll()
{
Iterator it = Begin();
Iterator end = End();
while(it < end)
it++->~ItemType();
}
template<class ItemType> Vector<ItemType>::Vector() : VecPtr(NULL), Capacity(0U), Length(0U) {}
template<class ItemType> Vector<ItemType>::~Vector()
{
Free();
}
template<class ItemType> void Vector<ItemType>::Reserve(UInt Capacity)
{
ItemType* ptr;
if(Capacity > this->Capacity)
{
ptr = (ItemType*)System::Memory::Alloc(sizeof(ItemType) * Capacity);
if(VecPtr)
{
System::Memory::Copy(VecPtr, ptr, sizeof(ItemType) * this->Capacity);
System::Memory::Free(VecPtr);
}
VecPtr = ptr;
this->Capacity = Capacity;
}
}
template<class ItemType> void Vector<ItemType>::Add(ItemType const & Value)
{
Insert(Length, Value);
}
template<class ItemType> void Vector<ItemType>::Insert(UInt Position, ItemType const & Value)
{
ItemType* ptr;
Bool insert;
AllocSpace();
//If Position is beyond the end then insert at end.
insert = Position < Length;
ptr = insert ? VecPtr + Position : VecPtr + Length;
if(insert)
System::Memory::Move(ptr, ptr + 1, sizeof(ItemType) * (Length - Position));
new((VoidPtr)ptr) ItemType(Value);
++Length;
}
template<class ItemType> void Vector<ItemType>::Remove(UInt Position)
{
ItemType* ptr;
if(Position < Length)
{
--Length;
ptr = VecPtr + Position;
ptr->~ItemType();
if(Position < Length)
System::Memory::Move(ptr + 1, ptr, sizeof(ItemType) * (Length - Position));
}
}
template<class ItemType> void Vector<ItemType>::Clear()
{
DestroyAll();
Length = 0U;
}
template<class ItemType> void Vector<ItemType>::Free()
{
if(VecPtr)
{
DestroyAll();
System::Memory::Free(VecPtr);
VecPtr = NULL;
Capacity = 0U;
Length = 0U;
}
}
template<class ItemType> UInt Vector<ItemType>::GetCapacity() const
{
return Capacity;
}
template<class ItemType> UInt Vector<ItemType>::GetLength() const
{
return Length;
}
template<class ItemType> ItemType Vector<ItemType>::operator[](UInt Position) const
{
return *(VecPtr + Position);
}
template<class ItemType> typename Vector<ItemType>::Iterator Vector<ItemType>::Begin()
{
return VecPtr;
}
template<class ItemType> typename Vector<ItemType>::Iterator Vector<ItemType>::End()
{
return VecPtr + Length;
}
template<class ItemType> typename Vector<ItemType>::ConstIterator Vector<ItemType>::Begin() const
{
return VecPtr;
}
template<class ItemType> typename Vector<ItemType>::ConstIterator Vector<ItemType>::End() const
{
return VecPtr + Length;
}
template<class ItemType> typename Vector<ItemType>::ConstIterator Vector<ItemType>::CBegin() const
{
return VecPtr;
}
template<class ItemType> typename Vector<ItemType>::ConstIterator Vector<ItemType>::CEnd() const
{
return VecPtr + Length;
}
</code></pre>
<p>The functions in the <code>Memory</code> namespace calls the following:</p>
<ul>
<li><code>Memory::Alloc</code> -> <code>malloc</code></li>
<li><code>Memory::Copy</code> -> <code>memcpy</code></li>
<li><code>Memory::Move</code> -> <code>memmove</code></li>
<li><code>Memory::Free</code> -> <code>free</code></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T20:18:29.917",
"Id": "32382",
"Score": "1",
"body": "For being _C++_ it looks a lot like _C#_... it even has some conceptual errors from thinking in _reference semantics_ instead of _value semantics_"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T22:39:17.000",
"Id": "32394",
"Score": "0",
"body": "memcpy()/memmove is not sufficient for the general case in C++ (though you can specialize it to work for certain types). Anything that is not POD type (or standard-layout types as K-ballo more accurately calls them) will have to be copied/moved using the copy/move constructors of the type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T22:39:53.193",
"Id": "32395",
"Score": "2",
"body": "Even getting things as fast as std::vector will be a struggle. It is very efficient."
}
] |
[
{
"body": "<p>The first and most obvious disadvantage of your <code>Vector</code> is that it does not satisfy the standard requirements for a <em>Sequence</em>. That means that your <code>Vector</code> cannot be used with any of the <em>standard algorithms</em> nor with 3rd party algorithms designed to work with <em>Sequences</em>. It is only useful to store elements, and nothing else.</p>\n\n<p>The lack of proper <em>constructors/destructor</em> and <em>assignment operator</em> will cause crashes and leaks every time your <code>Vector</code> is used. There is a lot to say on that subject, please search for a basic <em>C++</em> rule known as <em>The Rule of Three</em> which will let you know how you should write those special member functions to achieve the proper semantics.</p>\n\n<p>The next obvious drawback of your implementation is that one can only get <em>copies</em> of the elements stored in the <code>Vector</code>. This not only inconvenient, its also really inefficient. One has to make a copy of the element just to <em>read</em> it; and in order to <em>write</em> it one has to make a copy, modify said copy, remove the element from the <code>Vector</code> and then insert the modified copy. As said, this is both inconvenient and really inefficient. This would be a better approach for your subscript operator:</p>\n\n<pre><code>ItemType& operator[](UInt Position){ ... };\nItemType const& operator[](UInt Position) const{ ... };\n</code></pre>\n\n<p>This returns a <em>reference</em> to the stored element instead, so its possible to modify it in place if we have a <em>non-const</em> <code>Vector</code>.</p>\n\n<p>Another important drawback is that the <code>Vector</code> as implemented will only work with <em>standard-layout</em> types. Simply <em>moving</em> or <em>copying</em> the underlying memory for any other kind of type may result in garbled internal values, broken invariants, or even crashes and undefined behavior.</p>\n\n<p>The naming convention is strange to <em>C++</em>, it seems like something brought from a different language, perhaps <em>C#</em>. But the semantics are not the same, so as a result this <code>Vector</code> will look odd for a <em>C++</em> coder, and it will seem familiar to a <em>C#</em> coder which would be inclined to think the semantics are the ones from <em>C#</em>.</p>\n\n<p>You said that <em>This is intended to be a simpler replacement of <code>std::vector</code></em>. But if I were to replace <code>std::vector</code> with <code>Vector</code> the code would not even compile, and even if it would then the observed behavior would greatly differ. As a general rule, when you code in <em>C++</em> you should stick to <em>C++</em> conventions. The same applies for any other language as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T21:22:15.520",
"Id": "32388",
"Score": "0",
"body": "Thanks for the detailed review. I fixed the operator[] to return a reference and also added a const version.\nI did not intend for this class to be able to replace existing use of std::vector, so I am fine with it not qualifying as a sequence. I will look further into the _Rule of Three_, did you imply among other things that the constructor should be virtual?\nHow does this Vector not work with storing custom class? It does not simply copy the memory but also call the copy constructor on the added elements, and then their destructor when removing them. Again thanks for your review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T21:30:39.047",
"Id": "32391",
"Score": "0",
"body": "Ok so because there is no copy constructor defined, and no operator=, the compiler provides their default implementation. If either of those are used, `ItemType* VecPtr;` will simply be copied and point to the same memory as the source vector. I will be fixing that, thank you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T20:42:42.990",
"Id": "20249",
"ParentId": "20243",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T19:56:03.837",
"Id": "20243",
"Score": "4",
"Tags": [
"c++",
"vectors"
],
"Title": "Vector implementation - simple replacement"
}
|
20243
|
<p>This is my implementation of Conway's Game of Life in JavaScript. While I know that it runs slowly, I do not ask for performance improvements, but for a review on the code quality in general from professional JavaScript programmers.</p>
<p>Working HTML/CSS/JS files can be found <a href="http://www.mediafire.com/?8kd0aufsgd7oikt" rel="nofollow">here</a>.</p>
<p>Here is the main part of the code:</p>
<pre><code>(function(){
'use strict';
function getControl(api){
var buttonsControll = document.getElementsByTagName('canvas'),
buttonsRuleAlive = document.querySelectorAll('.btn_ruleAlive'),
buttonsRuleBorn = document.querySelectorAll('.btn_ruleBorn'),
button;
function drawRectangle(canvas, x){
canvas.fillRect(x, 1, 5, 10);
}
function drawTriangle(canvas, x, direction){
canvas.beginPath();
canvas.moveTo(x, 1);
canvas.lineTo(x, 11);
canvas.lineTo(x + 10 * direction, 6);
canvas.lineTo(x, 1);
canvas.fill();
}
function getIntervalTime(){
return parseInt(document.getElementById('tb_msPerFrame').value);
}
function getFields(){
return parseInt(document.getElementById('tb_fields').value);
}
function setNeighbors(){
var neighbors = parseInt(document.getElementById('sl_neighbors').value);
for(var i = 0; i < buttonsRuleAlive.length; i++){
if(i <= neighbors){
if(buttonsRuleAlive[i].className == 'btn_rule btn_ruleAlive btn_none'){
buttonsRuleAlive[i].className = 'btn_rule btn_ruleAlive btn_dieing';
buttonsRuleBorn[i].className = 'btn_rule btn_ruleBorn btn_dieing';
}
}
else{
buttonsRuleAlive[i].className = 'btn_rule btn_ruleAlive btn_none';
buttonsRuleBorn[i].className = 'btn_rule btn_ruleBorn btn_none';
}
}
api.setNeighbors(neighbors);
}
function usePreset(){
var preset = document.getElementById('sl_presets').value,
indexOf = preset.indexOf('/');
for(var i = 0; i < buttonsRuleAlive.length; i++){
setRulesAlive(i, 0);
setRulesBorn(i, 0);
}
for(var i in preset){
if(i < indexOf){
setRulesAlive(preset[i], 1);
}
else if(i > indexOf){
setRulesBorn(preset[i], 1);
}
}
}
function setRulesAlive(i, rule){
var ruleName = ['dieing', 'alive'];
if(buttonsRuleAlive[i].className != 'btn_rule btn_ruleAlive btn_none'){
buttonsRuleAlive[i].className = 'btn_rule btn_ruleAlive btn_' + ruleName[rule];
}
api.setRulesAlive(i, rule);
}
function setRulesBorn(i, rule){
var ruleName = ['dieing', 'born'];
if(buttonsRuleBorn[i].className != 'btn_rule btn_ruleBorn btn_none'){
buttonsRuleBorn[i].className = 'btn_rule btn_ruleBorn btn_' + ruleName[rule];
}
api.setRulesBorn(i, rule);
}
function setColorful(){
api.setColorful(document.getElementById('cb_colorful').checked);
}
function setEndless(){
api.setEndless(document.getElementById('cb_endless').checked);
}
for(i = 0; i < buttonsControll.length; i++){
buttonsControll[i].height = parseInt(buttonsControll[i].parentNode.scrollHeight) - 11;
buttonsControll[i].width = parseInt(buttonsControll[i].parentNode.scrollWidth) - 11;
}
button = document.getElementById('btn_fastRewind');
button.onclick = function(){
api.fastRewind();
}
buttonsControll = document.getElementById('canvas_fastRewind').getContext('2d');
drawRectangle(buttonsControll, 5);
drawTriangle(buttonsControll, 20, -1);
drawTriangle(buttonsControll, 30, -1);
button = document.getElementById('btn_rewind');
button.onclick = function(){
api.rewind();
}
buttonsControll = document.getElementById('canvas_rewind').getContext('2d');
drawTriangle(buttonsControll, 17, -1);
drawTriangle(buttonsControll, 27, -1);
button = document.getElementById('btn_lastFrame');
button.onclick = function(){
api.lastFrame();
}
buttonsControll = document.getElementById('canvas_lastFrame').getContext('2d');
drawTriangle(buttonsControll, 18, -1);
drawRectangle(buttonsControll, 21);
button = document.getElementById('btn_play');
button.onclick = function(){
api.play();
}
buttonsControll = document.getElementById('canvas_play').getContext('2d');
drawTriangle(buttonsControll, 13, 1);
button = document.getElementById('btn_pause');
button.style.display = 'none';
button.onclick = function(){
api.pause();
}
buttonsControll = document.getElementById('canvas_pause').getContext('2d');
drawRectangle(buttonsControll, 11);
drawRectangle(buttonsControll, 19);
button = document.getElementById('btn_nextFrame');
button.onclick = function(){
api.nextFrame();
}
buttonsControll = document.getElementById('canvas_nextFrame').getContext('2d');
drawRectangle(buttonsControll, 9);
drawTriangle(buttonsControll, 17, 1);
button = document.getElementById('btn_forward');
button.onclick = function(){
api.forward();
}
buttonsControll = document.getElementById('canvas_forward').getContext('2d');
drawTriangle(buttonsControll, 8, 1);
drawTriangle(buttonsControll, 18, 1);
button = document.getElementById('btn_fastForward');
button.onclick = function(){
api.fastForward();
}
buttonsControll = document.getElementById('canvas_fastForward').getContext('2d');
drawTriangle(buttonsControll, 5, 1);
drawTriangle(buttonsControll, 15, 1);
drawRectangle(buttonsControll, 25);
button = document.getElementById('btn_stop');
button.onclick = function(){
api.stop();
}
buttonsControll = document.getElementById('canvas_stop').getContext('2d');
buttonsControll.fillRect(13, 1, 10, 10);
document.getElementById('btn_msPerFrame').onclick = function(){
api.setIntervalTime(getIntervalTime());
}
document.getElementById('btn_fields').onclick = function(){
api.setFields(getFields());
}
document.getElementById('sl_neighbors').onchange = function(){
setNeighbors();
}
document.getElementById('sl_presets').onchange = function(){
usePreset();
}
for(var i in buttonsRuleAlive){
buttonsRuleAlive[i].onclick = (function(i){
return function(){
if(this.className == 'btn_rule btn_ruleAlive btn_dieing'){
this.className = 'btn_rule btn_ruleAlive btn_alive';
setRulesAlive(i, 1);
}
else if(this.className == 'btn_rule btn_ruleAlive btn_alive'){
this.className = 'btn_rule btn_ruleAlive btn_dieing';
setRulesAlive(i, 0);
}
}
}(i));
}
for(var i in buttonsRuleBorn){
buttonsRuleBorn[i].onclick = (function(i){
return function(){
if(this.className == 'btn_rule btn_ruleBorn btn_dieing'){
this.className = 'btn_rule btn_ruleBorn btn_born';
setRulesBorn(i, 1);
}
else if(this.className == 'btn_rule btn_ruleBorn btn_born'){
this.className = 'btn_rule btn_ruleBorn btn_dieing';
setRulesBorn(i, 0);
}
}
}(i));
}
document.getElementById('cb_colorful').onclick = setColorful;
document.getElementById('cb_endless').onclick = setEndless;
setColorful();
setEndless();
setNeighbors();
usePreset();
api.setIntervalTime(getIntervalTime());
api.setFields(getFields());
}
function constructCanvas(){
var cells = [[]],
canvas = document.getElementById('canvas'),
cellWidth = 16,
cellSpacing = 4,
colors,
colors0 = ['white', 'white', 'red', 'yellow', 'green'],
colors1 = ['white', 'white', 'white', 'black', 'black'],
ctx = canvas.getContext('2d'),
endless,
fields,
hist = [],
interval,
intervalTime,
module,
rulesAlive = [],
rulesBorn = [],
speed;
function constructHelperSquareTiles(){
var ratio = 2;
function getOffset(x){
return x * (cellWidth + cellSpacing);
}
return {
clearCanvas: function(){
for(var i = 1, w = 1, h = 1, x = 0, y = 0; i <= fields; i++){
cells[x][y] = emptyCell(x, y);
if(y + 1 == h && i >= Math.round(ratio * h * (h + 1))){
h++;
x = 0;
y++;
}
else if(y + 1 < h){
y++;
}
else{
x++;
if(i >= h * w){
cells[x] = [];
w++;
y = 0;
}
}
}
},
drawCanvas: function(){
var x = (function(){
if(fields == 2){
return 2;
}
for(var i = 0; Math.floor(1 / ratio * Math.pow(i, 2) - i + 1 - getProperModulo(i + ratio / 2, ratio) * (i / ratio - 1)) <= fields; i++);
return i - 1;
}()),
y = Math.round(Math.sqrt(fields / ratio));
return [getOffset(x) - cellSpacing + 3, getOffset(y) - cellSpacing + 3];
},
getOffset: getOffset
}
}
function constructModule3(){
var cellHeight = getPythagorasLeg(cellWidth, cellWidth / 2),
cellSpacingHeight = getPythagorasLeg(cellSpacing, cellSpacing / 2);
function getOffsetX(x){
var w = Math.floor(x / 4) * (3 * cellWidth + 3 * cellSpacing) + x % 2 * (cellWidth + cellSpacing);
if(x % 4 == 2 || x % 4 == 3){
w += 1.5 * cellWidth + 1.5 * cellSpacing;
}
return w;
}
function getOffsetY(y){
return y * (cellHeight + cellSpacingHeight);
}
return {
clearCanvas: function(){
for(var i = 0, w = 1, h = 0, x = 0, y = 0; i < fields; i++){
cells[x][y] = emptyCell(x, y);
if(x % 2 == 0){
x++;
if(!cells[x]){
cells[x] = [];
}
}
else{
if(x == w && y == h){
w += 2;
h++;
x++;
y = y % 2 == 0
? 1
: 0;
cells[x] = [];
}
else if(y < h){
x--;
y += 2;
if(y == h){
x = y % 2 == 0
? 0
: 2;
}
}
else{
x += 3;
}
}
}
},
drawCanvas: function(){
var x = (function(){
for(var i = 0, n = 0, x = 0; x < fields; i++){
if((i + 1) % 2 == 0 && i > 6){
n += Math.ceil((i - 6) / 4) * 4;
}
x = i + n;
}
return (x == fields)
? i - 2
: i - 3;
}()),
y = (function(){
for(var i = 1, x = 0; x < fields; i++){
x = Math.pow(i, 2) - i + 1;
}
return (x == fields)
? i - 2
: i - 3;
}());
return [getOffsetX(x) + cellWidth + 3, getOffsetY(y) + cellWidth + 3];
},
drawCell: function(x, y){
x = getOffsetX(x) + 1;
y = getOffsetY(y) + 1;
ctx.arc(x + cellWidth / 2, y + cellWidth / 2, cellWidth / 2, 0 , 2 * Math.PI);
},
getNeighbors: function(x, y){
var neighbors = 0;
if(x % 2 == 0){
if(cells[x - 1]){
neighbors += isAliveOrBorn(cells[x - 1][y - 1]);
neighbors += isAliveOrBorn(cells[x - 1][y + 1]);
}
if(cells[x + 1]){
neighbors += isAliveOrBorn(cells[x + 1][y]);
}
}
else{
if(cells[x - 1]){
neighbors += isAliveOrBorn(cells[x - 1][y]);
}
if(cells[x + 1]){
neighbors += isAliveOrBorn(cells[x + 1][y - 1]);
neighbors += isAliveOrBorn(cells[x + 1][y + 1]);
}
}
return neighbors;
},
selectCell: function(x, y){
var h = Math.floor(y / (cellHeight + cellSpacingHeight)),
w = h % 2 == 0
? x / (cellWidth + cellSpacing)
: (x + cellWidth / 2 + cellSpacing / 2) / (cellWidth + cellSpacing),
w = Math.floor(Math.floor(w) * 4 / 3);
if(h % 2 == 1 && w % 4 == 0){
w--;
}
if(getDistance(x, getOffsetX(w) + cellWidth / 2 + 1, y, getOffsetY(h) + cellWidth / 2 +1) < cellWidth / 2){
return [w, h];
}
return true;
}
}
}
function constructModule4(){
var helper = constructHelperSquareTiles();
return {
clearCanvas: helper.clearCanvas,
drawCanvas: helper.drawCanvas,
drawCell: function(x, y){
x = helper.getOffset(x) + 1;
y = helper.getOffset(y) + 1;
ctx.moveTo(x + cellWidth * .25, y);
ctx.lineTo(x + cellWidth * .75, y);
ctx.lineTo(x + cellWidth * .75, y + cellWidth * .25);
ctx.lineTo(x + cellWidth, y + cellWidth * .25);
ctx.lineTo(x + cellWidth, y + cellWidth * .75);
ctx.lineTo(x + cellWidth * .75, y + cellWidth * .75);
ctx.lineTo(x + cellWidth * .75, y + cellWidth);
ctx.lineTo(x + cellWidth * .25, y + cellWidth);
ctx.lineTo(x + cellWidth * .25, y + cellWidth * .75);
ctx.lineTo(x, y + cellWidth * .75);
ctx.lineTo(x, y + cellWidth * .25);
ctx.lineTo(x + cellWidth * .25, y + cellWidth * .25);
ctx.lineTo(x + cellWidth * .25, y - 1);
},
getNeighbors: function(x, y){
var neighbors = 0;
neighbors += isAliveOrBorn(cells[x][y - 1]);
neighbors += isAliveOrBorn(cells[x][y + 1]);
if(cells[x - 1]){
neighbors += isAliveOrBorn(cells[x - 1][y]);
}
if(cells[x + 1]){
neighbors += isAliveOrBorn(cells[x + 1][y]);
}
return neighbors;
},
selectCell: function(x, y){
var w = Math.floor(x / (cellWidth + cellSpacing)),
h = Math.floor(y / (cellWidth + cellSpacing));
if((isInsideAngle(helper.getOffset(w) + cellWidth * .25, helper.getOffset(h), x, y, 1.5, 2) == 0 && isInsideAngle(helper.getOffset(w) + cellWidth * .75, helper.getOffset(h) + cellWidth, x, y, .5, 1) == 0) || (isInsideAngle(helper.getOffset(w), helper.getOffset(h) + cellWidth * .25, x, y, 1.5, 2) == 0 && isInsideAngle(helper.getOffset(w) + cellWidth, helper.getOffset(h) + cellWidth * .75, x, y, .5, 1) == 0)){
return [w, h];
}
return true;
}
}
}
function constructModule6(){
var cellSize = cellWidth * 1.25,
cellHeight = getPythagorasLeg(cellSize, cellSize / 2),
cellSpacingHeight = getPythagorasLeg(cellSpacing, cellSpacing / 2),
offsetX = [cellSize / 4 + 1, cellSize + cellSpacingHeight + 1],
offsetY = [1, cellHeight / 2 + cellSpacing / 2 + 1];
function getOffsetX(x){
return Math.floor(x / 2) * (cellSize * 1.5 + cellSpacingHeight * 2);
}
function getOffsetY(y){
return Math.floor(y / 2) * (cellHeight + cellSpacing);
}
return {
clearCanvas: function(){
for(var i = 0, x = 0, y = 0; i < fields; i++){
cells[x][y] = emptyCell(x, y);
if(x == y){
x++;
y = y % 2 == 0
? 1
: 0;
cells[x] = [];
}
else if(y + 2 < x){
y += 2;
}
else if(y + 2 == x){
x = x % 2 == 0
? 0
: 1;
y += 2;
}
else{
x += 2;
}
}
},
drawCanvas: function(){
var x = (function(){
for(var i = 0; Math.ceil(Math.pow(i, 2) / 2 + 1) <= fields; i++);
return i;
}()),
y = (function(){
return fields < (Math.pow(x, 2) - x) / 2 + 1
? x - 1
: x;
}());
return [getOffsetX(x) + x % 2 * (cellSize + cellSpacingHeight) + (x + 1) % 2 * cellSize / 4 + 3, getOffsetY(y) + y % 2 * cellHeight + (y + 1) % 2 * (cellHeight / 2 - cellSpacing / 2) + 3];
},
drawCell: function(x, y){
x = getOffsetX(x) + offsetX[x % 2];
y = getOffsetY(y) + offsetY[y % 2];
ctx.moveTo(x, y);
ctx.lineTo(x + cellSize / 2, y);
ctx.lineTo(x + cellSize * .75, y + cellHeight / 2);
ctx.lineTo(x + cellSize / 2, y + cellHeight);
ctx.lineTo(x, y + cellHeight);
ctx.lineTo(x - cellSize / 4, y + cellHeight / 2);
ctx.lineTo(x, y);
},
getNeighbors: function(x, y){
var neighbors = 0;
neighbors += isAliveOrBorn(cells[x][y - 2]);
neighbors += isAliveOrBorn(cells[x][y + 2]);
if(cells[x - 1]){
neighbors += isAliveOrBorn(cells[x - 1][y - 1]);
neighbors += isAliveOrBorn(cells[x - 1][y + 1]);
}
if(cells[x + 1]){
neighbors += isAliveOrBorn(cells[x + 1][y - 1]);
neighbors += isAliveOrBorn(cells[x + 1][y + 1]);
}
return neighbors;
},
selectCell: function(x, y){
var w = Math.floor(x * 2 / (cellSize * 1.5 + cellSpacingHeight * 2)),
h = y / (cellHeight + cellSpacing),
h = w % 2 == 0
? Math.floor(h) * 2
: Math.floor(h - .5) * 2 + 1,
offsetX2 = getOffsetX(w) + w % 2 * (cellSize * .75 + cellSpacingHeight) + 1,
offsetY2 = getOffsetY(h) + h % 2 * (cellHeight / 2 + cellSpacing / 2) + 1,
isInside = isInsideAngle(offsetX2, offsetY2 + cellHeight / 2, x, y, 5 / 3, 7 / 3);
if(isInside == 0 && (isInsideAngle(offsetX2 + cellSize * .75, offsetY2, x, y, 1, 5 / 3) != 0 || isInsideAngle(offsetX2 + cellSize * .75, offsetY2 + cellHeight, x, y, 1 / 3, 1) != 0)){
return true;
}
else if(isInside == 1 && isInsideAngle(offsetX2 - cellSize * .75 - cellSpacingHeight, offsetY2 - cellSpacing / 2, x, y, 5 / 3, 1 / 3) == 0 && isInsideAngle(offsetX2 - cellSpacingHeight, offsetY2 - cellHeight / 2 - cellSpacing / 2, x, y, 1, 5 / 3) == 0 && isInsideAngle(offsetX2 - cellSpacingHeight, offsetY2 + cellHeight / 2 - cellSpacing / 2, x, y, 1 / 3, 1) == 0){
w -= 1;
h -= 1;
}
else if(isInside == -1 && isInsideAngle(offsetX2 - cellSize * .75 - cellSpacingHeight, offsetY2 + cellHeight + cellSpacing / 2, x, y, 5 / 3, 1 / 3) == 0 && isInsideAngle(offsetX2 - cellSpacingHeight, offsetY2 + cellHeight / 2 + cellSpacing / 2, x, y, 1, 5 / 3) == 0 && isInsideAngle(offsetX2 - cellSpacingHeight, offsetY2 + cellHeight * 1.5 + cellSpacing / 2, x, y, 1 / 3, 1) == 0){
w -= 1;
h += 1;
}
return [w, h];
}
}
}
function constructModule7(){
var helper = constructHelperSquareTiles(),
ratio = 2;
function getOffsetX(x, y){
return helper.getOffset(x) + (y % 4 == 2 || y % 4 == 3) * (cellWidth / 2 + cellSpacing / 2);
}
function getOffsetY(y){
return helper.getOffset(y);
}
return {
clearCanvas: helper.clearCanvas,
drawCanvas: function(){
var x = (function(){
if(fields == 2){
return 2;
}
for(var i = 0; Math.floor(1 / ratio * Math.pow(i, 2) - i + 1 - getProperModulo(i + ratio / 2, ratio) * (i / ratio - 1)) <= fields; i++);
return i - 1;
}()),
y = Math.round(Math.sqrt(fields / ratio));
return [getOffsetX(x) - cellSpacing + (y > 2) * (cellWidth / 2 + cellSpacing / 2) + 3, getOffsetY(y) - cellSpacing + 3];
},
drawCell: function(x, y){
x = getOffsetX(x, y) + 1;
y = getOffsetY(y) + 1;
ctx.moveTo(x, y);
ctx.lineTo(x + cellWidth, y);
ctx.lineTo(x + cellWidth, y + cellWidth);
ctx.lineTo(x, y + cellWidth);
ctx.lineTo(x, y - 1);
},
getNeighbors: function(x, y){
var neighbors = 0;
neighbors += isAliveOrBorn(cells[x][y - 1]);
neighbors += isAliveOrBorn(cells[x][y + 1]);
if(cells[x - 1]){
neighbors += isAliveOrBorn(cells[x - 1][y]);
if(y % 4 == 0 || y % 4 == 1 || y % 4 == 3){
neighbors += isAliveOrBorn(cells[x - 1][y - 1]);
}
if(y % 4 == 0 || y % 4 == 1 || y % 4 == 2){
neighbors += isAliveOrBorn(cells[x - 1][y + 1]);
}
}
if(cells[x + 1]){
neighbors += isAliveOrBorn(cells[x + 1][y]);
if(y % 4 == 1 || y % 4 == 2 || y % 4 == 3){
neighbors += isAliveOrBorn(cells[x + 1][y - 1]);
}
if(y % 4 == 0 || y % 4 == 2 || y % 4 == 3){
neighbors += isAliveOrBorn(cells[x + 1][y + 1]);
}
}
return neighbors;
},
selectCell: function(x, y){
var h = Math.floor(y / (cellWidth + cellSpacing)),
w = Math.floor((x - (h % 4 == 2 || h % 4 == 3) * (cellWidth / 2 + cellSpacing / 2)) / (cellWidth + cellSpacing));
if(getOffsetX(w, h) + cellWidth < x || getOffsetY(h) + cellWidth < y){
return true;
}
return [w, h];
}
}
}
function constructModule8(){
var helper = constructHelperSquareTiles();
return {
clearCanvas: helper.clearCanvas,
drawCanvas: helper.drawCanvas,
drawCell: function(x, y){
x = helper.getOffset(x) + 1;
y = helper.getOffset(y) + 1;
ctx.moveTo(x, y);
ctx.lineTo(x + cellWidth, y);
ctx.lineTo(x + cellWidth, y + cellWidth);
ctx.lineTo(x, y + cellWidth);
ctx.lineTo(x, y - 1);
},
getNeighbors: function(x, y){
var neighbors = 0;
neighbors += isAliveOrBorn(cells[x][y - 1]);
neighbors += isAliveOrBorn(cells[x][y + 1]);
if(cells[x - 1]){
neighbors += isAliveOrBorn(cells[x - 1][y - 1]);
neighbors += isAliveOrBorn(cells[x - 1][y]);
neighbors += isAliveOrBorn(cells[x - 1][y + 1]);
}
if(cells[x + 1]){
neighbors += isAliveOrBorn(cells[x + 1][y - 1]);
neighbors += isAliveOrBorn(cells[x + 1][y]);
neighbors += isAliveOrBorn(cells[x + 1][y + 1]);
}
return neighbors;
},
selectCell: function(x, y){
var w = Math.floor(x / (cellWidth + cellSpacing)),
h = Math.floor(y / (cellWidth + cellSpacing));
if(helper.getOffset(w) + cellWidth < x || helper.getOffset(h) + cellWidth < y){
return true;
}
return [w, h];
}
}
}
function isAliveOrBorn(n){
return n == 3 || n == 4;
}
function startInterval(func, s){
speed = s;
stopInterval();
displayPause();
interval = setInterval(func, intervalTime / speed);
}
function stopInterval(){
if(interval != null){
clearInterval(interval);
displayPlay();
interval = null;
}
}
function forward(){
var nextFrame = [],
neighbors, n, x, y;
for(x in cells){
nextFrame[x] = [];
for(y in cells[x]){
neighbors = module.getNeighbors(parseInt(x), parseInt(y));
switch(cells[x][y]){
case 0:
if(rulesBorn[neighbors] == 1){
nextFrame[x][y] = bornCell(x, y);
}
else{
nextFrame[x][y] = 0;
}
break;
case 1:
if(rulesBorn[neighbors] == 1){
nextFrame[x][y] = bornCell(x, y);
}
else{
nextFrame[x][y] = 1;
}
break;
case 2:
if(rulesBorn[neighbors] == 1){
nextFrame[x][y] = bornCell(x, y);
}
else{
nextFrame[x][y] = deadCell(x, y);
}
break;
case 3:
if(rulesAlive[neighbors] == 1){
nextFrame[x][y] = aliveCell(x, y);
}
else{
nextFrame[x][y] = dieingCell(x, y);
}
break;
case 4:
if(rulesAlive[neighbors] == 1){
nextFrame[x][y] = aliveCell(x, y);
}
else{
nextFrame[x][y] = dieingCell(x, y);
}
break;
}
}
}
if(isEqual(cells, nextFrame)){
stopInterval();
return;
}
if(!endless){
for(n in hist){
if(isEqual(hist[hist.length - n - 1], nextFrame)){
stopInterval();
return;
}
}
}
hist.push(cells);
cells = nextFrame;
}
function backward(){
if(hist.length > 0){
var lastFrame = hist.pop();
for(var x in lastFrame){
for(var y in lastFrame){
if(lastFrame[x][y] != cells[x][y]){
switch(lastFrame[x][y]){
case 0:
cells[x][y] = emptyCell(x, y);
break;
case 1:
cells[x][y] = deadCell(x, y);
break;
case 2:
cells[x][y] = dieingCell(x, y);
break;
case 3:
cells[x][y] = aliveCell(x, y);
break;
case 4:
cells[x][y] = bornCell(x, y);
break;
}
}
}
}
}
else{
stopInterval();
}
}
function drawCanvas(){
var dim = module.drawCanvas();
cells = [[]];
hist = [];
canvas.width = dim[0];
canvas.height = dim[1];
ctx.clearRect(1, 1, dim[0], dim[1]);
module.clearCanvas();
canvas.onmousedown = function(e){
var fill;
function fillCell(index, fill){
if(index === true){
return true;
}
fill = fill
? 0
: (fill == false
? 3
: cells[index[0]][index[1]]);
if(index[0] in cells && index[1] in cells[index[0]]){
if(fill == 3 || fill == 4){
cells[index[0]][index[1]] = emptyCell(index[0], index[1]);
return false;
}
else{
cells[index[0]][index[1]] = bornCell(index[0], index[1]);
return true;
}
}
}
if(e.button == 0){
stopInterval();
fill = fillCell(module.selectCell(e.pageX - this.offsetLeft, e.pageY - this.offsetTop));
hist = [];
this.onmousemove = function(e){
fillCell(module.selectCell(e.pageX - this.offsetLeft, e.pageY - this.offsetTop), fill);
};
this.onmouseup = function(){
this.onmousemove = null;
};
}
}
}
function drawCell(x, y, fill){
ctx.beginPath();
module.drawCell(x, y);
ctx.fillStyle = fill;
ctx.strokeStyle = 'white';
ctx.lineWidth = 4;
ctx.stroke();
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
ctx.stroke();
ctx.fill();
}
function emptyCell(x, y){
drawCell(x, y, colors[0]);
return 0;
}
function deadCell(x, y){
drawCell(x, y, colors[1]);
return 1;
}
function dieingCell(x, y){
drawCell(x, y, colors[2]);
return 2;
}
function aliveCell(x, y){
drawCell(x, y, colors[3]);
return 3;
}
function bornCell(x, y){
drawCell(x, y, colors[4]);
return 4;
}
return {
fastRewind: function(){
startInterval(backward, 16);
},
rewind: function(){
startInterval(backward, 4);
},
lastFrame: function(){
stopInterval();
backward();
},
play: function(){
startInterval(forward, 1);
},
pause: function(){
stopInterval();
},
nextFrame: function(){
stopInterval();
forward();
},
forward: function(){
startInterval(forward, 4);
},
fastForward: function(){
startInterval(forward, 16);
},
stop: function(){
hist = [];
stopInterval();
module.clearCanvas();
},
setColorful: function(bool){
colors = bool
? colors0
: colors1;
for(var x in cells){
for(var y in cells){
switch(cells[x][y]){
case 0:
emptyCell(x, y);
break;
case 1:
deadCell(x, y);
break;
case 2:
dieingCell(x, y);
break;
case 3:
aliveCell(x, y);
break;
case 4:
bornCell(x, y);
break;
}
}
}
},
setEndless: function(bool){
endless = bool;
},
setFields: function(number){
fields = number;
drawCanvas();
},
setIntervalTime: function setIntervalTime(interval){
intervalTime = interval;
},
setNeighbors: function(i){
stopInterval();
switch(i){
case 3:
module = constructModule3();
break;
case 4:
module = constructModule4();
break;
case 6:
module = constructModule6();
break;
case 7:
module = constructModule7();
break;
case 8:
module = constructModule8();
break;
}
drawCanvas();
},
setRulesAlive: function(i, rule){
rulesAlive[i] = rule;
},
setRulesBorn: function(i, rule){
rulesBorn[i] = rule;
}
}
}
window.onload = function(){
getControl(constructCanvas());
}
}());
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T21:31:01.040",
"Id": "32392",
"Score": "0",
"body": "For a start, I'd get rid of the magic number."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T13:11:42.397",
"Id": "32422",
"Score": "0",
"body": "That is correct, but some are obvious to me and some other are just unimportant (wont change, reused, eye candy...). But I guess my problem is that I have a hard time finding variable names for them.\nAnything else you would suggest?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-19T21:48:55.713",
"Id": "35216",
"Score": "1",
"body": "For starters I would run it through [JSHint](http://www.jshint.com) and abide by some [coding standards](http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml). It's hard to give any real advice because there's just _so much code_. I genuinely think you'd learn a lot from re-writing this with an emphasis on reducing the amount of code."
}
] |
[
{
"body": "<p>There is a ton here, these are my 2 cents:</p>\n\n<ul>\n<li>Read about Model View Controller, and implement it</li>\n<li>More specifically, knowing the state of a cell by checking the class name is bad form</li>\n<li>Read about the cool Array functions that exist ( filter, forEach etc. ), they could make a huge difference in your logic code</li>\n<li>Read about DRY ( Dont Repeat Yourself ), your code should be much DRYer</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-20T20:13:24.797",
"Id": "31599",
"ParentId": "20250",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "31599",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T21:00:12.897",
"Id": "20250",
"Score": "3",
"Tags": [
"javascript",
"game-of-life"
],
"Title": "Main implementation of Game of Life"
}
|
20250
|
<p>I am currently learning C++ (note: I am using C++11) and have begun working on a small project to practice what I've been learning. This project is a deck of cards that I hope to use later to create simple card games. I have created three classes: <code>Card</code> represents a single playing card, <code>CardStack</code> represents a stack of cards (e.g., to be used for a "hand" or "discard pile", etc.), and <code>Deck</code> is a sub-class of CardStack that contains all 52 cards in a standard deck of cards.</p>
<p>In addition to a general review of my code, I am specifically looking for feedback/answers to the following:</p>
<ol>
<li>Is there a better container choice than <code>std::vector</code> to hold <code>Card</code>s? If so, why?</li>
<li>Should I be storing a pointer to <code>Card</code> rather than copies of <code>Card</code> in <code>CardStack::cards</code>? If so, should I use <code>std::shared_ptr</code> or <code>std::unique_ptr</code>?</li>
<li>How do you feel about my choice to make <code>card_transfer</code> and <code>draw_card</code> functions rather than members of <code>CardStack</code> and <code>Deck</code>, respectively? Does <code>Deck::draw_card(CardStack&, unsigned)</code> make more sense? Why?</li>
<li>My method to move <code>Card</code>s from one <code>CardStack</code> to another right now is to copy it over than erase it from the source. I understand C++11 introduced move semantics. Is this the kind of place this type of behaviour should be implemented?</li>
<li>Obviously only one copy of a <code>Card</code> should exist at any time (if this is a standard deck of cards). How can I go about enforcing this?</li>
<li>I included the method <code>CardStack::string_to_iter</code> to facilitate input from the user in selecting a card (i.e., he or she can enter 'Ts' for the ten of spades). Is there anything wrong with how I did this? I decided that input validation would be done on the game level, and this method assumes valid input. Is this a good idea?</li>
</ol>
<p><strong>cards.h:</strong></p>
<pre><code>#ifndef CARDS_H
#define CARDS_H
#include <iostream>
#include <vector>
#include <random>
#include <ctime>
#include <string>
/***************************
Card
***************************/
struct Card
{
// Data
unsigned rank;
char suit;
// Constructors
Card(unsigned r, char s) : rank(r), suit(s) {};
// Copy control
Card(const Card &c) : rank(c.rank), suit(c.suit) {}
Card& operator=(const Card &rhs) {rank = rhs.rank; suit = rhs.suit;}
// Methods
std::string to_string() const;
};
// Operators
bool operator==(const Card &lhs, const Card &rhs);
bool operator!=(const Card &lhs, const Card &rhs);
bool operator<(const Card &lhs, const Card &rhs);
bool operator>(const Card &lhs, const Card &rhs);
std::ostream& operator<<(std::ostream &os, const Card &card);
/***************************
CardStack
***************************/
class CardStack
{
private:
// Data
std::default_random_engine rand_eng;
protected:
// Methods
std::vector<Card>::iterator string_to_iter(std::string);
public:
// Data
std::vector<Card> cards;
// Constructors
CardStack() {rand_eng.seed(time(0));}
// Methods
std::size_t size() const {return cards.size();}
CardStack& shuffle();
CardStack& sort_rank();
};
// Operators
std::ostream& operator <<(std::ostream&, const CardStack&);
// Functions
void card_transfer(CardStack &source, CardStack &dest); // transfer all cards to end of dest
void card_transfer(CardStack &source, CardStack &dest, Card&); // transfer specific card to end of dest
/***************************
Deck : public CardStack
***************************/
class Deck : public CardStack
{
friend void draw_cards(Deck&, CardStack&, unsigned quantity);
public:
// Constructors
Deck();
// Methods
Card& top();
};
// Functions
void draw_card(Deck&, CardStack&, unsigned quantity = 1);
#endif
</code></pre>
<p><strong>cards.cpp:</strong></p>
<pre><code>#include <iostream>
#include <vector>
#include <array>
#include <algorithm>
#include <iterator>
#include <string>
#include "cards.h"
using std::vector;
using std::array;
using std::string;
const array<unsigned, 13> RANKS = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
const array<char, 4> SUITS = {'c', 'd', 'h', 's'};
/***************************
Card
***************************/
string Card::to_string() const
{
string r;
switch (rank)
{
case 1:
r = "A"; break;
case 10:
r = "T"; break;
case 11:
r = "J"; break;
case 12:
r = "Q"; break;
case 13:
r = "K"; break;
default:
r = std::to_string(rank);
}
return r + suit;
}
bool operator==(const Card &lhs, const Card &rhs) {return lhs.rank == rhs.rank && lhs.suit == rhs.suit;}
bool operator!=(const Card &lhs, const Card &rhs) {return !(lhs == rhs);}
bool operator<(const Card &lhs, const Card &rhs) {return lhs.rank < rhs.rank;}
bool operator>(const Card &lhs, const Card &rhs) {return !(lhs < rhs);}
std::ostream& operator<<(std::ostream &os, const Card &card)
{
os << card.to_string();
return os;
}
/***************************
CardStack
***************************/
vector<Card>::iterator CardStack::string_to_iter(string str)
{
// Returns iterator to specified card in cards, otherwise returns cards.end()
return std::find_if(cards.begin(), cards.end(), [str] (const Card &c) {return c.to_string() == str;});
}
CardStack& CardStack::shuffle()
{
std::shuffle(cards.begin(), cards.end(), rand_eng);
return *this;
}
CardStack& CardStack::sort_rank()
{
std::sort(cards.begin(), cards.end());
return *this;
}
std::ostream& operator<<(std::ostream &os, const CardStack &cs)
{
for (auto c : cs.cards)
os << c << " ";
return os;
}
void card_transfer(CardStack &source, CardStack &dest)
{
while (source.cards.size() > 0)
{
auto it = source.cards.begin();
dest.cards.push_back(*it);
source.cards.erase(it);
}
}
void card_transfer(CardStack &source, CardStack &dest, Card &card)
{
auto it = std::find(source.cards.begin(), source.cards.end(), card);
if (it != source.cards.end())
{
dest.cards.push_back(*it);
source.cards.erase(it);
}
}
/***************************
Deck : public CardStack
***************************/
Deck::Deck()
{
for (const auto &r : RANKS)
for (const auto &s : SUITS)
cards.emplace_back(r, s);
}
Card& Deck::top()
{
return cards.front();
}
void draw_cards(Deck &deck, CardStack &cs, unsigned quantity = 1)
{
// Copy cards from deck to specified card stack
std::copy(deck.cards.begin(), deck.cards.begin() + quantity, std::back_inserter(cs.cards));
// Erase cards from deck
deck.cards.erase(deck.cards.begin(), deck.cards.begin() + quantity);
}
</code></pre>
|
[] |
[
{
"body": "<h3>Answers</h3>\n<blockquote>\n<p>Is there a better container choice than std::vector to hold Cards? If so, why?</p>\n</blockquote>\n<p>Depends.</p>\n<blockquote>\n<p>Should I be storing a pointer to Card rather than copies of Card in CardStack::cards?</p>\n</blockquote>\n<p>No. You should be storing by value.</p>\n<blockquote>\n<p>If so, should I use std::shared_ptr or std::unique_ptr?</p>\n</blockquote>\n<p>No. But the choice would depend on how you define ownership.</p>\n<blockquote>\n<p>How do you feel about my choice to make card_transfer and draw_card functions rather than members of CardStack and Deck, respectively?</p>\n</blockquote>\n<p>Don't like it. But it may work. The principle of "Separation of Concerns" your class should either "business logic (card stuff)" or "Resource Management (card container)" The question you need to decide is if <code>CardStack</code> is doing business logic or resource management.</p>\n<blockquote>\n<p>Does Deck::draw_card(CardStack&, unsigned) make more sense? Why?</p>\n</blockquote>\n<p>I think so: This way you are hiding the implementation but providing a neat interface.</p>\n<blockquote>\n<p>My method to move Cards from one CardStack to another right now is to copy it over than erase it from the source. I understand C++11 introduced move semantics. Is this the kind of place this type of behaviour should be implemented?</p>\n</blockquote>\n<p>No. Move semantics leaves the source in an undefined state (this is not what move semantics are for). Move is used to move an object efficiently to a destination where the source is no longer valid.</p>\n<blockquote>\n<p>Obviously only one copy of a Card should exist at any time (if this is a standard deck of cards). How can I go about enforcing this?</p>\n</blockquote>\n<p>Not sure. But I don't think its a big problem.</p>\n<blockquote>\n<p>I included the method CardStack::string_to_iter to facilitate input from the user in selecting a card (i.e., he or she can enter 'Ts' for the ten of spades). Is there anything wrong with how I did this? I decided that input validation would be done on the game level, and this method assumes valid input. Is this a good idea?</p>\n</blockquote>\n<p>I would have defined an input operator <code>std::istream& operator>>(std::istream& s, Card& c);</code></p>\n<h3>Review</h3>\n<pre><code>struct Card\n{\n // Data\n unsigned rank;\n char suit;\n // Constructors\n Card(unsigned r, char s) : rank(r), suit(s) {};\n</code></pre>\n<p>Default version of Copy constructor and assignment operator already do this:</p>\n<pre><code> // Copy control\n Card(const Card &c) : rank(c.rank), suit(c.suit) {}\n Card& operator=(const Card &rhs) {rank = rhs.rank; suit = rhs.suit; /*You forgot the return *this;*/}\n</code></pre>\n<p>Sure this is fine.<br />\nBut (personally) I would not bother.</p>\n<pre><code> // Methods\n std::string to_string() const;\n};\n\n\nclass CardStack\n{\n private:\n // Data\n std::default_random_engine rand_eng;\n</code></pre>\n<p>Protected does not really give you much.<br />\nStroustrup even indicated that he now thinks this was a mistake.<br />\nTo access it all I need to do is inherit from your class. If I really want I can then expose it publicly for others. Thus it really provides no protection.</p>\n<pre><code> protected:\n // Methods\n</code></pre>\n<p>Exposing the iterator type here locks you into that type. I would define my own iterator type locally to the CardStack (see below).</p>\n<pre><code> std::vector<Card>::iterator string_to_iter(std::string);\n public:\n</code></pre>\n<p>Here you are exposing the cards. Thus allows the internal state to be changed. This is a no no. Lock up the interface only allow the state to be changed via a very specific closed interface (also note you are locking yourself to vector).</p>\n<pre><code> // Data\n std::vector<Card> cards;\n\n // Constructors\n CardStack() {rand_eng.seed(time(0));}\n // Methods\n std::size_t size() const {return cards.size();}\n CardStack& shuffle();\n CardStack& sort_rank();\n};\n</code></pre>\n<p>I would have defined the Iterator type like this:</p>\n<pre><code>class CardStack\n{\n typedef std::vector<Card> Container;\n public:\n typedef Container::iterator iterator;\n typedef Container::const_iterator const_iterator;\n};\n</code></pre>\n<p>Now you expose an iterator type. But the user of the iterator can not assume anything about it or the underlying container type.</p>\n<p>Not sure this is a good idea:</p>\n<pre><code>bool operator<(const Card &lhs, const Card &rhs) {return lhs.rank < rhs.rank;}\n</code></pre>\n<p>If you use <code>Card</code> as the key in a map or set then things will break. As you do not define a <code>Strict Weak ordering</code>.</p>\n<p>Small thing:</p>\n<pre><code>vector<Card>::iterator CardStack::string_to_iter(string str) \n{\n // Returns iterator to specified card in cards, otherwise returns cards.end()\n return std::find_if(cards.begin(), cards.end(), [str] (const Card &c) {return c.to_string() == str;});\n}\n</code></pre>\n<p>Pass the str by const reference.</p>\n<pre><code>vector<Card>::iterator CardStack::string_to_iter(string const& str) \n{\n // Returns iterator to specified card in cards, otherwise returns cards.end()\n return std::find_if(cards.begin(), cards.end(), [str const&] (const Card &c) {return c.to_string() == str;});\n}\n</code></pre>\n<p>This is not very efficient:</p>\n<pre><code>void card_transfer(CardStack &source, CardStack &dest)\n{\n while (source.cards.size() > 0)\n {\n auto it = source.cards.begin();\n dest.cards.push_back(*it);\n source.cards.erase(it);\n }\n}\n</code></pre>\n<p>Given the sizes its not a real big deal. But I would have done:</p>\n<pre><code>void card_transfer(CardStack &source, CardStack &dest)\n{\n dest.insert(dest.cards.end(), source.cards.begin(), source.cards.end());\n source.clear();\n}\n\n\n \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T13:44:09.527",
"Id": "32424",
"Score": "0",
"body": "Thanks a lot for your input. Follow-up: (i) Could you elaborate your answer to my second question (why I should be storing by value?) (ii) You mentioned I should not expose the cards by returning an iterator, but you then go on to use typedefs to define iterators and then expose them. I'm a little confused on how that is different. Are you saying I shouldn't expose iterators or not? (iii) If `CardStack::cards` is public, doesn't that also expose the cards? However, if I make it private, how can I do things like transferring cards when I can't access `cards` of the destination? Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T16:19:11.390",
"Id": "32432",
"Score": "0",
"body": "The question is why would you not store them by value? If you use pointers then you introduce a whole new set of problems with managing the pointers. Unless the object is extremely expensive to copy the default action should be by value (if it is expensive then you can design a wrapper class). C++11 has a new implace push_back so you don't actually get a copy when inserting into the vector it is constructed in place so even for big objects this problem is mitigated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T16:24:14.313",
"Id": "32434",
"Score": "0",
"body": "You missed the point on iterator: You are exposing `std::vector<Card>::iterator`. This means that anybody using the class is now has to use `std::vector` which ties you to the implementation of using a vector (if you change then everybody using your code must also be manually changed). The alternative is to expose an iterator that is relative to the your class. My code exposes the iterator `CardStack::iterator`. Now people using the code are not tied to an implementation. If I change the internal representation to a std::list<Card> a simple re-compile of theor code will update it correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T16:26:11.173",
"Id": "32435",
"Score": "0",
"body": "You can still write `transferring_cards()` with a private version of `cards` by making `transfer_cards()` a friend of the class (or by making it a member method). You should practically never expose member `variables` as public (or protected)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T18:33:09.523",
"Id": "32445",
"Score": "0",
"body": "Thank you very much for your help. I understand your point about the iterator. However, did you also mean that I shouldn't be exposing an iterator in the first place because that would allow users of the class to change the private member variable `cards`? Thanks again for your help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T19:18:41.257",
"Id": "32456",
"Score": "0",
"body": "Personally I would not expose an iterator. **BUT** the way you are suing it is perfectly fine and just a difference in style (as long as the iterator you expose does not expose a particular implementation). But you do intimate the cards in the deck are imutable objects so I would rather expose a const_iterator so the user can not modify them (but can read them)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T05:29:46.513",
"Id": "20265",
"ParentId": "20254",
"Score": "6"
}
},
{
"body": "<p>With regards to containers to store your cards in:</p>\n\n<p>If you know that there will only be a set number (at compile time) of cards you might prefer <code>std::array</code> over <code>std::vector</code>, as <code>std::array</code> has slightly less overhead then vector, but cannot be resized.</p>\n\n<p>If you know that you always want to draw from the top of the deck and never draw from the middle or the bottom you might consider the container wrapper std::queue which enforces FIFO insertion and removal from the container. The default container wrapped by <code>std::queue</code> is <code>std::deque</code> which is optimized for insertion and removal at both ends of the container.</p>\n\n<p>If your top priority is ensuring that all of the cards in the deck are unique you might consider using <code>std::set</code> which enforces that all elements are unique, but then you don't really have control over the order of the cards in the deck. Another way to achieve card uniqueness would be to use the std algorithms for unique such as <code>std::unique</code>.</p>\n\n<p>If you plan on adding and removing cards from the middle of the deck frequently, you might consider using <code>std::list</code>, but unless you're trying to implement some strange form of dealing cards (say for a magic trick simulation) I can't imagine why that would be a priority.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-12T22:41:59.640",
"Id": "37261",
"ParentId": "20254",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20265",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T23:09:36.130",
"Id": "20254",
"Score": "7",
"Tags": [
"c++",
"classes",
"c++11",
"playing-cards"
],
"Title": "Playing cards in C++"
}
|
20254
|
<p>I use the following functions to encrypt my <code>$_GET</code> variables (whenever I can't easily get away with using <code>$_POST</code> or some other way of passing information between pages). </p>
<pre><code>function decryptStringArray ($stringArray, $key = "Your secret salt thingie")
{
$s = unserialize(rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode(strtr($stringArray, '-_,', '+/=')), MCRYPT_MODE_CBC, md5(md5($key))), "\0"));
return $s;
}
function encryptStringArray ($stringArray, $key = "Your secret salt thingie")
{
$s = strtr(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), serialize($stringArray), MCRYPT_MODE_CBC, md5(md5($key)))), '+/=', '-_,');
return $s;
}
function prepareUrl($url, $key = "Your secret salt thingie")
{
$url = explode("?",$url,2);
if(sizeof($url) <= 1)
return $url;
else
return $url[0]."?params=".encryptStringArray($url[1],$key);
}
function setGET($params,$key = "Your secret salt thingie")
{
$params = decryptStringArray($params,$key);
$param_pairs = explode('&',$params);
foreach($param_pairs as $pair)
{
$split_pair = explode('=',$pair);
$_GET[$split_pair[0]] = $split_pair[1];
}
}
</code></pre>
<p>Obviously I replace the "Your secret salt thingie" with other strings. Here is how I use it:</p>
<p>On the page where I need a URL: </p>
<pre><code>$url = prepareUrl("http://someurl.com?variable1=1314&variable2=1851&variable3=stringstuff", "algjalgjalgjal");
</code></pre>
<p>Then I put the new <code>$url</code> in a <code>href</code> or a tag or something (I use <code>$smarty</code> templates but that isn't relevant).</p>
<p>On the page someurl.com where I need to decrypt the params I just use:</p>
<pre><code>setGET($_GET['params'],"algjalgjalgjal");
</code></pre>
<p>This all works fine for me. Is there anything inherently terrible about this way of doing things? I'm asking this because I posted this as an answer on Stack Overflow to a question someone asked about hiding their <code>$_GET</code> parameters and it was immediately down-voted. That made me curious about whether it was somehow bad code or insecure in some way.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T02:25:21.847",
"Id": "32404",
"Score": "3",
"body": "$_POST over HTTPS is the correct approach security and functionality wise. Encrypting GET variables is just reinventing the wheel, and what happens if you forget to encrypt a param? (I'm assuming you're hiding data from snoopers, not the actual user of the website, correct?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T18:43:56.323",
"Id": "32446",
"Score": "0",
"body": "actually i'm hiding it from the users too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T02:16:07.840",
"Id": "32486",
"Score": "0",
"body": "Hiding it from the user tends to imply that you're either misusing GET or you're not fortifying your code enough. If you're using GET for passwords or something, *don't*; use POST instead. But if you're using it so that a user can't change `admin=0` to `admin=1` then there's a serious problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T16:48:56.917",
"Id": "32541",
"Score": "0",
"body": "mostly its so they can't change some_record_id=120 to something else because certain users only have access to the records assigned to them, its definitely not for admin things. and its not mission critical."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-22T21:37:45.663",
"Id": "218869",
"Score": "0",
"body": "Might I suggest [rethinking your strategy entirely](https://paragonie.com/blog/2015/09/comprehensive-guide-url-parameter-encryption-in-php)? I don't think encryption is the right tool for this job."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-22T22:21:27.323",
"Id": "218880",
"Score": "0",
"body": "@ScottArciszewski Its been 3 years since i posted this. Rest assured I have rethought it by now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-23T05:42:40.120",
"Id": "218933",
"Score": "0",
"body": "Excellent. Glad too hear that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-08-06T13:44:55.810",
"Id": "387230",
"Score": "0",
"body": "Hi all, I know it's been a long time and that this method is old and outdated for php7, but, someone else has updated this to now work: http://www.rndblog.com/php-encrypt-decrypt-a-request-param/"
}
] |
[
{
"body": "<p>Agree 100% with Corbin. GET isn't something that is inherently secure, and trying to make it so is nigh impossible. That's what POST is for. Only use GET for non-sensitive information. That being said, there are some generally concerning bits to your code that could cause some people to downvote it.</p>\n\n<p>Your line length is rather long and convoluted, which causes major issues with legibility. I would suggest breaking up that single line into multiple lines to more easily maintain and read. Adding whitespace couldn't hurt either. Additionally, using single letter variables is not very descriptive and also leads to issues with legibility. Its a bit longer, but much easier to read.</p>\n\n<pre><code>$translation = strtr( $stringArray, '-_,', '+/=' );\n\n$key = md5( $key );\n$data = base64_decode( $translation );\n$iv = md5( $key );\n$decrypt = mcrypt_decrypt(\n MCRYPT_RIJNDAEL_256,\n $key,\n $data,\n MCRYPT_MODE_CBC,\n $iv\n);\n\n$trimmed = rtrim( $decrypt, \"\\0\" );\n\nreturn unserialize( $trimmed );\n</code></pre>\n\n<p>A couple more potential issues with the above code are the methods you are implementing. I am by no means a security guru and have not put a lot of research into the matter, but I seem to remember from somewhere that mcrypt is frowned upon and that hashing a string with <code>md5()</code> twice is actually less secure than doing it just once. I don't know if this is true or not, but that could be a potential issue.</p>\n\n<p>Your code is also slightly repetitive, violating the \"Don't Repeat Yourself\" (DRY) Principle. As the name implies, your code should not repeat. Your encrypt and decrypt functions seem to share some common elements, using some shared helper functions to provide that similar data might be beneficial, even though you might just end up creating wrapper functions. I don't really see anyone downvoting you for this alone, this is rather minor in this instance and is rather hard to spot due to the above reasons.</p>\n\n<p>Another potential issue I see is with your braceless syntax. Braceless <code>{}</code> syntax can be somewhat confusing to those who have never seen it before, and therefore could cause issues with maintainability. This is entirely a point of preference, but one I would argue most vehemently against. It is especially bad to offer in the form of an answer when it is unknown how the questioner will use it. It is quite possible they attempted to modify the code and could not get it to work.</p>\n\n<p>The last issue I see is the way you are accessing array elements with magic numbers. This is rather sloppy and could cause issues with legibility, though I don't think you would get downvoted for it. There are a number of different ways this could be solved. The first is by using the PHP construct <code>list()</code>, which is probably preferable in this instance. The second is by using array functions to slice off the required portions of the array. This is more beneficial when you need the first and last elements of an array of undetermined length. Finally, there is also the possibility of using <code>extract()</code>, but that requires an associative array and is sometimes frowned upon. I won't show that last method because it doesn't apply here, but here are the other two:</p>\n\n<pre><code>//using list\nlist( $baseurl, $params ) = $url;\n\n//using array functions\n$baseurl = array_shift( $url );\n$params = array_shift( $url );//could potentially use array_pop()\n\nreturn $baseurl . '?params=' . encryptStringArray( $params, $key );\n</code></pre>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T18:51:34.187",
"Id": "32451",
"Score": "0",
"body": "fyi the reason i am using $_GET is because i'm using it for popup windows from a main page to do sub forms and its the easiest way. I like encrypting it so the users don't see the names of the id's i'm sending. it doesn't really need to be all that secure but a little obscurity doesn't hurt because i have had some users that like to fool around with the urls (in the past)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T18:54:30.133",
"Id": "32453",
"Score": "1",
"body": "I'd take a look at AJAX, it sounds like what you really need."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T18:58:24.977",
"Id": "32454",
"Score": "0",
"body": "yeah i have been using that lately. it all depends. i have heard it is also bad practice to use ajax with async false. but i end up doing that quite a bit too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T02:13:10.293",
"Id": "32484",
"Score": "1",
"body": "+1, but 2 nitpicks (both for the potential benefit of a future reader -- I suspect you're aware of both): `list()` should really only be used when you know for certain that the array is large enough. I suppose it could be a calling contract of his function though that a url must have a `?` in it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T02:14:06.720",
"Id": "32485",
"Score": "1",
"body": "Also, the statement about GET and POST is slightly misleading. The only security difference between get and post is that get shows up in URLs. Both are sent in clear text; both are easily altered, and both can be sniffed. The only difference is that URLs (and thus GET data) tend to be a lot more visible than POST data (history logs, company proxy logs, someone looking over your shoulder, etc). Anyway, `</pedant-mode>` :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-22T21:38:25.467",
"Id": "218870",
"Score": "0",
"body": "Hey @mseancole your decryption code isn't secure."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T16:55:09.160",
"Id": "20279",
"ParentId": "20257",
"Score": "6"
}
},
{
"body": "<p>So far I think you are doing a decent job of obfuscation, if that's what you want.</p>\n\n<p>If only your server is supposed to see the data, then it should stay on your server. Your server will have some index of data (session? database?) mechanism for identifying which data the client is working with, and only send the client the index to the data, not the data itself.</p>\n\n<p>BUT based on your comment about wanting to obfuscate the indices, maybe some more validation logic on your server would be the best solution. If you don't want the user to mess with the query string to do something, then come up with rules that the server can use to determine whether access is valid at that time and allow the user to create his own query strings if he wants to.</p>\n\n<p>You can't build a truly secure website until you can allow advanced users to access your server by any means they choose, including constructing raw HTTP requests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T16:52:52.907",
"Id": "32543",
"Score": "0",
"body": "its an intranet so it already has limited access, and you have to be logged in to view anything. raw http requests will only work if they are logged in with valid username password otherwise it will redirect to log in. there are some raw requests that we wouldn't want them to execute because they may not have the permissions to update that status or whatever the case may be. there is a heavy permissions based system on who can do what."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T18:26:28.287",
"Id": "32555",
"Score": "1",
"body": "If only certain users should have access to certain items, and your system gives access to these items, you need to be looking up permissions in your system when a user accesses items. So if they change the ID in the URL, you can look up if they have access to that ID, and if not, don't let them do that operation.\n\nIt might not seem like a big deal on your intranet, but then why do you have a policy about users access at all? Someone at your company cares about that policy and that it is followed.\n\nAnd what if one day you write an internet app?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T22:01:19.023",
"Id": "32595",
"Score": "0",
"body": "we do recheck their permissions. the obscured url is just a further step so they cannot even see the records let alone do anything with them."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-01-09T14:59:27.350",
"Id": "20325",
"ParentId": "20257",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20279",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-07T23:42:53.893",
"Id": "20257",
"Score": "5",
"Tags": [
"php",
"strings",
"cryptography",
"url"
],
"Title": "Hiding $_GET variables using encryption"
}
|
20257
|
<p>I wrote a simple script that converts a decimal to a mixed number, proper, or improper fraction depending on the inputed decimal.</p>
<p>It works but I think it could be improved as it hangs when large decimals are used. Please review and let me know how I could improve and simplify it. Thanks.</p>
<p>My script on JS Bin: <a href="http://jsbin.com/axulob/1/edit" rel="noreferrer">http://jsbin.com/axulob/1/edit</a></p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script>
window.onload = function() {
var factor;
// Finds the highest common factor of 2 numbers
function highestCommonFactor() {
for (factor = numerator; factor > 0; factor--) {
if ((numerator % factor == 0) && (denominator % factor == 0)) {
return factor;
}
}
}
// Enter a decimal to convert to a fraction
var decimal = "1.75";
// Split the decimal
var decimalArray = decimal.split(".");
var leftDecimalPart = decimalArray[0];
var rightDecimalPart = decimalArray[1];
// Save decimal part only for later use
var decimalOnly = "0." + rightDecimalPart;
// Find the decimal multiplier
var multiplier = "1";
for (var i = 0; i < rightDecimalPart.length; i++) {
multiplier += "0";
}
// Create numerator by multiplying the multiplier and decimal part together
var numerator = Number(multiplier) * Number(decimalOnly);
var denominator = multiplier;
// Find the highest common factor for the numerator and denominator
highestCommonFactor();
// Simplify the fraction by dividing the numerator and denominator by the factor
var numerator = Number(numerator) / Number(factor);
var denominator = Number(denominator) / Number(factor);
// Output as a mixed number fraction (depending on input)
var mixedNumber = leftDecimalPart + " " + numerator + "/" + denominator;
// Output as a proper fraction or improper fraction (depending on input)
var numerator = numerator + (leftDecimalPart * denominator);
var fraction = numerator + "/" + denominator;
// Display solution
document.getElementById("divSolution").innerText = fraction;
}
</script>
</head>
<body>
<div id="divSolution"></div>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-10T16:38:56.677",
"Id": "32647",
"Score": "0",
"body": "Why not use an existing fraction library instead? Here's one https://github.com/LarryBattle/Ratio.js"
}
] |
[
{
"body": "<ol>\n<li><p><code>highestCommonFactor</code> should take 2 integers as parameter instead of relying on the variable <code>numerator</code> and `denominator'. Also, you could find it using <a href=\"http://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid.27s_algorithm\" rel=\"nofollow\">Euclid'a algorithm</a>.</p></li>\n<li><p>I am wrong is saying that this piece of code :</p>\n\n<pre><code>var rightDecimalPart = decimalArray[1];\n// Save decimal part only for later use\nvar decimalOnly = \"0.\" + rightDecimalPart;\n// Find the decimal multiplier\nvar multiplier = \"1\";\nfor (var i = 0; i < rightDecimalPart.length; i++) {\n multiplier += \"0\";\n}\n// Create numerator by multiplying the multiplier and decimal part together\nvar numerator = Number(multiplier) * Number(decimalOnly);\n</code></pre></li>\n</ol>\n\n<p>is here to transform a number such as <code>78924</code> in <code>0.78924</code> and then check that have to multiply it by 100000 to get an integer which is ... <code>78924</code>. </p>\n\n<p><strong>Edit</strong>\nAfter a first cleanup, I get :</p>\n\n<pre><code>function highestCommonFactor(a,b) {\n if (b==0) return a;\n return highestCommonFactor(b,a%b);\n}\n\nvar decimal = \"1.75\";\nvar decimalArray = decimal.split(\".\");\nvar leftDecimalPart = decimalArray[0];\nvar rightDecimalPart = decimalArray[1];\n\nvar denominator = \"1\";\n\nfor (var i = 0; i < rightDecimalPart.length; i++) {\n denominator += \"0\";\n}\ndocument.getElementById(\"debug\").innerText = denominator;\nvar factor = highestCommonFactor(rightDecimalPart, denominator);\n\n// Simplify the fraction by dividing the numerator and denominator by the factor\nvar denominator = Number(denominator) / Number(factor);\nvar numerator = (Number(rightDecimalPart) / Number(factor)) + (leftDecimalPart * denominator);\n\n// Display solution as a proper fraction or improper fraction (depending on input)\ndocument.getElementById(\"divSolution\").innerText = numerator + \"/\" + denominator;\n</code></pre>\n\n<p>I'll try to go a step further.</p>\n\n<p><strong>Edit 2</strong>\nAfter a rewriting of the calculation, here's what I got :</p>\n\n<pre><code>function highestCommonFactor(a,b) {\n if (b==0) return a;\n return highestCommonFactor(b,a%b);\n}\n\nvar decimal = \"1.75\";\nvar decimalArray = decimal.split(\".\");\nvar leftDecimalPart = decimalArray[0]; // 1\nvar rightDecimalPart = decimalArray[1]; // 75\n\nvar numerator = leftDecimalPart + rightDecimalPart // 175\nvar denominator = Math.pow(10,rightDecimalPart.length); // 100\nvar factor = highestCommonFactor(numerator, denominator); // 25\ndenominator /= factor;\nnumerator /= factor;\n\ndocument.getElementById(\"divSolution\").innerText = numerator + \"/\" + denominator;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T21:31:53.393",
"Id": "32467",
"Score": "0",
"body": "Thanks for taking the time to go through my code. Could you explain how the function highestCommonFactor works?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T22:39:09.377",
"Id": "32474",
"Score": "0",
"body": "I understand Euclid'a algorithm but I don't get how it's returning 2 values (return highestCommonFactor(b,a%b))? I assume it's multiplying (b) * ((a%b))."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T00:23:56.810",
"Id": "32479",
"Score": "0",
"body": "The method highestCommonFactor takes 2 (integer) arguments and return 1 (integer) value. I used the formula from http://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid.27s_algorithm to write this recursive function."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T01:21:19.260",
"Id": "20261",
"ParentId": "20258",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20261",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T00:36:45.253",
"Id": "20258",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "Converting Decimals to Fractions with JavaScript - Simplify & Improve"
}
|
20258
|
<p>I've put in quite a bit of hours on this BlackJack project for Codecademy to get it to the point where I'm satisfied with it. Before I move on to create the UI for it I would really appreciate feedback on things to improve, such as my use of classes and objects, best practices, etc. I'm including a link to my jsFiddle.</p>
<p><a href="http://jsfiddle.net/mrStevens/syB7P/15/" rel="nofollow">BlackJack project</a></p>
<pre><code>"use strict";
// Hands for players, multiple hands used for splitting cards
function Hand() {
var cards = [],
// Set to true if totalScore > 21
isBust = false,
// Total of all cards at a point in time, aces are handled in calcTotalScore
totalScore = 0;
// Sets totalScore and isBust
this.calcTotalScore = function () {
var hasAce = false,
tempCardValue;
if (cards.length === 0) {
console.log("ERROR: No cards in this Hand");
} else {
// Reset totalScore before every calculation
totalScore = 0;
for (var i = 0; i < cards.length; i++) {
tempCardValue = cards[i].getCardValue();
if (tempCardValue === 11) { hasAce = true }
totalScore += tempCardValue;
}
if ((totalScore > 21) && hasAce) {
totalScore -= 10;
}
if (totalScore > 21) {
isBust = true;
}
}
}
this.popLastCard = function () {
var tempPoppedCard = cards.pop();
this.calcTotalScore();
return tempPoppedCard;
};
this.pushNewCard = function (card) {
cards.push(card);
this.calcTotalScore();
};
this.getScore = function () {
return totalScore;
};
this.getCard = function (cardPos) {
return cards[cardPos].getCardNumber() + " of " + cards[cardPos].getCardSuit();
};
this.getCardNumber = function (cardPos) {
return cards[cardPos].getCardNumber();
}
this.getCardsLength = function () {
return cards.length;
}
this.getIsBust = function () {
return isBust;
}
}
// Cards exist in Hands or Decks
function Card(inSuit, inNum) {
this.getCardSuit = function () {
var suitName = "";
switch (inSuit) {
case 1:
suitName = "Hearts";
break;
case 2:
suitName = "Clubs";
break;
case 3:
suitName = "Diamonds";
break;
case 4:
suitName = "Spades";
break;
default:
suitName = "ERROR";
}
return suitName;
};
this.getCardNumber = function () {
var numName = "";
if (inNum === 1) {
numName = "Ace";
} else if (inNum > 10) {
switch (inNum) {
case 11:
numName = "Jack";
break;
case 12:
numName = "Queen";
break;
case 13:
numName = "King";
break;
default:
numName = "ERROR";
}
} else {
numName = inNum;
}
return numName;
};
this.getCardValue = function () {
var value = inNum > 9 ? 10 : inNum === 1 ? 11 : inNum;
return value;
};
}
// Decks used for shuffling and dealing cards to Hands
function Deck() {
var deckOfCards = [];
this.shuffle = function () {
var tempCard,
randomDeckIndex,
tempCardSuit = 1,
tempCardNumber = 1;
deckOfCards.length = 0;
// Populate deck with 52 cards in order
for (var i = 0; i < 52; i++) {
deckOfCards[i] = new Card(tempCardSuit, tempCardNumber);
if (tempCardNumber < 13) {
tempCardNumber++;
} else {
tempCardNumber = 1;
tempCardSuit++;
}
}
// Randomize the 52 cards
for (var i = (deckOfCards.length - 1); i > 0; i--) {
if (i === 0) {
randomDeckIndex = Math.floor(Math.random() * deckOfCards.length);
} else {
randomDeckIndex = Math.floor(Math.random() * i);
}
tempCard = deckOfCards[randomDeckIndex];
deckOfCards[randomDeckIndex] = deckOfCards[i];
deckOfCards[i] = tempCard;
}
};
// Returns last card in the Deck
this.popLastCard = function () {
return deckOfCards.pop();
};
}
// Players have Hands
function Player() {
var hands = [new Hand()];
this.initializePlayer= function () {
hands.length = 0;
this.addNewHand();
}
this.addNewHand = function () {
hands.push(new Hand());
};
this.getScore = function (handIndex) {
return hands[handIndex].getScore();
};
this.getCard = function (handIndex, cardIndex) {
return hands[handIndex].getCard(cardIndex);
};
this.pushNewCard = function (handIndex, card) {
hands[handIndex].pushNewCard(card);
};
this.popLastCard = function (handIndex) {
return hands[handIndex].popLastCard();
}
this.getCardNumber = function (handIndex, cardIndex) {
return hands[handIndex].getCardNumber(cardIndex);
}
this.splitHand = function (handIndex) {
this.addNewHand();
hands[handIndex + 1].pushNewCard(hands[handIndex].popLastCard());
}
this.getHandsLength = function () {
return hands.length;
}
this.getCardsLength = function (handIndex) {
return hands[handIndex].getCardsLength();
}
this.getIsBust = function (handIndex) {
return hands[handIndex].getIsBust();
}
this.getIsStand = function (handIndex) {
return hands[handIndex].isStand;
}
this.setIsStand = function (handIndex) {
hands[handIndex].isStand = true;
}
// Returns true if there are Hands left to play
this.hasGoodHand = function () {
var goodHand = false;
for (var i = 0; i < hands.length; i++) {
if (!this.getIsBust(i)) {
goodHand = true;
}
}
return goodHand;
}
}
function main() {
var playCurrentHand,
playerSplits = false,
deck1 = new Deck(),
currentHandIndex = 0,
play = true;
//Create initial hands and deal first 2 cards
var player1 = new Player(),
dealer = new Player();
while (play) {
deck1.shuffle();
player1.pushNewCard(currentHandIndex, deck1.popLastCard());
dealer.pushNewCard(0, deck1.popLastCard());
player1.pushNewCard(currentHandIndex, deck1.popLastCard());
dealer.pushNewCard(0, deck1.popLastCard());
//Print initial deal to player
console.log("You were dealt a " + player1.getCard(currentHandIndex, 0) + " and a "
+ player1.getCard(currentHandIndex, 1));
console.log("Dealer shows " + dealer.getCard(0, 0));
//Play player's hand
while (currentHandIndex < player1.getHandsLength()) {
//Check for splits
if (player1.getCardNumber(currentHandIndex, 0) === player1.getCardNumber(currentHandIndex, 1)) {
if (confirm("You were dealt two " + player1.getCardNumber(currentHandIndex, 0) + "'s. Do you want to split them?")) {
player1.splitHand(currentHandIndex);
//Deal 1 card to each hand
player1.pushNewCard(currentHandIndex, deck1.popLastCard());
player1.pushNewCard(currentHandIndex + 1, deck1.popLastCard());
}
}
playCurrentHand = true;
while (playCurrentHand && !player1.getIsBust(currentHandIndex)) {
if ((currentHandIndex > 0) || (player1.getHandsLength() > 1)) {
console.log("Your current hand is a " + player1.getScore(currentHandIndex));
}
// Player automatically stands on a 21
if ((player1.getScore(currentHandIndex) < 21) && confirm("Would you like another card?")) {
player1.pushNewCard(currentHandIndex, deck1.popLastCard());
console.log("You draw a " + player1.getCard(currentHandIndex, (player1.getCardsLength(currentHandIndex) - 1))
+ " your new score is " + player1.getScore(currentHandIndex));
if (player1.getIsBust(currentHandIndex)) {
console.log("You bust on this hand");
}
} else {
console.log("You stand on hand " + (currentHandIndex + 1) + " with a " + player1.getScore(currentHandIndex));
playCurrentHand = false;
}
}
currentHandIndex++;
}
if (!player1.hasGoodHand()) {
play = confirm("Do you want to play again?");
} else {
// Play dealer's hand
console.log("The dealer was dealt a " + dealer.getScore(0));
while (dealer.getScore(0) < 17 && !dealer.getIsBust(0)) {
dealer.pushNewCard(0, deck1.popLastCard());
console.log("The dealer draws a " + dealer.getCard(0, (dealer.getCardsLength(0) - 1)) + ". New score is "
+ dealer.getScore(0));
}
// Show results of dealer's hand
if (dealer.getIsBust(0)) {
console.log("Dealer busts!");
} else {
console.log("Dealer stands with a " + dealer.getScore(0));
}
// Display results
for (var i = 0; i < player1.getHandsLength(); i++) {
if (!player1.getIsBust(i)) {
if (dealer.getScore(0) === player1.getScore(i)) {
console.log("You push on hand " + (i + 1));
} else if ((dealer.getScore(0) > player1.getScore(i)) && !dealer.getIsBust(0)) {
console.log("Dealer wins hand " + (i + 1));
} else {
console.log("You win hand " + (i + 1));
}
}
}
play = confirm("Do you want to play again?");
}
if (play) {
player1.initializePlayer();
dealer.initializePlayer();
currentHandIndex = 0;
}
}
}
//main();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T01:00:22.803",
"Id": "32399",
"Score": "1",
"body": "As stated in the FAQ, please include the code you would like reviewed in the question. http://codereview.stackexchange.com/faq#make-sure-you-include-your-code-in-your-question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T02:10:57.120",
"Id": "32403",
"Score": "0",
"body": "Let's put it this way: If jsFiddle goes down, that like won't be relevant and your code won't get reviewed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T03:16:54.487",
"Id": "32405",
"Score": "0",
"body": "Sure thing. Added."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T08:07:00.423",
"Id": "32407",
"Score": "0",
"body": "Hint:If you have that many conditional statements (`if`, `case` or `? :`) in your **Domain Object**s e.g. `Card` you are not doing OOP right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T09:15:05.340",
"Id": "32409",
"Score": "0",
"body": "@abuzittingillifirca Thanks for the feedback. Can you give me an example by refactoring one of the if statements?"
}
] |
[
{
"body": "<blockquote>\n <p>Can you give me an example by refactoring one of the if statements? </p>\n</blockquote>\n\n<p>Your <code>Card</code> object can be changed as follows:</p>\n\n<p>Following your general style,</p>\n\n<pre><code>function Suit(name, sym) {\n this.getName = function () {\n return name;\n }\n\n this.getSymbol = function () {\n return sym;\n }\n}\n\nvar hearts = new Suit(\"Hearts\", \"\\u2665\");\nvar clubs = new Suit(\"Clubs\", \"\\u2663\");\nvar diamonds = new Suit(\"Diamonds\", \"\\u2666\");\nvar spades = new Suit(\"Spades\", \"\\u2660\"); \nvar suits = [hearts, clubs, diamonds, spades];\n\nfunction Rank(name, value) {\n this.getName = function() {\n return name;\n }\n\n this.getValue = function() {\n return value\n }\n}\n\nvar ranks = [\n new Rank(\"Ace\", 11), \n new Rank(\"2\", 2), \n new Rank(\"3\", 3), \n new Rank(\"4\", 4), \n new Rank(\"5\", 5), \n new Rank(\"6\", 6),\n new Rank(\"7\", 7),\n new Rank(\"8\", 8),\n new Rank(\"9\", 9),\n new Rank(\"10\", 10),\n new Rank(\"Jack\", 10),\n new Rank(\"King\", 10),\n new Rank(\"Queen\", 10)\n];\n\n// Cards exist in Hands or Decks\nfunction Card(suit, rank) {\n this.getCardSuit = function () {\n return suit.getName();\n };\n\n this.getCardNumber = function () {\n return rank.getName();\n };\n\n this.getCardValue = function () {\n return rank.getValue();\n };\n\n}\n</code></pre>\n\n<p>And your deck creation accordingly changed from:</p>\n\n<pre><code>// Populate deck with 52 cards in order\nfor (var i = 0; i < 52; i++) {\n deckOfCards[i] = new Card(tempCardSuit, tempCardNumber);\n\n if (tempCardNumber < 13) {\n tempCardNumber++;\n } else {\n tempCardNumber = 1;\n tempCardSuit++;\n }\n}\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>for (var suitIdx = 0; suitIdx < suits.length; suitIdx ++) {\n for (var rankIdx = 0; rankIdx < ranks.length; rankIdx ++) {\n deckOfCards.push(new Card(suits[suitIdx], ranks[rankIdx]));\n }\n}\n</code></pre>\n\n<p>Suit and Rank are <strong>Value Objects</strong> from your domain. In which you can put more behavior. Now you can change relatively more easily from suit names to suit symbols for example. </p>\n\n<p>As a rule of thumb if a property does not change during the life time of an object, do not calculate it in the object, you may pass it to the constructor. </p>\n\n<p>Another OOP tip: If you are calling a number of methods of an object in a row, those code should probably go into that object.</p>\n\n<pre><code>this.getCard = function (cardPos) {\n return cards[cardPos].getCardNumber() + \" of \" + cards[cardPos].getCardSuit();\n};\n</code></pre>\n\n<p>the portion:</p>\n\n<pre><code>card.getCardNumber() + \" of \" + card.getCardSuit();\n</code></pre>\n\n<p>can go into <code>card.toString()</code></p>\n\n<p>Another one: Methods should be short and do one specific thing which should be indicated by their names.\nYour <code>Deck.shuffle()</code> methods is doing multiple things at once. It both populates the deck, but it also shuffles it afterwards. Populating the deck should move out of <code>shuffle</code> method.</p>\n\n<p>The same is true for you <code>main()</code> method. 2 players and a deck are asking to be moved into a class <code>BlackJackGame</code> or some other name.</p>\n\n<p>DRY: Don't repeat yourself. \nRepeating instances of <code>dealer.pushNewCard(0, deck1.popLastCard())</code> should move in to a function. Also note that that function can be a method of an object that contains both <code>deck</code> and <code>player</code>. Also note that method names containing implementation details like <code>push</code> or <code>pop</code> and the magic constant <code>0</code> are clues that that behavior needs to be encapsulated.</p>\n\n<p>Comments such as this:</p>\n\n<pre><code> // Display results\n</code></pre>\n\n<p>followed by a <strong>chunk of code</strong> should better be factored out into a method of its own, usually getting their names from the comment itself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T12:00:48.890",
"Id": "32416",
"Score": "1",
"body": "Marting Fowler's Refactoring book site\nhttp://refactoring.com/\nhas a large catalog of refactorings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T18:04:14.203",
"Id": "32443",
"Score": "0",
"body": "Thank you for that detailed response and for the link of refactoring suggestions. It gives me stuff to chew on."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T10:26:59.303",
"Id": "20267",
"ParentId": "20259",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "20267",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T00:38:44.963",
"Id": "20259",
"Score": "5",
"Tags": [
"javascript",
"game",
"playing-cards"
],
"Title": "Codecademy BlackJack project"
}
|
20259
|
<p>I've developed mini utility, the source code can get reviewed here:</p>
<p><a href="http://rle.codeplex.com/SourceControl/BrowseLatest" rel="nofollow">http://rle.codeplex.com/SourceControl/BrowseLatest</a></p>
<p>It's developed in C#, in the general page there is a description.
I'm listening to well criticism to make code more elegant and better to work with.</p>
<pre><code> /*
* GNU General Public License version 2 (GPLv2) http://rle.codeplex.com/license
* Oleg Orlov, 2013 (c), RLE encoding/decoding tool, version 1.0.1 (v1.01)
*
* C#, .NET 2.0 by default. It could be upgraded to any version of the .NET framework.
* I have downgraded the .NET version only for the compatibility aims
* and for the easy reproduction of the program to any other language.
*
* http://rle.codeplex.com/
*/
using System;
abstract class Contracts
{
public enum EncodingFormat
{
Old,
New,
};
}
class RLE : Contracts, IDisposable
{
private string str_base, str_rle;
private bool HasChar(ref string input)
{
bool status = false;
for (int i = 0; i < input.Length; i++)
{
if (Char.IsLetter(input[i]))
{
status = true;
break;
}
}
return status;
}
internal string Encode(ref string input, EncodingFormat format)
{
str_rle = null;
str_base = input;
if (format == EncodingFormat.New)
{
for (int i = 0; i < str_base.Length; i++)
{
char symbol = str_base[i];
int count = 1;
for (int j = i; j < str_base.Length - 1; j++)
{
if (str_base[j + 1] != symbol) break;
count++;
i++;
}
if (count == 1) str_rle += symbol;
else str_rle += count.ToString() + symbol;
}
}
else if (format == EncodingFormat.Old)
{
for (int i = 0; i < str_base.Length; i++)
{
char symbol = str_base[i];
int count = 1;
for (int j = i; j < str_base.Length - 1; j++)
{
if (str_base[j + 1] != symbol) break;
count++;
i++;
}
str_rle += count.ToString() + symbol;
}
}
return str_rle;
}
internal string Decode(ref string input)
{
str_rle = null;
str_base = input;
int radix = 0;
for (int i = 0; i < str_base.Length; i++)
{
if (Char.IsNumber(str_base[i]))
{
radix++;
}
else
{
if (radix > 0)
{
int value_repeat = Convert.ToInt32(str_base.Substring(i - radix, radix));
for (int j = 0; j < value_repeat; j++)
{
str_rle += str_base[i];
}
radix = 0;
}
else if (radix == 0)
{
str_rle += str_base[i];
}
}
}
if (str_rle == null || !HasChar(ref str_rle)) throw new Exception("\r\nCan't to decode! Input string has the wrong syntax. There isn't any char (e.g. 'a'->'z') in your input string, there was/were only number(s).\r\n");
return str_rle;
}
internal double GetPercentage(double x, double y)
{
return (100 * (x - y)) / x;
}
public void Dispose()
{
if (str_rle != null || str_base != null)
{
str_rle = str_base = null;
}
}
}
class Program : Contracts
{
private static string str_welcome = "\r\nRLE encoding/decoding tool, Oleg Orlov 2013(c).",
str_notice = "\r\nPlease, use the next syntax: <action> <string>\r\n(e.g. \"encode my_string\" or \"decode my_string\").\r\n\r\nWarning! The 2nd parameter (the string for encoding/decoding)\r\nmust not content any whitespaces!\r\n\r\nYou may also use the option \"-old\" to encode your string\r\n(e.g. \"encode my_string -old\") in such way, where before\r\nsingle char inserting the value: '1' (e.g. \"abbcddd\" -> \"1a2b1c3d\").";
private static void EncodeString(ref string str, EncodingFormat format)
{
using (RLE inst_rle = new RLE())
{
string str_encoded = inst_rle.Encode(ref str, format);
if (format == EncodingFormat.New)
{
Console.WriteLine("\r\nBase string ({0} chars): {1}\r\nAfter RLE-encoding ({2} chars): {3}\r\nCompression percentage: %{4}",
str.Length, str, str_encoded.Length, str_encoded,
inst_rle.GetPercentage((double)str.Length, (double)str_encoded.Length).ToString());
}
else if (format == EncodingFormat.Old)
{
Console.WriteLine("\r\nBase string ({0} chars): {1}\r\nAfter RLE-encoding with the \"-old\" option ({2} chars): {3}\r\nCompression percentage: %{4}",
str.Length, str, str_encoded.Length, str_encoded,
inst_rle.GetPercentage((double)str.Length, (double)str_encoded.Length).ToString());
}
}
}
private static void DecodeString(ref string str)
{
using (RLE inst_rle = new RLE())
{
string str_decoded = inst_rle.Decode(ref str);
Console.WriteLine("\r\nBase string ({0} chars): {1}\r\nAfter RLE-decoding ({2} chars): {3}\r\nDecompression percentage: %{4}",
str.Length, str, str_decoded.Length, str_decoded,
Math.Abs(inst_rle.GetPercentage((double)str.Length, (double)str_decoded.Length)).ToString());
}
}
[STAThread]
public static void Main(string[] args)
{
try
{
Console.WriteLine(str_welcome);
if (args.Length > 1)
{
if (args[0] == "encode")
{
if (args.Length == 3)
{
if (args[2] == "-old")
{
EncodeString(ref args[1], EncodingFormat.Old);
}
}
else
{
EncodeString(ref args[1], EncodingFormat.New);
}
}
else if (args[0] == "decode")
{
DecodeString(ref args[1]);
}
else
{
throw (new Exception("\r\nThere are only two methods: encode (with the \"-old\" option), decode. No other actions are available.\r\n"
+ str_notice + "\r\n"));
}
}
else
{
Console.WriteLine(str_notice);
Environment.Exit(1);
}
}
catch (Exception exc)
{
Console.WriteLine("\r\n{0}", exc);
Environment.Exit(1);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T01:32:53.617",
"Id": "32401",
"Score": "0",
"body": "If you want us to review your code, you need to post it here directly, not just link to it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T02:07:24.623",
"Id": "32402",
"Score": "0",
"body": "@svick have done!"
}
] |
[
{
"body": "<p><strong>MPEG?</strong></p>\n\n<p>I'm a little unclear where RLE comes into the MPEG codec, but if it does I would assume its based on binary encoding, not text based? In the same way as RLE formats for BMP's?</p>\n\n<p><strong>Streaming</strong></p>\n\n<p>Anything that processes information like this should attempt to keep its memory profile to a minimum. If this is to be used for MPEG data then the input data could be huge. \nAs the algorthum is forward only (ie you don't need to ammend information you have already written), you can make it stream based.\nThe class would operate on a source stream (or TextReader) and write the encoded data to an output stream (or TextWriter). This way virtually no state information needs to be held and the memory footprint is virtually nill regardless of the size of the data being encoded.\nIn any case there is no need to store the encoded/raw data.</p>\n\n<p><strong>Points about the code.</strong></p>\n\n<p>You don't need to pass by reference unless your going to change the string (ref string input). I'm guessing you were a C++ programmer?</p>\n\n<p>Building string using </p>\n\n<pre><code>str += \"stuff\";\n</code></pre>\n\n<p>is very slow. It causes a re-allocation and copy. Use StringBuilder.</p>\n\n<p>Throwing Exception is bad, you should use an existing .Net Exception or derive your own. It means code has to have catch(Exception) which causes ThreadAbortException to be caught (which is not typically what you want to happen). There is a fair bit of material out there about Exception throwing.</p>\n\n<p>GetPercentage is a helper function, its nothing to do with the encoder, so it should not live in the encoder class.</p>\n\n<p>Dispose is for freeing up unmanaged resources, if you insist on storing the raw/encoded data then you may want a method to cleanup method for discarding the data, but dispose has no practical use here. Read up on garbage collection (If you do have a C++ background then a bit of background will prevent you writting lots of unessessary code).</p>\n\n<p>Hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T20:21:42.373",
"Id": "32459",
"Score": "0",
"body": "About RLE in MPEG-2, look here: [link](https://www.cs.sfu.ca/CourseCentral/365/mark/material/notes/Chap4/Chap4.3/Topic5.fig_137.gif)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T20:24:15.567",
"Id": "32460",
"Score": "0",
"body": "I want to use `Dispose` for use `using {}` it requires to implement IDisposable"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-05T07:51:12.703",
"Id": "34211",
"Score": "0",
"body": "Still pretty sure the rle implementation will be a binary one, not text based, but I've not read the spec. \nYou only need to dispose for unmanaged resources, so in this case its not required, and therefore neither is the use of a using block."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T15:34:06.690",
"Id": "20275",
"ParentId": "20260",
"Score": "2"
}
},
{
"body": "<p>First of all. Follow the <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/ms229002%28v=vs.100%29.aspx\" rel=\"nofollow\">guidelines for .NET</a>. Your naming convention is off. Same goes for the indention (also discussed in the same web page, but a different section).</p>\n\n<hr>\n\n<pre><code>private bool HasChar(ref string input)\n{\n bool status = false;\n\n for (int i = 0; i < input.Length; i++)\n {\n if (Char.IsLetter(input[i]))\n {\n status = true;\n break;\n }\n }\n\n return status;\n}\n</code></pre>\n\n<p>that method can be replaced with <code>input.Any(x => char.IsLetter(x))</code>. If you want to stick with a method, why don't you just use <code>return true;</code> inside the loop? Makes the code a lot cleaner.</p>\n\n<hr>\n\n<p>.NET takes care of all memory management for you. The GC is quite aggressive. Implementing <code>IDisposable</code> just to set things to <code>null</code> does virtually nothing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T15:46:21.360",
"Id": "20276",
"ParentId": "20260",
"Score": "2"
}
},
{
"body": "<p>This looks like some sort of direct port from C. It totally ignores C# convention, standards and the .NET library that you have at your disposal. There also seems to be a bit of a misunderstanding of how inheritance works (or, in this case, isn't needed), the Disposable pattern, when instance variables versus locals should be used, use of the <code>ref</code> keyword and immutable string concatenation vs. <code>StringBuilder</code>. So, look those up in the appropriate places, learn them thoroughly and compare with this version (note, internal logic for creating the RLE itself is pretty solid, so I left it alone):</p>\n\n<pre><code> /*\n * GNU General Public License version 2 (GPLv2) http://rle.codeplex.com/license\n * Oleg Orlov, 2013 (c), RLE encoding/decoding tool, version 1.0.1 (v1.01)\n * \n * C#, .NET 2.0 by default. It could be upgraded to any version of the .NET framework.\n * I have downgraded the .NET version only for the compatibility aims\n * and for the easy reproduction of the program to any other language.\n * \n * http://rle.codeplex.com/\n */\n\nusing System;\nusing System.Globalization;\nusing System.Text;\n\npublic enum EncodingFormat\n{\n Old,\n\n New,\n}\n\npublic static class Rle\n{\n private static bool HasChar(StringBuilder input)\n {\n for (var i = 0; i < input.Length; i++)\n {\n if (char.IsLetter(input[i]))\n {\n return true;\n }\n }\n\n return false;\n }\n\n internal static string Encode(string input, EncodingFormat format)\n {\n var runLengthEncodedString = new StringBuilder();\n var baseString = input;\n\n switch (format)\n {\n case EncodingFormat.New:\n for (var i = 0; i < baseString.Length; i++)\n {\n var symbol = baseString[i];\n var count = 1;\n\n for (var j = i; j < baseString.Length - 1; j++)\n {\n if (baseString[j + 1] != symbol)\n {\n break;\n }\n\n count++;\n i++;\n }\n\n if (count == 1)\n {\n runLengthEncodedString.Append(symbol);\n }\n else\n {\n runLengthEncodedString.Append(count.ToString(CultureInfo.InvariantCulture) + symbol);\n }\n }\n\n break;\n case EncodingFormat.Old:\n for (var i = 0; i < baseString.Length; i++)\n {\n var symbol = baseString[i];\n var count = 1;\n\n for (var j = i; j < baseString.Length - 1; j++)\n {\n if (baseString[j + 1] != symbol)\n {\n break;\n }\n\n count++;\n i++;\n }\n\n runLengthEncodedString.Append(count.ToString(CultureInfo.InvariantCulture) + symbol);\n }\n\n break;\n }\n\n return runLengthEncodedString.ToString();\n }\n\n internal static string Decode(string input)\n {\n var runLengthEncodedString = new StringBuilder();\n var baseString = input;\n\n var radix = 0;\n\n for (var i = 0; i < baseString.Length; i++)\n {\n if (char.IsNumber(baseString[i]))\n {\n radix++;\n }\n else\n {\n if (radix > 0)\n {\n var valueRepeat = Convert.ToInt32(baseString.Substring(i - radix, radix));\n\n for (var j = 0; j < valueRepeat; j++)\n {\n runLengthEncodedString.Append(baseString[i]);\n }\n\n radix = 0;\n }\n else if (radix == 0)\n {\n runLengthEncodedString.Append(baseString[i]);\n }\n }\n }\n\n if (!HasChar(runLengthEncodedString))\n {\n throw new Exception(\"\\r\\nCan't to decode! Input string has the wrong syntax. There isn't any char (e.g. 'a'->'z') in your input string, there was/were only number(s).\\r\\n\");\n }\n\n return runLengthEncodedString.ToString();\n }\n\n internal static double GetPercentage(double x, double y)\n {\n return (100 * (x - y)) / x;\n }\n}\n\ninternal static class Program\n{\n private const string Welcome = \"\\r\\nRLE encoding/decoding tool, Oleg Orlov 2013(c).\";\n\n private const string Notice = \"\\r\\nPlease, use the next syntax: <action> <string>\\r\\n(e.g. \\\"encode my_string\\\" or \\\"decode my_string\\\").\\r\\n\\r\\nWarning! The 2nd parameter (the string for encoding/decoding)\\r\\nmust not content any whitespaces!\\r\\n\\r\\nYou may also use the option \\\"-old\\\" to encode your string\\r\\n(e.g. \\\"encode my_string -old\\\") in such way, where before\\r\\nsingle char inserting the value: '1' (e.g. \\\"abbcddd\\\" -> \\\"1a2b1c3d\\\").\";\n\n private static void EncodeString(string unencodedString, EncodingFormat format)\n {\n var encodedString = Rle.Encode(unencodedString, format);\n\n switch (format)\n {\n case EncodingFormat.New:\n Console.WriteLine(\n \"\\r\\nBase string ({0} chars): {1}\\r\\nAfter RLE-encoding ({2} chars): {3}\\r\\nCompression percentage: %{4}\",\n unencodedString.Length,\n unencodedString,\n encodedString.Length,\n encodedString,\n Rle.GetPercentage(unencodedString.Length, encodedString.Length));\n break;\n case EncodingFormat.Old:\n Console.WriteLine(\n \"\\r\\nBase string ({0} chars): {1}\\r\\nAfter RLE-encoding with the \\\"-old\\\" option ({2} chars): {3}\\r\\nCompression percentage: %{4}\",\n unencodedString.Length,\n unencodedString,\n encodedString.Length,\n encodedString,\n Rle.GetPercentage(unencodedString.Length, encodedString.Length));\n break;\n }\n }\n\n private static void DecodeString(string encodedString)\n {\n var decodedString = Rle.Decode(encodedString);\n\n Console.WriteLine(\n \"\\r\\nBase string ({0} chars): {1}\\r\\nAfter RLE-decoding ({2} chars): {3}\\r\\nDecompression percentage: %{4}\",\n encodedString.Length,\n encodedString,\n decodedString.Length,\n decodedString,\n Math.Abs(Rle.GetPercentage(encodedString.Length, decodedString.Length)));\n }\n\n [STAThread]\n public static int Main(string[] args)\n {\n try\n {\n Console.WriteLine(Welcome);\n\n if (args.Length > 1)\n {\n switch (args[0])\n {\n case \"encode\":\n if (args.Length == 3)\n {\n if (args[2] == \"-old\")\n {\n EncodeString(args[1], EncodingFormat.Old);\n }\n }\n else\n {\n EncodeString(args[1], EncodingFormat.New);\n }\n\n break;\n case \"decode\":\n DecodeString(args[1]);\n break;\n default:\n throw new Exception(\"\\r\\nThere are only two methods: encode (with the \\\"-old\\\" option), decode. No other actions are available.\\r\\n\"\n + Notice + \"\\r\\n\");\n }\n\n return 0;\n }\n\n Console.WriteLine(Notice);\n return 1;\n }\n catch (Exception exc)\n {\n Console.WriteLine(\"\\r\\n{0}\", exc);\n return 1;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T20:42:57.177",
"Id": "32461",
"Score": "0",
"body": "Thank you for the such good answer. But I have Q about your code. Why is `var` needed? As I remember `var` makes some more actions for runtime type identification? So maybe to explicitly use the exact type and not using `var`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T20:45:33.600",
"Id": "32462",
"Score": "0",
"body": "`var` is not needed at all in this instance. It's a matter of preference. It has nothing to do with RTTI. The compiler resolves its type at compile-time."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T15:53:42.533",
"Id": "20277",
"ParentId": "20260",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T00:54:07.400",
"Id": "20260",
"Score": "2",
"Tags": [
"c#",
".net"
],
"Title": "RLE encoding/decoding tool, review source"
}
|
20260
|
<p>I am trying to wrap my head around how to properly use OOP in PHP when dealing with form submissions.</p>
<p>The example below is a form for editing course information. I have a class called Course which has methods for loading the class with information from the database and saving information into the database.</p>
<p>Everything works but I feel like I am doing this all wrong - any critique/suggestion would be nice.</p>
<p><strong>edit_course.php</strong></p>
<pre><code><?php
require_once 'header_includes.php';
$course = new Course();
$errors = array();
// get course ID
$cid = filter_input(INPUT_GET, 'cid', FILTER_VALIDATE_INT);
// check course ID
if ($cid && $course->load_data($cid)) {
$filter = array(
'code' => FILTER_SANITIZE_STRING,
'name' => FILTER_SANITIZE_STRING,
'hid-submit' => FILTER_VALIDATE_BOOLEAN
);
$inputs = filter_input_array(INPUT_POST, $filter);
// check if form submitted
if (!empty($inputs['hid-submit'])) {
// show error messages if any
$course->code = $inputs['code'];
if (empty($inputs['code'])) {
$errors['code'] = 'This is not a valid code.';
}
$course->name = $inputs['name'];
if (empty($inputs['name'])) {
$errors['name'] = 'This is not a valid name.';
}
$course->description = $inputs['description'];
// save course information
if (!count($errors)) {
$saved = $course->save_data();
}
}
}
require_once 'header.php'; // header template
?>
<?php if ($course->error !== false) { ?>
<div id="error"><?php echo $course->error ?></div>
<?php } ?>
<form name="form1" action="" method="post">
<div>
<label>Code:</label>
<input type="text" name="code" value="<?php echo $course->code ?>" maxlength="10" size="8" />
<?php if (array_key_exists('code', $errors)) { ?>
<div class="error"><?php echo $errors['code'] ?></div>
<?php } ?>
</div>
<div>
<label>Name:</label>
<input type="text" name="name" value="<?php echo $course->name ?>" maxlength="45" size="25" />
<?php if (array_key_exists('name', $errors)) { ?>
<div class="error"><?php echo $errors['name'] ?></div>
<?php } ?>
</div>
<div>
<input type="submit" value="Save" />
<input type="hidden" name="hid-submit" value="1" />
</div>
</form>
<?php
require_once 'footer.php'; // footer template
?>
</code></pre>
<p><strong>Course.class.php</strong></p>
<pre><code><?php
if(!class_exists('Course')) {
class Course {
private $id = NULL;
private $code = '';
private $name = '';
private $error = FALSE;
public function __get($property) {
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
return $this;
}
/**
* Load course data from database
*
* @param int
* @return bool
*/
public function load_data($id) {
// SQL statement
$sql = 'SELECT id, code, name FROM courses WHERE id = :id';
try {
$core = Core::getInstance();
//
$sth = $core->dbh->prepare($sql);
$sth->bindParam(':id', $id, PDO::PARAM_INT);
if ($sth->execute()) {
// if course is found
if ($row = $sth->fetch(PDO::FETCH_OBJ)) {
$this->id = intval($row->id);
$this->code = $row->code;
$this->name = $row->name;
return TRUE;
}
} else {
throw new Exception('A problem has occurred while retrieving information from database.');
}
$sth->closeCursor();
} catch (Exception $e) {
$this->error = $e->getMessage();
}
return FALSE;
}
/**
* Save course information
*
* @return bool
*/
public function save_data() {
// SQL statements
if ($this->id) {
$sql = 'UPDATE courses
SET code = :code, name = :name
WHERE id = :id';
} else {
$sql = 'INSERT INTO courses(id, code, name)
VALUES(:id, :code, :name)';
}
try {
$core = Core::getInstance();
// update/insert into database
$sth = $this->core->dbh->prepare($sql);
$sth->bindParam(':id', $this->id, PDO::PARAM_INT);
$sth->bindParam(':code', $this->code, PDO::PARAM_STR);
$sth->bindParam(':name', $this->title, PDO::PARAM_STR);
if (!$sth->execute()) throw new Exception('A problem has occurred while updating database.');
return TRUE;
} catch (Exception $e) {
$this->error = $e->getMessage();
}
return FALSE;
}
}
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>The <code>*_once()</code> versions of <code>require()</code> and <code>include()</code> are relatively slower and should be avoided. When just including a few files it wont be noticeable, but the more you add, the more it will stack up. There are some exceptions, but headers and footers shouldn't be among them.</p>\n\n<p>When using <code>filter_input_array()</code>, you don't have to worry about a returned value being empty. Empty is usually reserved for empty arrays. NULL and FALSE are the negative returns. NULL for elements that aren't set, and FALSE for any failures. As long as you are sure you checked for a certain element and the key exists in the array, then all you have to do is treat the return as a boolean.</p>\n\n<pre><code>if( $inputs[ 'hid-submit' ] ) {\n</code></pre>\n\n<p>Your code is rather repetitive here. This violates one of the core OOP principles: \"Don't Repeat Yourself\" (DRY). As the name implies, your code should not repeat. Typically this can be fixed by creating a function or loop. There are a couple of different methods here. The first is to use <code>array_filter()</code> to keep only those elements with FALSE values. Then, since your errors seem so similar (only the last part changes), you can use a foreach loop later to provide the proper contents. The second method is to just use a foreach loop from the beginning and check each element individually. The first method is cleaner, but less reusable. If the <code>$errors</code> array expands and the rest of the errors aren't similar enough, then you will have to revert to using the second.</p>\n\n<pre><code>//array_filter method\n$errors = array_filter( $inputs, 'empty' );\n//later\nforeach( array_keys( $errors ) AS $error ) {\n echo \"this is not a valid $error\";//or throw error, log it, whatever...\n}\n\n//loop method\n$errors = array();\nforeach( $inputs AS $error => $value ) {\n if( ! $value ) {\n $errors[ $error ] = \"This is not a valid $error\";\n }\n}\n</code></pre>\n\n<p>PHP has two versions of syntax. The first you are already familiar with. The second is typically only used in include files and is preferred because of its more non-PHP friendly legibility. To go along with this is PHP's short echo tags <code><?=</code>, not to be confused with short open tags <code><?</code>. If your version of PHP is >= 5.4 then they are enabled by default and entirely separate from the dreaded short open tags. Below I am using both the secondary syntax and the short echo tag. If your version is lower than required, even though this feature is still available, I would suggest you keep using the echo and keep the short tags off.</p>\n\n<pre><code><?php if( $course->error !== FALSE ) : ?>\n\n <div id=\"error\"><?= $course->error; ?></div>\n\n<?php endif; ?>\n</code></pre>\n\n<p>What is the purpose of checking if the class exists already before creating it? If you are vigilant in the way you load your classes then there shouldn't be any issues with loading multiples of the same class. This is one of those few times where using the <code>*_once()</code> versions of <code>require()</code> or <code>include()</code> are ok. I'm assuming you are using an autoloader of some sort, just make sure that your class isn't already loaded there. You can do that with that same if statement you are currently using, or you can use that <code>*_once()</code> include.</p>\n\n<p>Leaving your class properties empty when first declaring them will give them all NULL values by default. Its only necessary to give it an explicit first value if you are planning on using it immediately.</p>\n\n<pre><code>private\n $id,\n $code,\n $name,\n $error\n;\n</code></pre>\n\n<p>Your getter and setter completely defies the purpose of having private properties. If you are just going to allow any application to modify your properties this way, you might as well make them public. It works the same and there's less code. Typically, a getter/setter is used to get/set only properties in a whitelist or array elements. The first is used for limited private property interaction, the second is primarily used in Views (MVC).</p>\n\n<pre><code>if( in_array( $property, $this->whitelist ) ) {\n return $this->$property;\n //or\n $this->$property = $value;\n}\n\n//or\n\nif( array_key_exists( $property, $this->data ) ) {\n return $this->data[ $property ];\n //or\n $this->data[ $property ] = $value;\n}\n</code></pre>\n\n<p>Returning <code>$this</code> is used to allow you to chain methods together (<code>$class->m1()->m2()</code>). Therefore, returning <code>$this</code> from your setter serves no purpose. You can't chain anything after setting a variable or property, so this makes no sense. Your setter doesn't need a return, you can just remove it.</p>\n\n<p>Your internal comments are unnecessary. Actually, all internal comments are unnecessary. They just add clutter. If you have something you need to explain, you should limit it to the doccomments.</p>\n\n<p>You should avoid defining variables in statements. Because of how easy it is to neglect the rest of the comparison (<code>==</code>, <code>!=</code>), it is sometimes quite difficult to determine if an assignment was meant or if this was just an accident. To avoid the confusion and potential backlash of improperly working code, you should just not do this. There are exceptions, such as loops, but generally this is considered bad practice. PHP is one of the few languages that still hasn't realized that. This feature actually lead to the development of the Yoda style to prevent accidental assignments in statements.</p>\n\n<pre><code>//bad\nif( $row = $sth->fetch( PDO::FETCH_OHJ ) ) {\n\n//good\n$row = $sth->fetch( PDO::FETCH_OHJ );\nif( $row ) {\n\nfor( $i = 0; //also fine\n</code></pre>\n\n<p>There is another principle being violated here: the Arrow Anti-Pattern. This pattern illustrates code that is heavily or unnecessarily indented so that it comes to points like an arrow. The arrow shape isn't necessary, its just one of the signs of violation. The problem with such code is legibility. The more indentation you have the less room per line you have for code (you should only go up to 80 characters, including indentation). It isn't bad here, but it should still be avoided. The easiest way to avoid violating this principle is to return early. And, if you are returning early, you can avoid unnecessary things like else statements. So, if we reverse our if logic so that the larger block of code would be in the else, then we can remove that entire level of indentation.</p>\n\n<pre><code>if( ! $sth->execute() ) {\n throw new Exception('A problem has occurred while retrieving information from database.');\n} //else {//else implied, not necessary\n\n//rest of code here, no more indentation\n</code></pre>\n\n<p>So, going back to that first principle I mentioned, DRY; If you look at your last two methods, you should notice that they do some pretty similar things. Both eventually connect to the database, prepare a statement, and bind some parameters. So, if we make this as reusable as possible, we can create a new private method. The easiest way to do this is to get our bindings into an array and loop over it. I'll let you create the actual method, but the below should help you get started.</p>\n\n<pre><code>$params = array(\n ':id' => array( $this->id, PDO::PARAM_INT ),\n ':code' => array( $this->code, PDO::PARAM_STR ),\n ':name' => array( $this->title, PDO::PARAM_STR )\n);\n\n$core = Core::getInstance();\n$sth = $this->core->dbh->prepare( $sql );\nforeach( $params AS $param => $data ) {\n list( $value, $type ) = $data;\n $sth->bindParam( $param, $value, $type );\n}\n</code></pre>\n\n<p>The biggest key, at least for me, to understanding OOP was to understand the underlying principles first. I mentioned one already and partially demonstrated it, DRY, but there are many more (Single Responsibility, Law of Demeter, etc...). My biggest suggestion to you would be to take a look at the <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">wikipedia entry for SOLID</a> and follow all of the links. Its a lot to read, but understanding all the principles and how they work together will make understanding OOP easier.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T03:07:20.407",
"Id": "32489",
"Score": "0",
"body": "Thanks (again) for your review, especially your mentioning about the different principles. I have much to learn."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T18:48:23.113",
"Id": "20292",
"ParentId": "20262",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20292",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T02:34:12.143",
"Id": "20262",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"pdo",
"form"
],
"Title": "How to properly use OOP in PHP with forms"
}
|
20262
|
<p>I am a JavaScript beginner. Here's a fictional example which isolates the functionality mentioned in the subject line. I hope to employ this functionality as part of a larger web application in the real world soon.</p>
<p><a href="http://illumin-8.com/lunchtime/addingelements.html" rel="nofollow">Live example here</a></p>
<p>An HTML5 page containing a simple form with one row:</p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Add Elements to a Form</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div id="addrow">
<label for="addnum">Add Rows:
<input type="text" name="addnum" id="addnum" value="" size="2">
</label>
<input type="button" name="addbtn" id="addbtn" value="Go!">
</div>
<br>
<fieldset id="lunches">
<legend>Let's do Lunch</legend>
<div class="formrow">
<span>My </span>
<select name="lunch[]" class="dropdown">
<option value="">Select a lunch item</option>
<option value="baloney">Baloney</option>
<option value="yogurt">Yogurt</option>
<option value="apple">Apple</option>
<option value="cheese">Government Cheese</option>
</select>
<span> has a </span>
<select name="firstorlast[]" class="dropdown">
<option value="first">First</option>
<option value="second">Second</option>
</select>
<span> name. It's</span>
<input type="text" name="name[]" value="Specify a Name" size="20">
</div>
</fieldset>
<script src="js/utilities.js"></script>
<script src="js/addelements.js"></script>
</body>
</html>
</code></pre>
<p><code>addelements.js</code> which contains the functionality for adding and removing rows of input. Each added row will have a button which, when clicked, will delete the row from the form. The first row cannot and should not be deleted:</p>
<pre><code> window.onload = function() {
'use strict';
//U.addEvent is a cross-browser way to add an event handler to a DOM object.
//U.$ is a shortcut to getElementById
//Idea taken from Larry Ullman's "Modern Javascript: Develop and Design
U.addEvent(U.$('addbtn'), 'click', addRows);
}
function addRows() {
'use strict';
var numRowsToAdd = U.$('addnum').value;
for(var i = 0; i < numRowsToAdd; i++){
addRow();
}
}
function addRow() {
'use strict';
var sourceNode = document.querySelector('.formrow');
var newRow = sourceNode.cloneNode(true);
//every row except the first row should have a delete button associated with it.
var delButton = document.createElement('input');
delButton.className = 'delbtn';
delButton.type = 'button';
delButton.name = 'delbtn';
delButton.value = 'Delete This Row';
U.addEvent(delButton, 'click', function() {removeRow(delButton)});
newRow.appendChild(delButton);
var fieldset = U.$('lunches');
fieldset.appendChild(newRow);
}
function removeRow(obj) {
'use strict';
var theRow = obj.parentNode;
var theRowParent = theRow.parentNode;
theRowParent.removeChild(theRow);
}
</code></pre>
<p>relevant code from <code>utilities.js</code>:</p>
<pre><code> var U = {
// For getting the document element by ID:
$: function(id) {
'use strict';
if (typeof id == 'string') {
return document.getElementById(id);
}
},
addEvent: function(obj, type, fn) {
'use strict';
if (obj && obj.addEventListener) { // W3C
obj.addEventListener(type, fn, false);
} else if (obj && obj.attachEvent) { // Older IE
obj.attachEvent('on' + type, fn);
}
}
}
</code></pre>
<p>If you copy and save these into the proper files with the proper path structure, it should work for you.</p>
|
[] |
[
{
"body": "<p>You should probably have a look at <a href=\"https://stackoverflow.com/questions/5805059/select-placeholder#answer-8442831\">https://stackoverflow.com/questions/5805059/select-placeholder#answer-8442831</a> and make the first line non-selectable by HTML only.</p>\n\n<p>It's done by making the first element <strong>selected</strong>, <strong>disabled</strong> and by adding a <strong>display:none</strong>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T17:28:09.387",
"Id": "32437",
"Score": "0",
"body": "As soon as I'm able to vote up your answer, I will."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-18T19:59:34.263",
"Id": "35156",
"Score": "0",
"body": "@DeeDee I think you can accept it if you think it answered your question (tick box under the score)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T13:36:10.360",
"Id": "20271",
"ParentId": "20263",
"Score": "2"
}
},
{
"body": "<p>I would suggest using event delegation instead of adding event handlers to each 'Delete' button individually.</p>\n\n<p>This can be done by attaching a click event listener to a parent element, then filtering the event target for a specified <code>className</code>.</p>\n\n<p>For example, if we added a function <code>U.on()</code> as follows (and utilizing <code>U.addEvent()</code> that you already have):</p>\n\n<pre><code>!(function () {\n\n'use strict';\n\n/**\n * helper function to delegate/attach DOM events\n * @param {String} root selector for event root element\n * @param {String} event single event name\n * @param {String} child className of target element\n * @param {Function} fn event handler\n */\nfunction on(root, eventName, child, fn) {\n var to = document.querySelector(root);\n var handler = delegator(child, fn);\n U.addEvent(to, eventName, handler);\n}\n\n/**\n * fires event handler if event target matches className\n * @param {String} className class to match\n * @param {Function} fn event handler to call\n */\nfunction delegator(className, fn) {\n return function (e) {\n if (e.target.classList.contains(className)) {\n fn.call(this, e);\n }\n };\n}\n\nU.on = on;\n\n})();\n</code></pre>\n\n<p>We could delegate all of the 'Delete' button click events to the parent form element, by doing to following:</p>\n\n<pre><code>on('#lunches', 'click', 'delbtn', function (e) {\n removeRow(e.target);\n});\n</code></pre>\n\n<p>This basically says, \"If a click happens inside an element with the id <code>lunches</code>, and the click happened on an element with the class <code>.delbtn</code>, then call this function that I'm passing in as the last argument.\"</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-25T03:20:32.753",
"Id": "48105",
"ParentId": "20263",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "20271",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T02:57:57.393",
"Id": "20263",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"html",
"html5",
"form"
],
"Title": "Using JavaScript to add and delete rows from an HTML 5 form"
}
|
20263
|
<p>I'm trying to write a simple <a href="https://en.wikipedia.org/wiki/Triplestore" rel="nofollow">triplestore</a> in Common Lisp that will store <a href="https://en.wikipedia.org/wiki/Resource_Description_Framework" rel="nofollow">triples</a> in the form subject-predicate-object. The code is inspired by the book <a href="http://rads.stackoverflow.com/amzn/click/0596153813" rel="nofollow">"Programming the Semantic Web"</a>.</p>
<pre class="lang-lisp prettyprint-override"><code>(defvar triplestore-graph (make-hash-table))
(defun triplestore-init ()
(puthash :spo (make-hash-table) triplestore-graph)
(puthash :pos (make-hash-table) triplestore-graph)
(puthash :osp (make-hash-table) triplestore-graph))
(defun triplestore-add (s p o)
(triplestore-add-to-index :spo s p o)
(triplestore-add-to-index :pos p o s)
(triplestore-add-to-index :osp o s p))
(defun triplestore-add-to-index (index a b c)
(let ((index (gethash index triplestore-graph)))
(cond ((not (gethash a index))
(let ((tmp (make-hash-table)))
(puthash a
(progn
(puthash b
(list c)
tmp)
tmp)
index)))
((not (gethash b (gethash a index)))
(puthash b
(list c)
(gethash a index)))
(t
(nconc (list c)
(gethash b
(gethash a index)))))))
</code></pre>
<p>Here <code>(puthash k v table)</code> is defined as <code>(setf (gethash k table) v)</code>. The code above is roughly equivalent to the Python code:</p>
<pre class="lang-python prettyprint-override"><code>graph = {}
def init(graph):
graph['_spo'] = {}
graph['_pos'] = {}
graph['_osp'] = {}
def add(graph, (s, p, o)):
_addToIndex(graph['_spo'], s, p, o)
_addToIndex(graph['_pos'], p, o, s)
_addToIndex(graph['_osp'], o, s, p)
def _addToIndex(index, a, b, c):
if a not in index:
index[a] = {b: set([c])}
elif b not in index[a]:
index[a][b] = set([c])
else:
index[a][b].add(c)
</code></pre>
<p>How can i improve readability and elegantness of the Common Lisp code? I'm mainly concerned that operations with hash-tables are verbose comparing to Python's equivalents. Are there macros for hash-table handling, for example?</p>
|
[] |
[
{
"body": "<p>First of all, I suggest that you use a structure instead of a hash table when you know that the table will only have 3 elements; this improves both readability and performance:</p>\n\n<pre><code>(defstruct triplestore-graph \n (spo (make-hash-table))\n (pos (make-hash-table))\n (osp (make-hash-table)))\n(defvar *triplestore-graph* (make-triplestore-graph))\n</code></pre>\n\n<p>Next, there is no <code>puthash</code> in Common Lisp, use <code>(setf gethash)</code> instead.</p>\n\n<p>Finally, I would modify the code like this:</p>\n\n<pre><code>(defun triplestore-add (s p o)\n (triplestore-add-to-index (triplestore-graph-spo *triplestore-graph*) s p o)\n (triplestore-add-to-index (triplestore-graph-pos *triplestore-graph*) p o s)\n (triplestore-add-to-index (triplestore-graph-osp *triplestore-graph*) o p s)) ; o s p?!\n\n(defun triplestore-add-to-index (index a b c)\n (let ((at (gethash a index)))\n (if at\n (pushnew c (gethash b at))\n (setf (gethash a index)\n (let ((tmp (make-hash-table)))\n (setf (gethash b tmp) (list c))\n tmp)))))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T23:53:42.353",
"Id": "20305",
"ParentId": "20266",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "20305",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T06:25:26.590",
"Id": "20266",
"Score": "2",
"Tags": [
"common-lisp",
"macros",
"hash-map"
],
"Title": "Simplify complex hash-table manipulations in Common Lisp"
}
|
20266
|
<p>I have this question in my exam and I want to know if my answer is correct.</p>
<p>Consider the following program written in C language to implement a reader:</p>
<pre><code>// to simplify the exercise, are not checked the return values of calls to the operating system
int main(int argc, char* argv[]) {
sem_t *sem_wrt;
int fd, readcount;
fd=shm_open("/readcount",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
ftruncate(fd, sizeof(int));
readcount=mmap(0,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
sem_wrt=sem_open("/write",O_CREAT ,0xFFFFFFFF,1);
while(1) {
readcount++;
if (readcount==1) sem_wait (wrt);
my_read();
(readcount)--;
if (readcount==0) sem_post (wrt);
}
}
</code></pre>
<p>After some time of using this program, it was found that the program only works properly when it is executed only by a process simultaneously.</p>
<p>Change the code of the program in order to provide a solution to this problem.</p>
<pre><code>int main(int argc, char* argv[]) {
sem_t *sem_wrt;
int fd, readcount;
fd=shm_open("/readcount",O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
ftruncate(fd, sizeof(int));
readcount=mmap(0,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
sem_wrt=sem_open("/write",O_CREAT ,0xFFFFFFFF,1);
//sem_mutex=sem_open("/mutex",O_CREAT ,0xFFFFFFFF,1);
while(1) {
//sem_wait(mutex);
readcount++;
if (readcount==1) sem_wait (wrt);
//sem_post(mutex);
my_read();
//sem_wait(mutex);
(readcount)--;
if (readcount==0) sem_post (wrt);
sem_post(mutex);
}
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>int fd, readcount;\n// ...\nreadcount=mmap(0,sizeof(int),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);\n</code></pre>\n\n<p>If this is the code you're using, it probably gave you a warning which you ignored. <code>mmap</code> returns <code>void *</code>. You should change the declaration of <code>readcount</code> to <code>int *</code>. Also, the size of the mapping should be a multiple of the page size. I'd be sure to re-read the manual for <code>mmap</code>, carefully read any compiler warnings, and make sure your code checks for errors.</p>\n\n<p>At any rate, if <code>int *readcount;</code> refers to shared memory, the following will not work:</p>\n\n<pre><code>++*readcount;\n</code></pre>\n\n<p>The problem is this line is conceptually broken into a few steps:</p>\n\n<ol>\n<li>Fetch <code>*readcount</code> into register</li>\n<li>Increment register</li>\n<li>Store back into <code>*readcount</code>.</li>\n</ol>\n\n<p>If multiple processes perform steps 1/2/3 in lockstep, and the initial value is 0, they will both store 1 back.</p>\n\n<p>You could use a GCC extension for <a href=\"http://en.wikipedia.org/wiki/Compare-and-swap\" rel=\"nofollow\">compare and swap</a> to make an increment safe:</p>\n\n<pre><code>int fetch;\ndo\n{\n fetch = *readcount;\n} while (!__sync_bool_compare_and_swap(readcount, fetch, fetch+1));\n</code></pre>\n\n<p>However I'm not sure if this will work right if you do it on memory mapped from a file by <code>mmap</code>. Keeping this kind of atomicity in a page fault handler seems complex and I'm not sure if the standard guarantees that it should work.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T19:36:46.700",
"Id": "20294",
"ParentId": "20272",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T15:06:33.837",
"Id": "20272",
"Score": "2",
"Tags": [
"c"
],
"Title": "Processes and semaphores in C"
}
|
20272
|
<p>I have this working code for C++ state machine using STL (not using boost state chart).</p>
<p>The purpose of posting is two-fold:</p>
<ol>
<li><p>To share a simple and working code C++ state machine using the STL for the sparse 'state' and 'event' function matrix.</p></li>
<li><p>To seek enhancements of implementation, since with this approach I have to init state machine for every new object created, which is not necessary since state-event function are same for all objects of a given class.</p></li>
</ol>
<p>(Note: while compiling using g++, use the "-std=c++0x" option and link both .cpp files to get the executable)</p>
<p><strong>File name: BasicFsmT.h</strong> </p>
<pre><code>//////////////////////////////////////////////////////////////////////
// File name : BasicFsmT.h
// Purpose : To define simple FSM implementation base class.
// This class to be inherited
// by any class which would like to implement FSM
///////////////////////////////////////////////////////////////////////
#ifndef _BasicFsmT_h
#define _BasicFsmT_h
#include <string>
#include <map>
#include <iostream>
#include <vector>
using namespace std;
class BasicFsm
{
public :
BasicFsm(); // Default Constructor
BasicFsm(string initialState);
virtual ~BasicFsm();
// StateMachine Method prototype
typedef int (*pFsmMethodT) (BasicFsm* pFSM, string event, int info);
virtual int AddState(string state);
virtual int AddStateEventMethod(string state, string event, pFsmMethodT);
virtual string GetState();
virtual int Fsm(string event, int info);
virtual int TransitionToState(string state);
virtual int SetPreviousEvent(string event);
protected :
vector<string> m_statesVec; // all valid states list in the fsm
vector<string> m_eventsVec; // all valid events list in the fsm
string m_fsmStateStr; // current state of the state fsm
string m_fsmPrevEventStr; // the last event procesed by the fsm
string m_fsmPrevStateStr; // the previous state of fsm
// the key is state and event strings concatanated together
map<string, pFsmMethodT> m_stateEventToMethodMap;
};
#endif // _BasicFsmT_h
////////////// End File : BasicFsmT.h ///////////////////////////////
</code></pre>
<p><strong>File name: BasicFsmT.cpp</strong></p>
<pre><code>//////////////////////////////////////////////////////////////////////
// File name : BasicFsmT.cpp
// Purpose : To define BasicFsmT Class methods. This class to be inherited
// by any class which would like to implement FSM
///////////////////////////////////////////////////////////////////////
#include <BasicFsmT.h>
#include <algorithm> // for std::find( ) etc.
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <stdlib.h>
/// Description : Default Constructor, called by derrived classes object
/// @param[in]
/// @returns
BasicFsm::BasicFsm()
{
m_statesVec.clear();
m_eventsVec.clear();
m_fsmStateStr.clear();
m_fsmPrevEventStr.clear();
m_fsmPrevStateStr.clear();
m_stateEventToMethodMap.clear();
}
/// Description : Constructor, with initial state to setup.
/// Need expicit call by derrived classes constructor.
/// @param[in]
/// @returns
BasicFsm::BasicFsm(string initialState)
{
m_statesVec.clear();
m_eventsVec.clear();
m_fsmStateStr.clear();
m_fsmPrevEventStr.clear();
m_fsmPrevStateStr.clear();
m_stateEventToMethodMap.clear();
m_statesVec.push_back(initialState);
m_fsmStateStr = initialState;
}
/// Description : Destructor, this can be overrided by derrived class's destructor
/// No special cleanup is needed..
/// @param[in]
/// @returns
BasicFsm::~BasicFsm()
{
}
/// Description : Add a state to be handled by the fsm
///
/// @param[in] : state to be handled by the fsm
/// @returns
int BasicFsm::AddState(string state)
{
vector<string>::iterator itr;
itr = find(m_statesVec.begin(), m_statesVec.end(), state);
if (itr == m_statesVec.end())
{
m_statesVec.push_back(state);
}
// else state is already available
}
/// Description : Store the address of Method/function to be called
/// for the specified state and event
/// @param[in] : state - at which the specified Method is applicable.
/// @param[in] : event - for which the specified Method is applicable.
/// @param[in] : pFunc - Address of the Method to be called for the
/// specified state and event.
/// @returns
int BasicFsm::AddStateEventMethod(string state, string event, pFsmMethodT pFunc)
{
string stateNEvent;
vector<string>::iterator itr;
itr = find(m_statesVec.begin(), m_statesVec.end(), state);
if (itr == m_statesVec.end())
{
m_statesVec.push_back(state);
}
// else state is already available
itr = find(m_eventsVec.begin(), m_eventsVec.end(), state);
if (itr == m_eventsVec.end())
{
m_eventsVec.push_back(event);
}
// else state is already available
// Add the function pointer to be called for the specified state-event pair
stateNEvent = state + event;
m_stateEventToMethodMap[stateNEvent] = pFunc;
}
/// Description : Get the current state of the fsm
/// @param[in] :
/// @returns
string BasicFsm::GetState()
{
return (m_fsmStateStr);
}
/// Description : Change fsm state to the specified state.
/// @param[in]
/// @returns
int BasicFsm::TransitionToState(string state)
{
vector<string>::iterator itr;
itr = find(m_statesVec.begin(), m_statesVec.end(), state);
if (itr != m_statesVec.end())
{ // transition to state is a valid state
m_fsmPrevStateStr = m_fsmStateStr;
m_fsmStateStr = state;
}
// else transition to state is not valid
}
/// Description : set fsm processed event to the specified event.
/// @param[in]
/// @returns
int BasicFsm::SetPreviousEvent(string event)
{
vector<string>::iterator itr;
itr = find(m_eventsVec.begin(), m_eventsVec.end(), event);
if (itr != m_eventsVec.end())
{ // transition to state is a valid state
m_fsmPrevEventStr = event;
}
// else event is not valid
}
/// Description : Calls the Method specified for the specified state
/// event
/// @param[in] event - The event to be processed
/// @param[in] info - Additional info needed for the method to process.
/// @returns -1 - If specfied state or event is in valid, or
/// no fsm function is defined for that state+event pair.
int BasicFsm::Fsm(string event, int info)
{
pFsmMethodT pFunc;
int retStatus;
string state, stateNEvent;
try {
state = GetState();
stateNEvent = state + event;
map<string, pFsmMethodT>::iterator itr =
m_stateEventToMethodMap.find(stateNEvent);
// validate state, event and event handler
if (itr == m_stateEventToMethodMap.end())
{
return(-1);
}
pFunc = itr->second; // get pointer to the function to be executed.
// retStatus = (this->*(pFunc))(this, event, info);
retStatus = (*(pFunc))(this, event, info);
SetPreviousEvent(event);
return(retStatus);
} // end try
catch(exception& Error) {
stringstream logErr;
logErr << "Exception at BasicFsm::fsm, Error : " << Error.what();
}
}
/////////// End File : BasicFsmT.cpp ////////////////////////////////
</code></pre>
<p><strong>File name: BasicFsmTest.cpp</strong></p>
<pre><code>//////////////////////////////////////////////////////////////////////
// File name : BasicFsmTest.cpp
// Purpose : To test implementation of FSM by BasicFsmT Class.
// This includes BasicFsmT as public base class to implement a
// sample Telephone state machine.
//
///////////////////////////////////////////////////////////////////////
#include <BasicFsmT.h>
#include <algorithm> // for std::find( ) etc.
#include <iostream>
#include <sstream>
#include <stdexcept>
///////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
/////// Test Functions for BasicFsm Class ////////////////////
namespace TelephoneEnumsT
{
// List of Valid Sate in the Stmc
const string S_Idle = "S_Idle";
const string S_DIGIT_COLLECTION = "S_DigitCollection";
const string S_ESTABLISHING = "S_Establishing";
const string S_RINGING_OG = "S_RingingOG";
const string S_RINGING_IC = "S_RingingIC";
const string S_CALL_ESTABLISHED = "S_Established";
const string S_CALL_FE_TERMINATED = "S_FETerminated";
// List of Valid Events in the Stmc
const string E_ONHOOK = "E_Onhook";
const string E_OFFOOK = "E_Offhook";
const string E_DIGIT_COLLECT = "E_DigitCollect";
const string E_DIGIT_COLLECT_COMPLETE = "E_DigitCollectComplete";
const string E_OG_RING = "E_OGRing";
const string E_REMOTE_ANSWER = "E_RemoteAnswer";
const string E_IC_RING = "E_ICRing";
const string E_TIMEOUT = "E_Timeout";
}; // end namespace declaration
class Telephone : public BasicFsm
{
private :
string digitsCollected;
string myNumber;
time_t call_st_time;
time_t call_end_time;
public :
Telephone();
Telephone(string myNumber);
~Telephone();
void DispDigitsCollected()
{
cout << "Digits collected so far = " << digitsCollected << endl;
}
friend int OffHookAtIdle(BasicFsm* pFsm, string event, int info);
friend int DigitCollect(BasicFsm* pFsm, string event, int info);
friend int DigitCollectComplete(BasicFsm* pFsm, string event, int info);
friend int TimeoutAtDigitCollection(BasicFsm* pFsm, string event, int info);
friend int OffHookAtEstablished(BasicFsm* pFsm, string event, int info);
/// This state-event processing list of functions are not complete
void InitFsm(); // This will init the fsm functions
}; // end of Telephone class declaration
using namespace std;
using namespace TelephoneEnumsT;
Telephone::Telephone()
{
digitsCollected.clear();
myNumber.clear();
call_st_time = 0;
call_end_time = 0;
}
Telephone::Telephone(string myNumber)
{
digitsCollected.clear();
myNumber.assign(myNumber);
call_st_time = 0;
call_end_time = 0;
}
Telephone::~Telephone()
{
}
int OffHookAtIdle(BasicFsm* pFsm, string event, int info)
{
stringstream logMsg;
try {
Telephone* pPhone = static_cast <Telephone*> (pFsm);
logMsg << "In Function OffHookAtIdle() " << " At State "
<< pFsm->GetState() << " For Event " << event << endl;
cout << logMsg.str() << endl;
// Do the required Processing
pPhone->digitsCollected.clear();
// Do state transition and do some book keeping
pPhone->TransitionToState(TelephoneEnumsT::S_DIGIT_COLLECTION);
pPhone->SetPreviousEvent(event);
} // end try
catch (exception& Error) {
stringstream logErr;
logErr << "Exception at OffHookAtIdle(), Error : " << Error.what();
}
return(0);
}
int DigitCollect(BasicFsm* pFsm, string event, int info)
{
stringstream logMsg;
try {
Telephone* pPhone = static_cast <Telephone*> (pFsm);
logMsg << "In Function DigitCollect() " << " At State "
<< pFsm->GetState() << " For Event " << event
<< " adding digit to dialed number " << info << endl;
cout << logMsg.str() << endl;
// Do the required Processing
char cinfo[8];
sprintf(cinfo,"%d",info);
pPhone->digitsCollected.append((const char *) (&cinfo), (size_t)(1));
// Do state transition and do some book keeping
pPhone->SetPreviousEvent(event);
} // end try
catch (exception& Error) {
stringstream logErr;
logErr << "Exception at DigitCollect(), Error : " << Error.what();
}
return(0);
}
int DigitCollectComplete(BasicFsm* pFsm, string event, int info)
{
// Do the required Processing
return(0);
}
int TimeoutAtDigitCollection(BasicFsm* pFsm, string event, int info)
{
// Do the required Processing
return(0);
}
int OffHookAtEstablished(BasicFsm* pFsm, string event, int info)
{
// Do the required Processing
return(0);
}
void Telephone::InitFsm()
{
AddStateEventMethod(TelephoneEnumsT::S_Idle,
TelephoneEnumsT::E_OFFOOK,
&(OffHookAtIdle));
AddStateEventMethod(TelephoneEnumsT::S_DIGIT_COLLECTION,
TelephoneEnumsT::E_DIGIT_COLLECT,
&(DigitCollect));
// Add State - Event functions so forth...
}
int main()
{
int fsmStatus;
Telephone myPhone1("1112223333");
myPhone1.InitFsm();
// Test some event handlers
myPhone1.TransitionToState(S_Idle);
fsmStatus = myPhone1.Fsm(E_OFFOOK, 0);
fsmStatus = myPhone1.Fsm(E_DIGIT_COLLECT, 9);
Telephone myPhone2("2223331234");
myPhone2.InitFsm();
// Test some event handlers
myPhone2.TransitionToState(S_Idle);
fsmStatus = myPhone2.Fsm(E_OFFOOK, 1);
fsmStatus = myPhone2.Fsm(E_DIGIT_COLLECT, 2);
myPhone1.DispDigitsCollected();
myPhone2.DispDigitsCollected();
// Authors comment: try to modify the base class, which can still be
// inherited by any FSM implementing classes
// where you just need to do Telephone::InitFsm();
// instead of doing myPhone1.InitFsm(); and myPhone2.InitFsm(); ...
}
/////// End File : BasicFsmTest.cpp //////////////////////////////////////////
</code></pre>
|
[] |
[
{
"body": "<h2>Two beginners mistakes:</h2>\n\n<h3>Leading underscore in identifers</h3>\n\n<pre><code>#ifndef _BasicFsmT_h\n#define _BasicFsmT_h\n</code></pre>\n\n<p>Using a leading underscore is a bad idea. The exact rules are complex and people usually get them wrong. So just don't use them and you will be safe. </p>\n\n<p>See: <a href=\"https://stackoverflow.com/a/228797/14065\">What are the rules about using an underscore in a C++ identifier?</a></p>\n\n<h3>using directives.</h3>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Never do this (at file scope) in a header file (any using directive). It means that if I include your code all the standard libraries have been imported into the global namespace for my code which may break it. This may potentially stop people from using your code.</p>\n\n<p>Even in source files this is a bad idea. The whole reason the namespace is called <code>std</code> rather than <code>standard</code> is so prefixing items with <code>std::</code> is not a major problem. Please start to use this.</p>\n\n<p>If you really don't want to use <code>std::</code> (you should) then you import specific things by doing</p>\n\n<pre><code>using std::cin; // only imports std::cin into the current namespace.\n</code></pre>\n\n<p>This is also usable within a scope:</p>\n\n<pre><code>void foo()\n{\n using std::cin;\n cin << \"Hi there\\n\";\n}\nvoid bar()\n{\n cin << \"This will fail to compile\\n\";\n}\n</code></pre>\n\n<p>You shoudl read this: <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is 'using namespace std;' considered a bad practice in C++?</a></p>\n\n<p>The most important answer for me is: <a href=\"https://stackoverflow.com/a/1453605/14065\">https://stackoverflow.com/a/1453605/14065</a></p>\n\n<h2>Interfaces:</h2>\n\n<p>Your BasicFsm uses function pointers. This is very C. An easy way is to define an interface that implements the method. This will make the code easier to read and write:</p>\n\n<pre><code>// StateMachine Method prototype\ntypedef int (*pFsmMethodT) (BasicFsm* pFSM, string event, int info);\n\n// I would write:\nstruct FsmMethodInterface\n{\n virtual ~FsmMethodInterface() {}\n virtual int doWork(BasicFsm& pFSM, std::string event, int info) = 0;\n};\n// Note: unless pFSM can be NULL (I suspect it can't) then you should\n// pass it by reference (then you don't need to check for NULL).\n</code></pre>\n\n<p>This is also more useful as it allows you to maintain state in the callback if required.</p>\n\n<h3>Constructor</h3>\n\n<pre><code>/// Description : Default Constructor, called by derrived classes object\n/// @param[in] \n/// @returns \nBasicFsm::BasicFsm()\n{\n m_statesVec.clear();\n m_eventsVec.clear();\n m_fsmStateStr.clear();\n m_fsmPrevEventStr.clear();\n m_fsmPrevStateStr.clear();\n m_stateEventToMethodMap.clear();\n}\n</code></pre>\n\n<p>This is doing no useful work. All those members are constructed empty. Just remove the constructor if it does nothing explicit.</p>\n\n<h3>Comments:</h3>\n\n<p>Comments that do nothing but repeat what the code says are worse than useless. They can fall out of sync with the code and provide no meaningful information to the a maintainer (and thus waste space).</p>\n\n<pre><code>/// Description : Add a state to be handled by the fsm\n/// \n/// @param[in] : state to be handled by the fsm\n/// @returns \nint BasicFsm::AddState(string state)\n{\n</code></pre>\n\n<p>The code explains what it is doing (with menaingful method/variable names). The comments should explain <strong>WHY</strong> it is doing it. If the why is obvious that don't write anything.</p>\n\n<p>Exceptions:</p>\n\n<pre><code>} // end try\ncatch(exception& Error) {\n stringstream logErr;\n logErr << \"Exception at BasicFsm::fsm, Error : \" << Error.what();\n} \n</code></pre>\n\n<p>Best to catch exceptions by const reference. YOu probably don't want to alter the exception.</p>\n\n<p>Also exceptions do not need to be derived from std::exception (they could be std::string or int or anything else. <code>catch(...)</code> catches anything. But if you use this the best you can usually do is log and re-throw the exception.</p>\n\n<p>So you logged the exception (which is good). But is that enough (It may be I don;t the code well enough). If an exception was thrown can you continue? The fact that something failed would suggest that unless you explicitly fix it the state of the machine is not good. If you cant't fix it then after you log the exception you should probably re-throw it.</p>\n\n<h2>Below is a discussion Seth and I are having.</h2>\n\n<p>It turns out Seths comments are more accurate then mine.<br>\nI am leaving the original comments for context.</p>\n\n<p>In modern C++ functors and duck typing are more heavily used (then would be suggested by my answer above). </p>\n\n<p>Seth thinks that they can be used in the current situation (I hope they can). But I can see how this will be done. We needed more space than the comments provided so we are working in the answer at the moment. This is an ongoing discussion which when resolved will be cleaned up.</p>\n\n<h3>From @Seth</h3>\n\n<p>So the more modern way to add generic functions would be:</p>\n\n<pre><code>int AddStateEventMethod(string state, string event, std::function<int(BasicFsm*, string, int)> func)\n{\n /* CODE AS BEFORE */\n\n // Add the function pointer to be called for the specified state-event pair\n\n stateNEvent = state + event;\n m_stateEventToMethodMap[stateNEvent] = func;\n}\n\nstd::map<std::string, std::function<int(BasicFsm*, string, int)>> m_stateEventToMethodMap;\n</code></pre>\n\n<h3>Response from @Loki</h3>\n\n<p>Unfortunately this provides exactly zero benefit over the original and as such is not really modern C++. The whole point of modern C++ duck typing is that you could pass any object that behaves like a function. This actively prevents this and we have exactly the same code as above (just wrapped with std::function) so no real benefit.</p>\n\n<p>To make this work in a modern C++ way you need to be able to templatize <code>int AddStateEventMethod()</code> but I can see how that would work.</p>\n\n<pre><code>template<typename T>\nint BasicFsm::AddStateEventMethod<T>(string state, string event, T func)\n{\n /* CODE AS BEFORE */\n\n // Add the function pointer to be called for the specified state-event pair\n\n -- What goes here --\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T00:31:20.053",
"Id": "32480",
"Score": "1",
"body": "NOTE: The practice of adding the \"\\_\" or \"__\" at the beginning and end of the defines, is a technique long used in the layers of abstraction \"hardware/middleware\" to prevent that the end developer do make errors of inclusion. example in HAL: `__UART_H__`, in user code: `UART_H`. if in some cases the use of this \"defines\" is correct. +1 For the detailed answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T02:29:46.920",
"Id": "32487",
"Score": "0",
"body": "While using function pointers is very C, making users of the class inherit from one of your classes is very \"old C++\". Isn't it better to write it as either a template if possible, else take an `std::function`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T06:52:23.990",
"Id": "32501",
"Score": "0",
"body": "@SethCarnegie: I would agree in most situations. But not in this specific case. Because the object is storing a container full of functors. You need to use a consistent interface to facilitate storage."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T07:05:35.133",
"Id": "32503",
"Score": "1",
"body": "@RTOSkit: The implementation is allowed to use any identifers it likes (such as `__UART_H__`). Unfortunately using this pattern in user code is not legal. Thus adding \" __ \" (double underscore) is always illegal. And adding \" _ \" (single underscore) at the beginning of an identifier is also always **wrong with macros** (assuming you follow the rule of making macros all upper-case). So in user space code we should be very careful to use underscore."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T07:29:28.570",
"Id": "32505",
"Score": "0",
"body": "Thanks for the correct justification and interpretation, in order to know that the \"low level\" we are always more illegal :) .You will know that when need optimizing code, we try using more the precompiler and these \"illegal defines\" are a strategy that not seem corect but are fluid and deterministic. ...¿What is upper-case? ? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T16:03:55.303",
"Id": "32535",
"Score": "0",
"body": "@LokiAstari why can't you store `std::function`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T18:55:51.490",
"Id": "32559",
"Score": "0",
"body": "@SethCarnegie: Its templated. Thus storing a `std::map<std::string, std::function<????>>` of them is not obvious how you would achieve that. But I am open to suggestion add an answer that uses std::function (or add a description to my answer)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T18:59:45.677",
"Id": "32561",
"Score": "0",
"body": "@LokiAstari maybe I don't understand you because I can't see where the `???` comes from, and there are no templates in his code, and I mean instead of storing instances of classes that implement an interface, store instances of `std::function<int(BasicFsm* pFSM, string event, int info)>`. By \"templating if possible\" I mean storing a map of `T` where `T` can be a user-defined functor, a function pointer, or `std::function` or whatever."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T19:57:37.007",
"Id": "32567",
"Score": "0",
"body": "I don't see what storage has to do with it, if anything `std::function` is more flexible when it comes to storage ( unless they've changed something, as I'm still on `boost::function` )."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T20:06:58.293",
"Id": "32569",
"Score": "0",
"body": "@SethCarnegie: That does not help. Please show me how to use a generic duck typed functor as you suggest in your first comment and store it in a map. You have said that my way is wrong but (and I can believe that, I just don't know how to do it better here). What I want is you to show me the **code** for it to work with modern C++. Otherwise I have to stick to original assertion that the interface is the better way to go. Note: I would prefer a generic solution I just can't see it (so need code)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T20:23:36.223",
"Id": "32575",
"Score": "0",
"body": "@LokiAstari there, I edited the code to add an example for the non-template way. I hope you can see it, the site says it needs to be peer reviewed before anyone else can see it. Again, I get the feeling I'm missing something because it was really simple."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T20:57:59.063",
"Id": "32579",
"Score": "0",
"body": "@SethCarnegie: I will approve the edit. But I don't see how that helps over bare pointers. You have added a layer of indirection without adding any benefit. The point of modern C++ and functors (is to be able to add state to your callback). What you have added gives no real benefit. As I still can not using anything but a pointer (and that is what we are trying to get away from)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T21:09:49.813",
"Id": "32581",
"Score": "0",
"body": "@LokiAstari why, of course you can, you can use lambdas, custom functors, `std::bind`s, and normal function pointers. `std::function` can hold any callable object. What am I missing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T21:16:31.047",
"Id": "32583",
"Score": "0",
"body": "@SethCarnegie: If that's true that would be perfect. I will try it. If it works I will update. I did not think that it would work based on the `std::function` contained `BasicFsm*` but I am still exploring the C++11 functionality. So I will update tonight after work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T21:22:57.290",
"Id": "32584",
"Score": "0",
"body": "@LokiAstari Oh sorry, I thought I had seen you answer a lot of C++11 questions on SO. Here is an example: http://tinyurl.com/bdswzve"
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T17:17:45.687",
"Id": "20284",
"ParentId": "20273",
"Score": "10"
}
},
{
"body": "<p>Adding to the previous post.</p>\n\n<p><strong>Don't try to inhibit bugs, define pre conditions instead</strong></p>\n\n<p>Your <code>AddState</code> searches to see if there's already a state with the supplied identifier, and if that's the case it silently does nothing. If duplicates are not allowed you should either return an error / throw exception or simply assert. Robustness aside I'd rather have:</p>\n\n<pre><code>int BasicFsm::AddState(string state)\n{\n assert(find(m_statesVec.begin(), m_statesVec.end(), state) != m_statesVec.end());\n m_statesVec.push_back(state);\n}\n</code></pre>\n\n<p>Which to top it of is also faster. A good rule is to fail as fast as possible, this way you're more likely to spend your time debugging the actual bug instead of its consequences.</p>\n\n<p><strong>Learn when and where to use const, and const reference in particular</strong></p>\n\n<p>You have a couple of instances of this, but as a rule of thumb builtins are the only types which should be passed by value. There's very few instances where you need a copy of an argument. <code>AddState(string state)</code> should be <code>AddState(const string& state)</code>. If you don't need to modify the argument add <code>const</code>, this way the caller knows what to expect.</p>\n\n<p><strong>Unless you're INCREDIBLY concerned about memory / performance don't use bare function pointers</strong></p>\n\n<p>They're just so incredibly inferior to <code>std::function</code> ( or <code>boost::function</code> for that matter ). Describing the power of <code>std::bind</code> & <code>std::function</code> would be quite lengthy, so unless you want to know anything in particular it's probably better to google.</p>\n\n<p><strong>Don't make things virtual just for the heck of it</strong></p>\n\n<p>I see no reason for why you want all the member functions of <code>Fsm</code> to be virtual, you're unnecessarily paying for virtual dispatch and by making member functions in your base virtual you're deceiving the user of it. Qualifiers describes intent, by making all functions virtual you're saying \"All calls to me can do pretty much anything under the sun\". If you later find that you need <code>AddState</code> to be virtual, make it virtual at that point instead. Good design is much more about restricting than enabling.</p>\n\n<p><strong>Don't use strings for static identifiers</strong></p>\n\n<p>This is a very common mistake made even by pretty experienced programmers, but strings makes for very poor static identifiers. They're expensive to compare for equality, requires unnecessary amounts of storage, introduces a whole slew of possibilities for user errors which are hard to impossible to check for at compile time, and inhibits the possibilities for generic programming. In this case there's nothing really stopping you from using static tags. IE:</p>\n\n<pre><code> struct Event { virtual ~Event(){} }; // Needs at least 1 virtual function for vtable\n struct OnHook : public Event {};\n //...\n\n struct State { virtual ~State(){} }; // Dtor for vtable\n struct IdleState : public State {};\n //...\n map< std::pair< Loki::TypeInfo, Loki::TypeInfo >, pFsmMethodT > m_stateEventToMethodMap;\n //...\n void BasicFsm::AddStateEventMethod( const State& state, const Event& event, pFsmMethodT pFunc)\n {\n m_stateEventToMethodMap[ std::make_pair( Loki::TypeInfo( typeid( state ) ), Loki::TypeInfo( typeid( event ) ) ) ] = pFunc;\n }\n</code></pre>\n\n<p><code>Loki::TypeInfo</code> is a handy container for <code>std::type_info</code> which gives us the ability to use them as keys, if you opt to not use RTTI you need another way associate a type with unique ID, there's a ton of ways to do this ( the easiest probably being a virtual function ). This way is faster than using strings, and now we can't for example pass an event as a state by accident, or introduce user created strings which doesn't map to valid states or events.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T20:27:18.120",
"Id": "32576",
"Score": "1",
"body": "Instead of `Loki::TypeInfo` you can use `std::type_index` in C++11."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T20:29:59.613",
"Id": "32577",
"Score": "0",
"body": "Ah, cool, still stuck in the old times where I don't have C++11 :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-09T20:25:37.900",
"Id": "20351",
"ParentId": "20273",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T15:21:18.887",
"Id": "20273",
"Score": "8",
"Tags": [
"c++",
"stl",
"state-machine"
],
"Title": "Designing a state machine in C++ using the STL"
}
|
20273
|
<p>I wrote code that queries a data structure that contains various triples - 3-item tuples in the form subject-predicate-object. I wrote this code based on an exercise from <em><a href="http://shop.oreilly.com/product/9780596153823.do" rel="nofollow noreferrer">Programming the Semantic Web</a></em> textbook.</p>
<pre><code>def query(clauses):
bindings = None
for clause in clauses:
bpos = {}
qc = []
for pos, x in enumerate(clause):
if x.startswith('?'):
qc.append(None)
bpos[x] = pos
else:
qc.append(x)
rows = list(triples(tuple(qc)))
if bindings == None:
# 1st pass
bindings = [{var: row[pos] for var, pos in bpos.items()}
for row in rows]
else:
# >2 pass, eliminate wrong bindings
for binding in bindings:
for row in rows:
for var, pos in bpos.items():
if var in binding:
if binding[var] != row[pos]:
bindings.remove(binding)
continue
else:
binding[var] = row[pos]
return bindings
</code></pre>
<p>The function invocation looks like:</p>
<pre><code>bg.query([('?person','lives','Chiapas'),
('?person','advocates','Zapatism')])
</code></pre>
<p>The function <code>triples</code> inside it accepts 3-tuples and returns list of 3-tuples. It can be found <a href="https://codereview.stackexchange.com/q/19470/12332">here</a>.</p>
<p>The function <code>query</code> loops over each clause, tracks variables (strings that start with '?'), replaces them with None, invokes <code>triples</code>, receives rows, tries to fit values to existing bindings.</p>
<p>How can I simplify this code? How can I make it more functional-style, without nested <code>for</code>-loops, <code>continue</code> keyword and so on?</p>
|
[] |
[
{
"body": "<ol>\n<li>Your code would be helped by splitting parts of it out into functions.</li>\n<li>Your <code>continue</code> statement does nothing</li>\n<li>Rather then having a special case for the first time through, initialize <code>bindings</code> to <code>[{}]</code> for the same effect. </li>\n</ol>\n\n<p>My version:</p>\n\n<pre><code>def clause_to_query(clause):\n return tuple(None if term.startswith('?') else term for term in clause)\n\ndef compatible_bindings(clause, triples):\n for triple in triples:\n yield { clause_term : fact_term\n for clause_term, fact_term in zip(clause, row) if clause_term.startswith('?')\n }\n\ndef merge_bindings(left, right):\n shared_keys = set(left.keys()).intersection(right.keys)\n\n if all(left[key] == right[key] for key in shared_keys):\n bindings = left.copy()\n bindings.update(right)\n return bindings\n else:\n return None # indicates that a binding cannot be merged\n\n\ndef merge_binding_lists(bindings_left, bindings_right):\n new_bindings = []\n for left, right in itertools.product(bindings_left, bindings_right):\n merged_binding = merge_bindings(left, right)\n if merged_binding is not None:\n new_bindings.append( merged_binding )\n\n return new_bindings\n\n\ndef query(clauses):\n bindings = [{}]\n for clause in clauses:\n query = clause_to_query(clause)\n new_bindings = compatible_bindings(clause, triples(query))\n bindings = merge_binding_lists(bindings, new_bindings)\n\n return bindings\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T20:02:00.293",
"Id": "20295",
"ParentId": "20278",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "20295",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-08T16:48:24.977",
"Id": "20278",
"Score": "3",
"Tags": [
"python",
"functional-programming"
],
"Title": "Querying a data structure that contains various triples"
}
|
20278
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.