body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have a php authentication script and everything works fine, but I'm very unsure about the way I programmed it (I hardcoded some things). I was hoping stack could look through this and point out any potential problems. Here's the script:</p> <pre><code>&lt;?php require_once 'Bcrypt.php'; class Mysql { private $conn; function __construct() { $this-&gt;conn = new PDO('mysql:host=***;dbname=***;charset=UTF-8','***','***') or die('There was a problem connecting to the database.'); } function verify_Username_and_Pass($un, $pwd) { ini_set('display_errors', 'On'); error_reporting(E_ALL | E_STRICT); $query = "SELECT * FROM Conference WHERE Username = :un"; $stmt = $this-&gt;conn-&gt;prepare($query); $stmt-&gt;bindParam(':un', $un); //$stmt-&gt;bindParam(':pwd', $pwd); $stmt-&gt;execute(); $row = $stmt-&gt;fetchAll(); $hash = $row[0]["Password"]; $is_correct = Bcrypt::check($pwd, $hash); if ($is_correct) { // User exist $firstName = $row[0]["First Name"]; $_SESSION["FirstName"] = $firstName; return true; $stmt-&gt;close(); } else { // User doesn't exist return false; $stmt-&gt;close(); } } } ?&gt; </code></pre> <p>So how does it look?</p>
[]
[ { "body": "<p>I've tried cleaning it up a bit here, removed instances of setting a variable once and using it directly below where it was set (yes, improves readability, but still). </p>\n\n<pre><code>require_once 'Bcrypt.php';\n\nclass Mysql {\n private $conn;\n private $host = 'host';\n private $dbName = 'dbname'; \n private $charset = 'UTF-8';\n private $checkUserQuery = 'SELECT * FROM Conference WHERE Username = :un';\n\n function __construct() {\n $this-&gt;conn = new PDO('mysql:host=' . $this-&gt;host . ';dbname=' . $this-&gt;dbname . ';charset=' . $this-&gt;charset) \n or die('There was a problem connecting to the database.');\n }\n\n function verifyUsernameAndPass($un, $pwd) {\n $stmt = $this-&gt;conn-&gt;prepare($this-&gt;checkUserQuery);\n\n $stmt-&gt;bindParam(':un', $un);\n #$stmt-&gt;bindParam(':pwd', $pwd);\n $stmt-&gt;execute();\n $row = $stmt-&gt;fetchAll();\n $stmt-&gt;close(); # Moved up, so closes before we return/exit function\n\n # You're setting $hash here, and using it directly below.\n # See new code below\n //$hash = $row[0]['Password'];\n //$is_correct = Bcrypt::check($pwd, $hash);\n\n //if ($is_correct) {\n if( Bcrypt::check($pwd, $row[0]['Password']) ){\n # User exist\n\n # You're setting $firstName once, and using it directly below it.\n # See new code below\n //$firstName = $row[0]['First Name']; \n //$_SESSION['FirstName'] = $firstName;\n\n $_SESSION['FirstName'] = $row[0]['First Name'];\n\n return true;\n } else {\n # User does not exist\n return false;\n }\n }\n}\n</code></pre>\n\n<p>And here's the same code, without my comments:</p>\n\n<pre><code>require_once 'Bcrypt.php';\n\nclass Mysql {\n private $conn;\n private $host = 'host';\n private $dbName = 'dbname'; \n private $charset = 'UTF-8';\n private $checkUserQuery = 'SELECT * FROM Conference WHERE Username = :un';\n\n function __construct() {\n $this-&gt;conn = new PDO('mysql:host=' . $this-&gt;host . ';dbname=' . $this-&gt;dbname . ';charset=' . $this-&gt;charset) \n or die('There was a problem connecting to the database.');\n }\n\n function verifyUsernameAndPass($un, $pwd) {\n $stmt = $this-&gt;conn-&gt;prepare($this-&gt;$checkUserQuery);\n\n $stmt-&gt;bindParam(':un', $un);\n $stmt-&gt;execute();\n $row = $stmt-&gt;fetchAll();\n $stmt-&gt;close();\n\n if( Bcrypt::check($pwd, $row[0]['Password']) ){ # User exists\n $_SESSION['FirstName'] = $row[0]['First Name'];\n return true;\n } else { # User does not exist\n return false;\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T17:19:17.173", "Id": "16233", "ParentId": "16209", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T19:37:26.827", "Id": "16209", "Score": "5", "Tags": [ "php", "sql", "mysql", "pdo" ], "Title": "PHP Login Authentication with BCrypt" }
16209
<p>I'm a complete PHP beginner and would like some feedback on this registration page I've created. Now, the one thing I know right off that bat that's wrong with it is that there's WAY too much commenting. This was for my benefit to help teach myself as I went along and help avoid confusion as I read back through my code.</p> <p>What this page does in a nutshell: Presents a form for the user to register for the site. Some of the fields are validated. It allows the user to upload an avatar, then the code renames the file, moves it to a directory on the server, then re-sizes it and saves it as a .jpg. Once everything is okay it adds the new user to the database.</p> <pre><code>&lt;?php /*Give all POST variables the 'var' prefix*/ import_request_variables("p", "var"); ?&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;link rel="stylesheet" type="text/css" href="styles/styles.css" /&gt; &lt;title&gt;Register&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;?php /*Call header*/ include 'header.php'; ?&gt; &lt;!--Registration form. The 'name' attributes will have 'var' added to them to become variables. The 'value' attribute will be populated only if there is an error, so the user doesn't have to type everything in again.--&gt; &lt;form enctype="multipart/form-data" method="post"&gt; &lt;table id="regTable"&gt; &lt;tr&gt; &lt;td&gt;*Desired Screen Name:&lt;/td&gt;&lt;td&gt; &lt;input type="text" name="username" value="&lt;?php print $varusername ?&gt;" maxlength="30" autofocus /&gt; &lt;/td&gt; &lt;td id="usernameast" class="ast"&gt;*&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;*Password:&lt;/td&gt;&lt;td&gt; &lt;input type="password" name="password" value="&lt;?php print $varpassword ?&gt;" /&gt;&lt;/td&gt; &lt;td id="passwordast" class="ast"&gt;*&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;*Verify Password: &lt;/td&gt;&lt;td&gt;&lt;input type="password" name="verpassword" value="&lt;?php print $varverpassword ?&gt;" /&gt;&lt;/td&gt; &lt;td id="verpasswordast" class="ast"&gt;*&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;*Email address: &lt;/td&gt;&lt;td&gt;&lt;input type="text" name="email" value="&lt;?php print $varemail ?&gt;" /&gt;&lt;/td&gt; &lt;td id="emailast" class="ast"&gt;*&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;First Name: &lt;/td&gt;&lt;td&gt;&lt;input type="text" name="firstname" value="&lt;?php print $varfirstname ?&gt;" /&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Last Name: &lt;/td&gt;&lt;td&gt;&lt;input type="text" name="lastname" value="&lt;?php print $varlastname ?&gt;" /&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Gender: &lt;/td&gt;&lt;td&gt;&lt;select name="gender"&gt; &lt;option value=""&gt;Select&lt;/option&gt; &lt;option value="male"&gt;Male&lt;/option&gt; &lt;option value="female"&gt;Female&lt;/option&gt; &lt;option value="other"&gt;Other&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Birthdate: &lt;/td&gt; &lt;?php include 'birthdate.php'; ?&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;City: &lt;/td&gt;&lt;td&gt;&lt;input type="text" name="locationcity" value="&lt;?php print $varlocationcity ?&gt;" /&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;State/Province: &lt;/td&gt;&lt;td&gt;&lt;input type="text" name="locationstate" value="&lt;?php print $varlocationstate ?&gt;" /&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Country: &lt;/td&gt;&lt;td&gt;&lt;input type="text" name="locationcountry" value="&lt;?php print $varlocationcountry ?&gt;" /&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Upload an avatar: &lt;/td&gt;&lt;td&gt;&lt;input type="file" name="avatar" /&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;span style="font-size: .75em;"&gt;(Your image should be as close to a perfect square as possible and less than 2mb in size.&lt;br /&gt; Accepted file types are .jpg, .gif, and .png)&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;br /&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="submit" name="submit" value="Register"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;?php /*Connect to database*/ mysql_connect("server", "username", "password"); mysql_select_db("databaseName"); /*Leading and trailing whitespace is trimmed from username.*/ $varusername = trim($varusername); /*Query to check if username already exists in the database*/ $exists = mysql_query("SELECT * FROM users where user_name = '$varusername'"); /*Places the 'exists' query columns into an object variable named '$existsusername'*/ $existsusername = mysql_fetch_object($exists); /*Query to check if email already exists in the database*/ $exists2 = mysql_query("SELECT * FROM users where email = '$varemail'"); /*Places the 'exists2' query columns into an object variable named '$existsemail'*/ $existsemail = mysql_fetch_object($exists2); /*Checks if the submit button from the form above has been triggered*/ if(isset($_POST['submit'])) { /*Sets $fileext variable to the extension of selected file, then places the accepted extensions into an array. This is used in the next section to ensure the file is of the correct type and size.*/ if (($_FILES['avatar']['tmp_name'])) { $name = $_FILES["avatar"]["name"]; $srcExt = end(explode(".", $name)); $allowedexts = array("jpeg", "JPEG", "jpg", "JPG", "gif", "GIF", "png", "PNG"); $avatarok = true; } /*Sets the $error variable to the number of errors.*/ $error = $_FILES['avatar']['error']; /*Checks that user-entered data is valid. If not, an error is thrown and asterisk is shown.*/ /*Checks that user entered both username and password*/ if($varpassword == ''|| $varusername == '') { print "Error: Please input both a username and password.&lt;br /&gt;"; echo "&lt;script type='text/javascript'&gt;document.getElementById('usernameast').style.display = 'block' document.getElementById('passwordast').style.display = 'block'; document.getElementById('verpasswordast').style.display = 'block';&lt;/script&gt;"; /*Checks that username is not taken by comparing against '$ob'.*/ } elseif ($existsusername-&gt;user_name == $varusername){ print "Error: Sorry, that username is already taken. Please select a different one.&lt;br /&gt;"; echo "&lt;script type='text/javascript'&gt;document.getElementById('usernameast').style.display = 'block';&lt;/script&gt;"; /*Checks that passwords match.*/ } elseif ($varpassword != $varverpassword){ print "Error: Please ensure the passwords match.&lt;br /&gt;"; echo "&lt;script type='text/javascript'&gt;document.getElementById('verpasswordast').style.display = 'block';&lt;/script&gt;"; /*Checks that username contains only letters and numbers.*/ } elseif (!preg_match("/[a-z0-9_\.-]+$/i", $varusername)) { print "Error: Your username can contain only letters and numbers and must be less than 30 characters long.&lt;br /&gt;"; echo "&lt;script type='text/javascript'&gt;document.getElementById('usernameast').style.display = 'block';&lt;/script&gt;"; /*Checks that password is at least six characters long.*/ } elseif (strlen($varpassword) &lt; 6) { print "Error: Your password must be at least six characters long.&lt;br /&gt;"; echo "&lt;script type='text/javascript'&gt;document.getElementById('passwordast').style.display = 'block';&lt;/script&gt;"; /*Checks that email is valid.*/ } elseif (!preg_match("/^[a-z0-9_\.-]+@[a-z0-9_\.-]+\.[a-z0-9\.]{2,6}$/i", $varemail)) { print "Error: Please enter a valid email address.&lt;br /&gt;"; echo "&lt;script type='text/javascript'&gt;document.getElementById('emailast').style.display = 'block';&lt;/script&gt;"; /*Checks that email does not already exist in database*/ } elseif ($existsemail-&gt;email == $varemail){ print "Error: Sorry, that email address is already in use.&lt;br /&gt;"; echo "&lt;script type='text/javascript'&gt;document.getElementById('emailast').style.display = 'block';&lt;/script&gt;"; } elseif ($avatarok == true &amp; !in_array($srcExt, $allowedexts) || $error == 1) { print "Your avatar must be a .jpg, .gif, .png and must be smaller than 2mb."; $avatarok = false; /*If all fields are valid, the password is hashed...*/ } else { $hashpassword = sha1($varpassword); /*The Month, Date and year are placed into variables, concatonated, and placed into a single variable to write to the database...*/ $month = $varmonth; $date = $vardate; $year = $varyear; $birthdate = $year."-".$month."-".$date; /*Check if the user selected an avatar. If they did, the image is moved to the avatar folder. If not, the generic avatar is assigned.*/ if (($_FILES['avatar']['tmp_name'])) { $avatarFullPath = '&lt;img alt=Avatar src=images/avatars/' . $varusername . '_avatar /&gt;'; $avatarThumbPath = '&lt;img alt=Avatar src=images/avatars/' . $varusername . '_avatar width=45px height=45px /&gt;'; } else { $avatarFullPath = '&lt;img alt=Avatar src=images/avatars/generic.gif /&gt;'; $avatarThumbPath = '&lt;img alt=Avatar src=images/avatars/generic.gif width=45px height=45px /&gt;'; } if ($avatarok == true) { /*Get the extension of the uploaded file*/ $name = $_FILES["avatar"]["name"]; $ext = end(explode(".", $name)); /*Create full path from $varuserame*/ $oldImagePath = "images/avatars/" . $varusername . "_avatar." . $ext; /*Move uploaded file to avatars directory*/ move_uploaded_file($_FILES['avatar']['tmp_name'], $oldImagePath); /*Resize the image*/ /*Get uploaded image height and width*/ $srcSize = getimagesize($oldImagePath); /*Create source image based on file extension*/ switch ($ext) { case "jpeg": case "jpg": $srcImage = imagecreatefromjpeg($oldImagePath); break; case "gif": $srcImage = imagecreatefromgif($oldImagePath); break; case "png": $srcImage = imagecreatefrompng($oldImagePath); break; } /*Create new image*/ $destImage = imagecreatetruecolor(100, 100); /*Resample the image*/ imagecopyresampled($destImage, $srcImage, 0, 0, 0, 0, 100, 100, $srcSize[0], $srcSize[1]); /*Create new path with .jpg extension*/ $newImagePath = "images/avatars/" . $varusername . "_avatar.jpg"; /*Save resized image*/ imagejpeg($destImage, $newImagePath, 85); /*Remove images from memory*/ imagedestroy($srcImage); imagedestroy($destImage); /*Delete the original file from the server as long as it has a different name than the new one (since if it has the same name, the new one will have already overwritten it anyway and we don't want to delete the new file. This also prevents the new file from being deleted in the unlikely event that someone uploads an avatar in the exact "username_avatar.jpg" format.)*/ if ($oldImagePath != $newImagePath) { unlink($oldImagePath); } } /*...and the user is inserted into the users table.*/ mysql_query("insert into users (user_name, first_name, last_name, email, gender, birthdate, location_city, location_state, location_country, password, avatar_full, avatar_thumb) values ('$varusername', '$varfirstname', '$varlastname', '$varemail', '$vargender', '$birthdate', '$varlocationcity', '$varlocationstate', '$varlocationcountry', '$hashpassword', '$avatarFullPath', '$avatarThumbPath');"); /*Redirect to home page*/ print "&lt;script type='text/javascript'&gt;window.location = 'login.php'&lt;/script&gt;"; } } ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T20:57:48.890", "Id": "26383", "Score": "3", "body": "Try to separate your PHP and HTML code as much as possible. Also, move away from the old MySQL code (`mysql_query` etc) and towards using something like PDO. \n\n**ALSO** I notice that you have JS within PHP...no bueno. Again, separation, separation, separation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T21:04:45.687", "Id": "26384", "Score": "0", "body": "jsanc623, thanks for the quick feedback. Would you mind expanding a bit? By separation do you mean using includes to point to the HTML files? And could you give an example of how to separate my JS from my PHP? For instance, near the very end I have print \"<script type='text/javascript'>window.location = 'login.php'</script>\"; What would be a better way to implement this? Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T22:23:16.637", "Id": "26386", "Score": "2", "body": "Please read [Create your own framework... on top of the Symfony2 Components](http://fabien.potencier.org/article/50/create-your-own-framework-on-top-of-the-symfony2-components-part-1) to find out about some best practises and how can you separate HTML presentation from PHP and also keep JS separate. Also read [Separation of concerns article from Wikipedia](http://en.wikipedia.org/wiki/Separation_of_concerns)." } ]
[ { "body": "<p>Ok, this is your form.php code - what the users browse to. I've dropped in comments within the code - and also notice the addition of <code>require_once('pre_header.php')</code> on <code>line 4</code>. This will contain the PHP code at the bottom. </p>\n\n<pre><code>&lt;?php\n/*Give all POST variables the 'var' prefix*/\nimport_request_variables(\"p\", \"var\");\nrequire_once('pre_header.php');\n?&gt;\n\n&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"&gt;\n &lt;link rel=\"stylesheet\" type=\"text/css\" href=\"styles/styles.css\" /&gt;\n &lt;title&gt;Register&lt;/title&gt;\n &lt;/head&gt;\n\n &lt;body&gt;\n\n &lt;?php\n /* We can deduct that we're calling header, no need to tell us. REMOVE THIS COMMENT */\n include 'header.php';\n ?&gt;\n\n\n &lt;!-- This is an HTML comment, meaning users (and malicious users) can read them. If you need to \n put a comment about how the form works, hide it in a PHP comment. --&gt;\n\n &lt;!--Registration form. The 'name' attributes will have 'var' added to \n them to become variables. The 'value' attribute will be populated only if\n there is an error, so the user doesn't have to type everything in again.--&gt;\n &lt;form enctype=\"multipart/form-data\" method=\"post\"&gt;\n &lt;table id=\"regTable\"&gt;\n &lt;tr&gt;\n &lt;td&gt;*Desired Screen Name:&lt;/td&gt;\n &lt;td&gt;&lt;input type=\"text\" name=\"username\" value=\"&lt;?php print $varusername ?&gt;\" maxlength=\"30\" autofocus /&gt;&lt;/td&gt;\n &lt;td id=\"usernameast\" class=\"ast\"&gt;*&lt;/td&gt;\n &lt;/tr&gt; \n &lt;tr&gt;\n &lt;td&gt;*Password:&lt;/td&gt;\n &lt;td&gt;&lt;input type=\"password\" name=\"password\" value=\"&lt;?php print $varpassword ?&gt;\" /&gt;&lt;/td&gt;\n &lt;td id=\"passwordast\" class=\"ast\"&gt;*&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;*Verify Password: &lt;/td&gt;\n &lt;td&gt;&lt;input type=\"password\" name=\"verpassword\" value=\"&lt;?php print $varverpassword ?&gt;\" /&gt;&lt;/td&gt;\n &lt;td id=\"verpasswordast\" class=\"ast\"&gt;*&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;*Email address: &lt;/td&gt;&lt;td&gt;&lt;input type=\"text\" name=\"email\" value=\"&lt;?php print $varemail ?&gt;\" /&gt;&lt;/td&gt;\n &lt;td id=\"emailast\" class=\"ast\"&gt;*&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;First Name: &lt;/td&gt;\n &lt;td&gt;&lt;input type=\"text\" name=\"firstname\" value=\"&lt;?php print $varfirstname ?&gt;\" /&gt;&lt;/td&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;Last Name: &lt;/td&gt;\n &lt;td&gt;&lt;input type=\"text\" name=\"lastname\" value=\"&lt;?php print $varlastname ?&gt;\" /&gt;&lt;/td&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;Gender: &lt;/td&gt;\n &lt;td&gt;\n &lt;select name=\"gender\"&gt;\n &lt;option value=\"\"&gt;Select&lt;/option&gt;\n &lt;option value=\"male\"&gt;Male&lt;/option&gt;\n &lt;option value=\"female\"&gt;Female&lt;/option&gt;\n &lt;option value=\"other\"&gt;Other&lt;/option&gt;\n &lt;/select&gt;\n &lt;/td&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;Birthdate: &lt;/td&gt;\n &lt;?php include 'birthdate.php'; ?&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;City: &lt;/td&gt;\n &lt;td&gt;&lt;input type=\"text\" name=\"locationcity\" value=\"&lt;?php print $varlocationcity ?&gt;\" /&gt;&lt;/td&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;State/Province: &lt;/td&gt;\n &lt;td&gt;&lt;input type=\"text\" name=\"locationstate\" value=\"&lt;?php print $varlocationstate ?&gt;\" /&gt;&lt;/td&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;Country: &lt;/td&gt;\n &lt;td&gt;&lt;input type=\"text\" name=\"locationcountry\" value=\"&lt;?php print $varlocationcountry ?&gt;\" /&gt;&lt;/td&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;Upload an avatar: &lt;/td&gt;\n &lt;td&gt;&lt;input type=\"file\" name=\"avatar\" /&gt;&lt;/td&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;td&gt;\n &lt;span style=\"font-size: .75em;\"&gt;\n (Your image should be as close to a perfect square as possible and less than\n 2mb in size.&lt;br /&gt;\n Accepted file types are .jpg, .gif, and .png)\n &lt;/span&gt;\n &lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;br /&gt;&lt;/td&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;&lt;/td&gt;\n &lt;td&gt;&lt;input type=\"submit\" name=\"submit\" value=\"Register\"/&gt;&lt;/td&gt;\n &lt;/tr&gt;\n &lt;/table&gt;\n &lt;/form&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>This is the content of <code>pre_header.php</code> - the old PHP code that used to be at the bottom of the code. </p>\n\n<pre><code>&lt;?php\n\n/* Connect to database TODO: THIS IS BAD. USE PDO OR SOME OTHER ORM. */\nfunction connectToMySQL(){\n mysql_connect(\"server\", \"username\", \"password\");\n mysql_select_db(\"databaseName\");\n}\n\n/* Check if a user exists, PLEASE DO SOME CLEANUP. YOU'RE LETTING YOURSELF OPEN TO SQLINJECTION \n OR OTHER SQL VULNERABILITIES */\nfunction checkUserExists($varusername){\n /*Leading and trailing whitespace is trimmed from username.*/\n $varusername = trim($varusername);\n\n connectToMySQL();\n\n /*Query to check if username already exists in the database*/\n $exists = mysql_query(\"SELECT * FROM users where user_name = '$varusername'\");\n\n /*Places the 'exists' query columns into an object variable named '$existsusername'*/\n $existsusername = mysql_fetch_object($exists);\n\n /*Query to check if email already exists in the database*/\n $exists2 = mysql_query(\"SELECT * FROM users where email = '$varemail'\");\n\n /*Places the 'exists2' query columns into an object variable named '$existsemail'*/\n $existsemail = mysql_fetch_object($exists2);\n}\n\n\n\n\n/*Checks if the submit button from the form above has been triggered*/\nif(isset($_POST['submit'])) {\n /*Sets $fileext variable to the extension of selected file, then places the\n accepted extensions into an array. This is used in the next section to \n ensure the file is of the correct type and size.*/\n if (($_FILES['avatar']['tmp_name'])) {\n $name = $_FILES[\"avatar\"][\"name\"];\n $srcExt = end(explode(\".\", $name));\n $allowedexts = array(\"jpeg\", \"JPEG\", \"jpg\", \"JPG\", \"gif\", \"GIF\", \"png\", \"PNG\");\n $avatarok = true;\n }\n\n /*Sets the $error variable to the number of errors.*/\n $error = $_FILES['avatar']['error'];\n\n /*Checks that user-entered data is valid. If not, an error\n is thrown and asterisk is shown.*/\n if($varpassword == ''|| $varusername == '') {\n print \"Error: Please input both a username and password.&lt;br /&gt;\";\n echo \"&lt;script type='text/javascript'&gt;document.getElementById('usernameast').style.display = 'block'\n document.getElementById('passwordast').style.display = 'block';\n document.getElementById('verpasswordast').style.display = 'block';&lt;/script&gt;\";\n /*Checks that username is not taken by comparing against '$ob'.*/\n} elseif ($existsusername-&gt;user_name == $varusername){\n print \"Error: Sorry, that username is already taken. Please select a different one.&lt;br /&gt;\";\n echo \"&lt;script type='text/javascript'&gt;document.getElementById('usernameast').style.display = 'block';&lt;/script&gt;\";\n /*Checks that passwords match.*/\n } elseif ($varpassword != $varverpassword){\n print \"Error: Please ensure the passwords match.&lt;br /&gt;\";\n echo \"&lt;script type='text/javascript'&gt;document.getElementById('verpasswordast').style.display = 'block';&lt;/script&gt;\";\n /*Checks that username contains only letters and numbers.*/\n } elseif (!preg_match(\"/[a-z0-9_\\.-]+$/i\", $varusername)) {\n print \"Error: Your username can contain only letters and numbers and must be less than 30 characters long.&lt;br /&gt;\";\n echo \"&lt;script type='text/javascript'&gt;document.getElementById('usernameast').style.display = 'block';&lt;/script&gt;\";\n /*Checks that password is at least six characters long.*/\n } elseif (strlen($varpassword) &lt; 6) {\n print \"Error: Your password must be at least six characters long.&lt;br /&gt;\";\n echo \"&lt;script type='text/javascript'&gt;document.getElementById('passwordast').style.display = 'block';&lt;/script&gt;\";\n /*Checks that email is valid.*/\n } elseif (!preg_match(\"/^[a-z0-9_\\.-]+@[a-z0-9_\\.-]+\\.[a-z0-9\\.]{2,6}$/i\", $varemail)) {\n print \"Error: Please enter a valid email address.&lt;br /&gt;\";\n echo \"&lt;script type='text/javascript'&gt;document.getElementById('emailast').style.display = 'block';&lt;/script&gt;\";\n /*Checks that email does not already exist in database*/\n } elseif ($existsemail-&gt;email == $varemail){\n print \"Error: Sorry, that email address is already in use.&lt;br /&gt;\";\n echo \"&lt;script type='text/javascript'&gt;document.getElementById('emailast').style.display = 'block';&lt;/script&gt;\";\n } elseif ($avatarok == true &amp; !in_array($srcExt, $allowedexts) || $error == 1) {\n print \"Your avatar must be a .jpg, .gif, .png and must be smaller than 2mb.\";\n $avatarok = false;\n /*If all fields are valid, the password is hashed...*/\n } else { \n $hashpassword = sha1($varpassword);\n /*The Month, Date and year are placed into variables, concatonated,\n and placed into a single variable to write to the database...*/\n $month = $varmonth;\n $date = $vardate;\n $year = $varyear;\n $birthdate = $year.\"-\".$month.\"-\".$date;\n /*Check if the user selected an avatar. If they did, the image is moved to the avatar\n folder. If not, the generic avatar is assigned.*/ \n if (($_FILES['avatar']['tmp_name'])) {\n $avatarFullPath = '&lt;img alt=Avatar src=images/avatars/' . $varusername . '_avatar /&gt;';\n $avatarThumbPath = '&lt;img alt=Avatar src=images/avatars/' . $varusername . '_avatar width=45px height=45px /&gt;';\n } else {\n $avatarFullPath = '&lt;img alt=Avatar src=images/avatars/generic.gif /&gt;';\n $avatarThumbPath = '&lt;img alt=Avatar src=images/avatars/generic.gif width=45px height=45px /&gt;';\n }\n if ($avatarok == true) {\n /*Get the extension of the uploaded file*/\n $name = $_FILES[\"avatar\"][\"name\"];\n $ext = end(explode(\".\", $name));\n /*Create full path from $varuserame*/\n $oldImagePath = \"images/avatars/\" . $varusername . \"_avatar.\" . $ext;\n /*Move uploaded file to avatars directory*/\n move_uploaded_file($_FILES['avatar']['tmp_name'], $oldImagePath);\n /*Resize the image*/\n /*Get uploaded image height and width*/\n $srcSize = getimagesize($oldImagePath);\n /*Create source image based on file extension*/\n switch ($ext) {\n case \"jpeg\":\n case \"jpg\": $srcImage = imagecreatefromjpeg($oldImagePath); break;\n case \"gif\": $srcImage = imagecreatefromgif($oldImagePath); break;\n case \"png\": $srcImage = imagecreatefrompng($oldImagePath); break;\n }\n /*Create new image*/\n $destImage = imagecreatetruecolor(100, 100);\n /*Resample the image*/\n imagecopyresampled($destImage, $srcImage, 0, 0, 0, 0, 100, 100, $srcSize[0], $srcSize[1]);\n /*Create new path with .jpg extension*/\n $newImagePath = \"images/avatars/\" . $varusername . \"_avatar.jpg\";\n /*Save resized image*/\n imagejpeg($destImage, $newImagePath, 85);\n /*Remove images from memory*/\n imagedestroy($srcImage);\n imagedestroy($destImage);\n /*Delete the original file from the server as long as it has a \n different name than the new one (since if it has the same name, the\n new one will have already overwritten it anyway and we don't want\n to delete the new file. This also prevents the new file from being \n deleted in the unlikely event that someone uploads an avatar in \n the exact \"username_avatar.jpg\" format.)*/\n if ($oldImagePath != $newImagePath) {\n unlink($oldImagePath);\n }\n }\n /*...and the user is inserted into the users table.*/\n mysql_query(\"insert into users (user_name, first_name, last_name, email,\n gender, birthdate, location_city, location_state, location_country, password, avatar_full, avatar_thumb)\n values ('$varusername', '$varfirstname', '$varlastname', '$varemail',\n '$vargender', '$birthdate', '$varlocationcity', '$varlocationstate', \n '$varlocationcountry', '$hashpassword', '$avatarFullPath', '$avatarThumbPath');\");\n /*Redirect to home page*/\n print \"&lt;script type='text/javascript'&gt;window.location = 'login.php'&lt;/script&gt;\";\n }\n} \n?&gt;\n</code></pre>\n\n<p>I would really really recommend you go through and clean the code up - refactor refactor refactor, use best practices and as @peterhil said - read through the links and keep the HTML presentation away from PHP and JS and CSS. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T16:52:09.083", "Id": "16231", "ParentId": "16210", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T20:49:54.693", "Id": "16210", "Score": "5", "Tags": [ "php", "beginner", "mysql" ], "Title": "Registration form with validation and avatar-uploading" }
16210
<p>I made a simple library to help me doing A/B tests in a web app. The idea is simple: I have two or more page options (URL) for a given page and every call to the library method should give me a URL so at the end all options were given the same traffic.</p> <p>My questions are: </p> <ul> <li>Is this 100% thread safe? </li> <li>Is this performatic (I'm worried about the locks in a multithreaded (web) environment)? </li> <li>Did I use the best data structure for it?</li> <li>Can it be more readable?</li> </ul> <p>Here are the tests and the implementation:</p> <pre><code>[TestFixture] public class ABTestTest { [SetUp] public void Setup() { ABTest.ResetAll(); } [Test] public void GetUrlWithTwoCandidates() { ABTest.RegisterUrl("CarrinhoPagamento", "Url1.aspx"); ABTest.RegisterUrl("CarrinhoPagamento", "Url2.aspx"); ABTest.GetUrl("CarrinhoPagamento").Should().Be.EqualTo("Url1.aspx"); ABTest.GetUrl("CarrinhoPagamento").Should().Be.EqualTo("Url2.aspx"); ABTest.GetUrl("CarrinhoPagamento").Should().Be.EqualTo("Url1.aspx"); ABTest.GetUrl("CarrinhoPagamento").Should().Be.EqualTo("Url2.aspx"); ABTest.GetUrl("CarrinhoPagamento").Should().Be.EqualTo("Url1.aspx"); ABTest.GetUrl("CarrinhoPagamento").Should().Be.EqualTo("Url2.aspx"); ABTest.GetUrl("CarrinhoPagamento").Should().Be.EqualTo("Url1.aspx"); } [Test] public void GetUrlWithThreeCandidates() { var OptionsSelected = new Dictionary&lt;string, int&gt;(); OptionsSelected.Add("Url1.aspx", 0); OptionsSelected.Add("Url2.aspx", 0); OptionsSelected.Add("Url3.aspx", 0); ABTest.RegisterUrl("CarrinhoPagamento", "Url1.aspx"); ABTest.RegisterUrl("CarrinhoPagamento", "Url2.aspx"); ABTest.RegisterUrl("CarrinhoPagamento", "Url3.aspx"); var nextUrl = ""; for (int i = 1; i &lt; 10; i++) { nextUrl = ABTest.GetUrl("CarrinhoPagamento"); OptionsSelected[nextUrl]++; } OptionsSelected["Url1.aspx"].Should().Be.EqualTo(3); OptionsSelected["Url2.aspx"].Should().Be.EqualTo(3); OptionsSelected["Url3.aspx"].Should().Be.EqualTo(3); } [Test] public void GetUrlWithThreeCandidatesThreaded() { var OptionsSelected = new Dictionary&lt;string, int&gt;(); OptionsSelected.Add("Url1.aspx", 0); OptionsSelected.Add("Url2.aspx", 0); OptionsSelected.Add("Url3.aspx", 0); ABTest.RegisterUrl("CarrinhoPagamento", "Url1.aspx"); ABTest.RegisterUrl("CarrinhoPagamento", "Url2.aspx"); ABTest.RegisterUrl("CarrinhoPagamento", "Url3.aspx"); ThreadPool.SetMaxThreads(3, 3); for (int i = 1; i &lt; 10; i++) { ThreadPool.QueueUserWorkItem((object state) =&gt; { var nextUrl = ABTest.GetUrl("CarrinhoPagamento"); OptionsSelected[nextUrl]++; }); } while (OptionsSelected.Select(x =&gt; x.Value).Sum() != 9) { Thread.Sleep(100); } OptionsSelected["Url1.aspx"].Should().Be.EqualTo(3); OptionsSelected["Url2.aspx"].Should().Be.EqualTo(3); OptionsSelected["Url3.aspx"].Should().Be.EqualTo(3); } } public class ABTest { private volatile static Hashtable NextOption = new Hashtable(); private static Hashtable Options = new Hashtable(); public static void ResetAll() { lock (NextOption) { NextOption = new Hashtable(); } lock (Options) { Options = new Hashtable(); } } public static void RegisterUrl(string key, string url) { if (Options.ContainsKey(key.GetHashCode())) { lock (Options) { ((List&lt;ABTestOption&gt;)Options[key.GetHashCode()]).Add(new ABTestOption() { Url = url, Count = 0 }); } } else { if (!Options.ContainsKey(key.GetHashCode())) { lock (Options) { if (!Options.ContainsKey(key.GetHashCode())) { Options.Add( key.GetHashCode(), new List&lt;ABTestOption&gt;() { new ABTestOption() { Url = url, Count = 0 } }); } } } if (!NextOption.ContainsKey(key.GetHashCode())) { lock (NextOption) { if (!NextOption.ContainsKey(key.GetHashCode())) { NextOption.Add(key.GetHashCode(), url); } } } } } public static string GetUrl(string key) { lock (NextOption) { var nextUrl = (string)NextOption[key.GetHashCode()]; var keyOptions = (List&lt;ABTestOption&gt;)Options[key.GetHashCode()]; var selectedOption = keyOptions.Where(x =&gt; x.Url == nextUrl).First(); selectedOption.Count++; NextOption.Remove(key.GetHashCode()); NextOption.Add(key.GetHashCode(), keyOptions.OrderBy(x =&gt; x.Count).First().Url); return nextUrl; } } private class ABTestOption { public string Url { get; set; } public int Count { get; set; } } } </code></pre>
[]
[ { "body": "<p>This part is not thread safe:</p>\n\n<pre><code> lock (NextOption)\n {\n NextOption = new Hashtable();\n }\n</code></pre>\n\n<p>The problem is that the object being used to synchronize is re-assigned. That means a subsequent caller will acquire a different lock.</p>\n\n<p>It's conceivable that two writer threads hit <code>RegisterUrl</code> and each see a different lock, but end up adding concurrently to the same hash table, which is a harmful race condition. There are also more subtle problems if two threads are both calling <code>ResetAll</code> and a third thread is inserting.</p>\n\n<p>You should do something like this:</p>\n\n<pre><code>object NextOptionLock = new object();\nHashtable NextOption = new Hashtable();\n\nlock (NextOptionLock)\n{\n NextOption = new HashTable();\n}\n</code></pre>\n\n<p>I would do this for all other places where you use <code>lock(/* ... */)</code>. It's a good practice to keep the lock object separate from the data being protected.</p>\n\n<hr/>\n\n<p>This next part looked kind of suspicious to me because its thread safety depends on the implementation of <code>Hashtable</code>:</p>\n\n<pre><code> if (Options.ContainsKey(key.GetHashCode()))\n {\n lock (Options)\n {\n ((List)Options[key.GetHashCode()]).Add(new ABTestOption()\n</code></pre>\n\n<p>The question is whether or not it's safe to call <code>ContainsKey</code> while another thread does <code>Add</code>. According to <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.hashtable.aspx\" rel=\"nofollow\">Microsoft's documentation</a> it is safe:</p>\n\n<blockquote>Hashtable is thread safe for use by multiple reader threads and a single writing thread. It is thread safe for multi-thread use when only one of the threads perform write (update) operations, which allows for lock-free reads provided that the writers are serialized to the Hashtable. </blockquote>\n\n<p>So while it might be a red flag for someone auditing for concurrency problems, it seems OK.</p>\n\n<hr/>\n\n<p>Your use of <code>GetHashCode</code> looks a little weird. Don't MS's classes do this for you when you use an object as a hash table key?</p>\n\n<p>Also, why use a non-generic class like <code>Hashtable</code>? I see from MSDN that <code>Dictionary&lt;K,V&gt;</code> does not allow reads to be overlapped with a write in the same way that <code>Hashtable</code>'s documentation claims, so maybe that's the reason... Have you looked at <code>ConcurrentDictionary</code>?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T19:07:41.740", "Id": "26413", "Score": "0", "body": "I can see that you suggested the double check lock pattern (http://msdn.microsoft.com/en-us/library/ff650316.aspx) for the first part of your review. I guess you are right. I'm going to change that. As for the use o GetHashCode I already removed it based on a friend´s review. Will look into the ConcurrentDictionary. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T19:39:24.477", "Id": "26416", "Score": "0", "body": "@tucaz - Actually this is not the double-check lock pattern. (And the double-check lock pattern is broken on some CPU architectures - though probably not those that .NET supports.) I am suggesting you keep the locks and data separate, so that if you re-initialize the data, your code is still using the same lock..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T18:47:45.080", "Id": "16238", "ParentId": "16211", "Score": "2" } }, { "body": "<p>Here's a possible way which is hopefully easy to read.</p>\n\n<p>I'm sure someone smarter than me can (and will) point out any potential issues with this suggestion.</p>\n\n<p>The <code>options</code> field is never null and the set operation of the field is atomic so I don't think you need a lock around that.</p>\n\n<pre><code>public static class ABTest\n{\n private static IDictionary&lt;string, ABTestOption&gt; options = new Dictionary&lt;string, ABTestOption&gt;();\n private readonly static object locker = new object();\n\n public static string GetUrl(string key)\n {\n ABTestOption option;\n\n lock (locker)\n {\n if (!options.TryGetValue(key, out option))\n {\n return null;\n }\n }\n\n return option.GetNextUrl();\n }\n\n public static void RegisterUrl(string key, string url)\n {\n ABTestOption option;\n\n lock (locker)\n {\n if (!options.TryGetValue(key, out option))\n {\n option = new ABTestOption();\n options[key] = option;\n }\n }\n\n option.AddUrl(url);\n }\n\n public static void ResetAll()\n {\n options = new Dictionary&lt;string, ABTestOption&gt;();\n }\n\n private class ABTestOption\n {\n private readonly object locker = new object();\n private readonly List&lt;string&gt; urls = new List&lt;string&gt;();\n private int totalCallCount = -1;\n\n public void AddUrl(string url)\n {\n lock (this.locker)\n {\n if (!this.urls.Contains(url))\n {\n this.urls.Add(url);\n }\n }\n }\n\n internal string GetNextUrl()\n {\n lock (this.locker)\n {\n int urlCount = this.urls.Count;\n int position = Interlocked.Increment(ref this.totalCallCount) % urlCount;\n\n return this.urls[position];\n }\n }\n }\n}\n</code></pre>\n\n<p>I couldn't get your threadpool test to build as your <code>for</code> statements are incomplete and I wasn't sure how they should be completed so I used these two tests instead:</p>\n\n<pre><code>[TestFixture]\npublic class ABTestTest\n{\n [Test]\n public void GetUrlWithTwoCandidates()\n {\n ABTest.RegisterUrl(\"CarrinhoPagamento\", \"Url1.aspx\");\n ABTest.RegisterUrl(\"CarrinhoPagamento\", \"Url2.aspx\");\n\n Assert.AreEqual(\"Url1.aspx\", ABTest.GetUrl(\"CarrinhoPagamento\"));\n Assert.AreEqual(\"Url2.aspx\", ABTest.GetUrl(\"CarrinhoPagamento\"));\n Assert.AreEqual(\"Url1.aspx\", ABTest.GetUrl(\"CarrinhoPagamento\"));\n Assert.AreEqual(\"Url2.aspx\", ABTest.GetUrl(\"CarrinhoPagamento\"));\n }\n\n [Test]\n public void GetUrlWithThreeCandidates()\n {\n ABTest.RegisterUrl(\"CarrinhoPagamento\", \"Url1.aspx\");\n ABTest.RegisterUrl(\"CarrinhoPagamento\", \"Url2.aspx\");\n ABTest.RegisterUrl(\"CarrinhoPagamento\", \"Url3.aspx\");\n\n Assert.AreEqual(\"Url1.aspx\", ABTest.GetUrl(\"CarrinhoPagamento\"));\n Assert.AreEqual(\"Url2.aspx\", ABTest.GetUrl(\"CarrinhoPagamento\"));\n Assert.AreEqual(\"Url3.aspx\", ABTest.GetUrl(\"CarrinhoPagamento\"));\n Assert.AreEqual(\"Url1.aspx\", ABTest.GetUrl(\"CarrinhoPagamento\"));\n Assert.AreEqual(\"Url2.aspx\", ABTest.GetUrl(\"CarrinhoPagamento\"));\n Assert.AreEqual(\"Url3.aspx\", ABTest.GetUrl(\"CarrinhoPagamento\"));\n }\n\n [SetUp]\n public void Setup()\n {\n ABTest.ResetAll();\n }\n}\n</code></pre>\n\n<p>EDIT: Updated following feedback.</p>\n\n<p>The lock is simple and quite fast, you could get more throughput by using a <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx\" rel=\"nofollow\">ReaderWriterLockSlim</a> but that is more complicated and unless you can prove that the lock causes significant blocking I would leave it at that initially.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T19:13:34.153", "Id": "26415", "Score": "0", "body": "I fixed the third test now. Sorry for that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:52:55.967", "Id": "26423", "Score": "0", "body": "The concurrency section of the MSDN doc for `Dictionary<K,V>` says that reads can be concurrent but cannot be overlapped with a write: \"A `Dictionary<TKey, TValue>` can support multiple readers concurrently, as long as the collection is not modified.\" http://msdn.microsoft.com/en-us/library/xfhwa508.aspx" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T11:51:09.220", "Id": "26439", "Score": "0", "body": "@asveikau - good point, the original idea would work for multiple readers (with no writers) or a multiple writers (with no readers) but not a mixture. I'll update it to add locks around the reads too." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T18:54:56.463", "Id": "16239", "ParentId": "16211", "Score": "0" } } ]
{ "AcceptedAnswerId": "16238", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T21:08:31.997", "Id": "16211", "Score": "5", "Tags": [ "c#", "multithreading", "thread-safety" ], "Title": "Library for doing A/B tests in a web app" }
16211
<p>This is an ordinary data processing task: read a list of dates and amounts (for example, deposits and withdrawals from a bank account) and report the date on which the lowest balance was recorded and what that balance was. While I do get the correct answer--always a virtue--with the code below, I can't help thinking that it could be done better (e.g. more concisely). I've included the preliminary input parsing code so that the whole thing can be compiled and run as is.</p> <pre><code>module Main where import Text.ParserCombinators.Parsec import Data.Time import Numeric import Control.Applicative ((&lt;$&gt;), (&lt;*&gt;), (*&gt;)) import Control.Monad.State as CM --The purpose is to sum up a list of dated values (example: transactions in a bank --account) and produce the date and amount of the lowest recorded balance. --For the three lines below, the output would be: -- DtdBal {runningBal = 4859.96, lowDt = 2013-01-23, lowBal = 4859.96} --12/1/12, 6844.79 --1/1/13, 992.41 --1/23/13, -2977.24 data DtdVal = DtdVal { dt :: Day , amt :: Double } deriving Show data DtdBal = DtdBal { runningBal :: Double , lowDt :: Day , lowBal :: Double } deriving Show main = do res &lt;- parseFromFile sched "escrow.txt" case res of Right l -&gt; putStrLn . show $ process l Left _ -&gt; error "Oops" where process (x:xs) = execState (minBal xs) (initState x) initState x = DtdBal { runningBal = amt x, lowDt = dt x, lowBal = amt x } minBal :: [DtdVal] -&gt; CM.State DtdBal () minBal [] = return () minBal (x:xs) = do rBal &lt;- runningBal &lt;$&gt; get lBal &lt;- lowBal &lt;$&gt; get lDt &lt;- lowDt &lt;$&gt; get if amt x + rBal &lt; lBal then put $ DtdBal { runningBal = rBal + amt x, lowDt = dt x, lowBal = amt x + rBal} else put $ DtdBal { runningBal = rBal + amt x, lowDt = lDt, lowBal = lBal } minBal xs sched :: CharParser () [DtdVal] sched = line `endBy` newline line :: CharParser () DtdVal line = DtdVal &lt;$&gt; dts &lt;*&gt; (char ',' &gt;&gt; spaces *&gt; readSgnd) dts :: CharParser () Day dts = toDay &lt;$&gt; many digit `sepBy` char '/' where toDay [x, y, z] = fromGregorian (2000 + read z) (read x) (read y) readSgnd :: CharParser () Double readSgnd = do optional (char '+') inp &lt;- getInput let [(num, inp')] = readSigned readFloat inp setInput inp' return num </code></pre>
[]
[ { "body": "<ul>\n<li>recursive part of <code>minBal</code> is <code>mapM_</code></li>\n<li>multiple <code>get</code> is better to refactor into one</li>\n<li><code>get</code> - process - <code>put</code> part of <code>minBal</code> is <code>modify</code></li>\n<li>state monad is not necessary - you can use plain <code>foldr</code> instead of <code>mapM_</code> and <code>modify</code></li>\n<li><code>runningBal</code> is better to implement using <code>scanr</code>. Then <code>zip</code> running balances and source list and <code>foldr</code> the resulting list of tuples</li>\n<li>use <code>minimum</code> to find the minimum</li>\n</ul>\n\n<p>Here is a more idiomatic approach to minBal:</p>\n\n<pre><code>runningBal' = scanl1 (+) . map amt\n\nrb l = zip (runningBal' l) l\n\nmb l = minimumBy (compare `on` fst) l\n\nminDay = mb . rb\n\nminBal' l = DtdBal { \n runningBal = fst $ last runningBals, \n lowDt = dt $ snd md, \n lowBal = fst md } \n where\n runningBals = rb l\n md = minDay l\n</code></pre>\n\n<p>You can inline all the small functions for the final code but that's the order I created them in. Note that <code>rb</code> is calculated twice, but I was not sure if you really need the final balance. In your algorithm it was a byproduct.</p>\n\n<p><code>main</code> can be rewritten too:</p>\n\n<pre><code>main' = (parseFromFile sched &gt;=&gt; process &gt;=&gt; print) \"escrow.txt\" where\n process (Right l) = return $ minBal' l\n process (Left _) = error \"Oops\"\n</code></pre>\n\n<p>Basically, <code>putStrLn . show</code> is <code>print</code> and composition is your friend. <code>&gt;=&gt;</code> is monadic variant of <code>.</code>. It's advantage over <code>&gt;&gt;=</code> is associativity - it lets you refactor your code more easily.</p>\n\n<p>Here is a shorter version of <code>minBal'</code> which also saves a few calculations, but <code>last</code> is still <code>O(N)</code>:</p>\n\n<pre><code>minBal' l = DtdBal { \n runningBal = last runningBals, \n lowDt = dt $ snd md, \n lowBal = fst md } \n where\n md = minimumBy (compare `on` fst) $ zip runningBals l\n runningBals = scanl1 (+) $ map amt l\n</code></pre>\n\n<p>Let me know how this works for very large files.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T11:47:54.207", "Id": "16223", "ParentId": "16212", "Score": "2" } }, { "body": "<ul>\n<li>There is no need to use a state monad for the <code>minBal</code>, a simple\n<code>foldl</code> suffices.</li>\n<li><p>One nice thing about using a parser library is that it will automatically\ngenerate some helpful error messages, but the way it is used in <code>dts</code> will only give a pattern match failure if something is wrong. Similarly a less helpful error message will be generated from a parse failure using <code>readSigned</code>.</p></li>\n<li><p>It is not uncommon to simply name the parser from the thing that is being parsed, similar to BNF grammars. </p></li>\n</ul>\n\n<pre class=\"lang-hs prettyprint-override\"><code>data Transaction = Transaction \n { time :: Day\n , amount :: Double \n } deriving Show\n\ndata DtdBal = DtdBal\n { runningBal :: Double\n , lowDt :: Day\n , lowBal :: Double\n } deriving Show\n\nmain = do \n result &lt;- parseFromFile transactions \"escrow.txt\"\n case result of \n Right ls -&gt; print . minBal $ ls\n Left e -&gt; print e\n\nminBal (l:ls) = foldl go start ls\n where\n start = DtdBal{runningBal = amount l,lowDt = time l,lowBal = amount l}\n go a b\n | newBal &lt; lowBal a = a{runningBal = newBal,lowBal = newBal,lowDt = time b}\n | otherwise = a{runningBal = newBal}\n where newBal = amount b + runningBal a\n\ntransactions :: CharParser () [Transaction] \ntransactions = transaction `endBy` newline\n\ntransaction :: CharParser () Transaction\ntransaction = Transaction &lt;$&gt; date &lt;*&gt; (char ',' &gt;&gt; spaces *&gt; float)\n\ndate :: CharParser () Day\ndate = do \n x &lt;- int\n char '/'\n y &lt;- int\n char '/'\n z &lt;- int\n return (fromGregorian (2000 + z) x y)\n\nint :: (Integral a) =&gt; CharParser () a\nint = (fromInteger . read) &lt;$&gt; many digit\n\nfloat :: CharParser () Double\nfloat =\n (char '-' &gt;&gt; negate &lt;$&gt; posFloat) &lt;|&gt;\n (optional (char '+') &gt;&gt; posFloat)\n where\n posFloat = do\n x &lt;- many digit\n char '.'\n y &lt;- many digit\n return (read (x ++ ('.':y)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T20:08:08.927", "Id": "16241", "ParentId": "16212", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T21:58:21.837", "Id": "16212", "Score": "4", "Tags": [ "haskell", "homework" ], "Title": "Ordinary Data Processing Task in Haskell: Vague Misgivings" }
16212
<p>Is there any problem in checking PHP PDO connection this manner?</p> <p>Is this way reliable?</p> <pre><code>function pdo_mysql() { $mysql_string = "xxxxxxxxxxx"; $mysql_user = "xxxxxxxxxxx"; $mysql_pass = "xxxxxxxxxxx"; try { $pdo_mysql = new PDO( $mysql_string, $mysql_user, $mysql_pass ); $pdo_mysql-&gt;setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $pdo_mysql-&gt;setAttribute( PDO::ATTR_EMULATE_PREPARES, false ); return true; } catch( PDOException $ex ) { log_action( "pdo_mysql", $ex-&gt;getCode() . ": " . $ex-&gt;getMessage() ); return false; } return false; } </code></pre> <p>and then checking the return like this:</p> <pre><code>if( $pdo_mysql = pdo_mysql() ) </code></pre>
[]
[ { "body": "<p>I'm not quite sure I see the purpose of this function.</p>\n\n<p>It essentially checks if a PDO connection is possible. It does not actually return a connection. In addition to that, it has hard coded credentials, thus killing all flexibility. Also, there's no evident reason why you made it MySQL specific. None of your options used are MySQL specific.</p>\n\n<p>Since a boolean is returned, <code>if( $pdo_mysql = pdo_mysql() )</code> is redundant too:</p>\n\n<p><code>if (pdo_mysql())</code> is sufficient (unless you plan on using the true/false $pdo_mysql outside of the <code>if/else</code> block).</p>\n\n<p>You should pass the credentials into the function instead of hard coding them. Once you've done that though, you've kind of removed any need for the function.</p>\n\n<p>Personally, I don't see a purpose for this function. Just make the connection without this function. If you want to keep it in some kind of centralized place, just keep in it a simple bootstrap file, or even a simple bootstrapping class. </p>\n\n<hr>\n\n<p>I've been vague on basically everything in this post, so if you want more detail, let me know :).</p>\n\n<hr>\n\n<p>Also, I might have missed the point of your function. Is your end goal to connect to a MySQL server, or to check if you <em>could</em> connect to a MySQL server?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T21:17:38.673", "Id": "26421", "Score": "0", "body": "thank you. I do see what you mean, and agree. Would be better to return the actual connection. But I have been researching all day and have since found, what I believe is, a better way." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T00:14:12.267", "Id": "16215", "ParentId": "16213", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T23:53:26.110", "Id": "16213", "Score": "5", "Tags": [ "php", "mysql", "pdo" ], "Title": "Is there any problem in checking PHP PDO connection this manner?" }
16213
<pre><code>var EVENT_TYPE = "touchstart" // Global Event Type var H = 360, S = 1.0, V = 1.0 var randomColorsList = [], staticColorsList = [ [r = 255, g = 56, b = 30], [r = 22, g = 20, b = 32], [r = 24, g = 244, b = 223], [r = 188, g = 222, b = 32], [r = 122, g = 211, b = 36], [r = 199, g = 22, b = 33], [r = 12, g = 11, b = 56], [r = 133, g = 22, b = 31], [r = 122, g = 2, b = 3], [r = 133, g = 222, b = 44], [r = 122, g = 211, b = 24], [r = 133, g = 222, b = 11], [r = 141, g = 255, b = 3], [r = 156, g = 25, b = 3], [r = 112, g = 25, b = 3], [r = 112, g = 25, b = 3], ]; INIT_RANDOM_COLORS = 0, MAX_RANDOM_COLORS = 15, INIT_STATIC_COLORS = 0, MAX_STATIC_COLORS = 15 var colorListener = function( event ){ var r = this.r, g = this.g, b = this.b alert("R: " + r + " G: " + g + " B: " + b); } var randomColorButtonListener = function( event ){ for(i = INIT_RANDOM_COLORS; i &lt;= MAX_RANDOM_COLORS ; i++ ){ var color = hsvToRgb(Math.random()*H, S, V); //Renders high intesity colors var r = Math.round(color[0]); var g = Math.round(color[1]); var b = Math.round(color[2]); randomColorsList[i].style.background = "rgb("+ r + "," + b + "," + g +")"; randomColorsList[i].r = r; randomColorsList[i].g = g; randomColorsList[i].b = b; } } var optionsButtonsListener = function( event ){ var optionID = this.buttonID; swtich( optionID ){ case button1: alert("Options Button 1"); return; case button2: alert("Options Button 2"); return; case button3: alert("Options Button 3"); return; case button4: alert("Options Button 4"); return; case default: alert("This is not an option"); return } } function simpleDashInit(){ //simpleDashboardWrapper Div var simpleDashID = "simpleDash", simpleDashWrapperWidth = 600, simpleDashWrapperHeight = 712, simpleDashWrapperPosition = "absolute", simpleDashWrapperTop = 480, simpleDashWrapperBG = "url('simpleDashBG.png')", simpleDashWrapperBGRepeat = "no-repeat" //randomColorWrapper Div var randomColorWrapperID = "randomColorWrapper", randomColorWrapperWidth = 580, randomColorWrapperTop = 75, randomColorWrapperLeft = 5, randomColorWrapperPosition = "absolute", randomColorWrapperBorder = "1px solid #712f04", randomColorWrapperBackground = "#ffedcc", randomColorWrapperCorner = 15, randomColorWrapperMargin = "0px 0px 0px 8px", randomColorWrapperPadding = "0px 0px 5px 0px" //randomColor Div var randomColorID = "randomColor", randomColorsHeight = 55, randomColorsWidth = 55, randomColorCorner = 15, randomColorsBorder = "5px solid #712f04", randomColorsMargin = "5px 0px 0px 6px", randomColorsFloat = "left", randomColorsCorner = 15, randomColorsBackground = "#ffedcc" //Random Colors Button var newRandomColorsID = "newRandomColorButton", newRandomColorWidth = 580, newRandomColorHeight = 50, newRandomColorsCorner = 15, newRandomColorsTop = 10, newRandomColorsLeft = 5, newRandomColorFontSize = 14, newRandomColorFontType = "comic-sans", newRandomColorsPosition = "absolute", newRandomColorBorder = "5px solid #712f04", newRandomColorBG = "#ffedcc" //Random Color Button Text var newRandomColorButtonTextID = "newRandomColorText", newRandomColorButtonTextInnerHTML = "Touch For New Colors", newRandomColorButtomTextFontSize = 30, newRandomColorButtonTextFontFamily = "Arial", newRandomColorButtonTextFontWeight = "bold", newRandomColorButtonTextPosition = "absolute", newRandomColorButtonTextColor = "#712f04", newRandomColorButtonTextLeft = 120, newRandomColorButtonTextTop = 10 //Static Colors Wrapper var staticColorsWrapperID = "staticColorsWrapper", staticColorsWrapperWidth = 580, staticColorsWrapperTop = 229, staticColorsWrapperPosition = "absolute", staticColorsWrapperBorder = "1px solid black", staticColorsWrapperBackground = "#ffedcc", staticColorsWrapperCorner = 15, staticColorsWrapperMargin = "0px 0px 0px 8px", staticColorsWrapperPadding = "0px 0px 5px 0px" //Static Colors var staticColorID = "staticColor", staticColorWidth = 55, staticColorHeight = 55, staticColorCorner = 15, staticColorBorder = "5px solid #712f04", staticColorMargin = "5px 0px 0px 6px", staticColorFloat = "left" //Options Menu Wrapper var optionsMenuWrapperID = "optionsMenuWrapper", optionsMenuWrapperWidth = 580, optionsMenuWrapperTop = 383, optionsMenuWrapperPosition = "absolute", optionsMenuWrapperBorder = "0px solid black", optionsMenuWrapperMargin = "0px 0px 0px 14px", optionsMenuWrapperPadding = "0px 0px 0px 0px" //Options Buttons Properties var optionsButtonID = "optionsButton", optionsButtonWidth = 132, optionsButtonHeight = 150, optionsButtonFloat = "left" optionsButtonBorder = "1px solid black", optionsButtonBackground = "#ffedcc", optionsButtonCorner = 15, optionsButtonMargin = "0px 11px 0px 0px", optionsButtonPadding = "5px 0px 0px 0px" //Button Backgounds var optionButtonOneBG = "url(homeIcon.png) 3px 9px no-repeat #ffedcc", optionButtonTwoBG = "url(pagesIcon.png) 3px 9px no-repeat #ffedcc", optionButtonThreeBG = "url(saveIcon.png) 3px 9px no-repeat #ffedcc", optionButtonFourBG = "url(eraseIcon.png) 3px 9px no-repeat #ffedcc" var simpleDashboardWrapper = document.createElement("div"); simpleDashboardWrapper.setAttribute("id", simpleDashID); simpleDashboardWrapper.style.width = simpleDashWrapperWidth; simpleDashboardWrapper.style.height = simpleDashWrapperHeight; simpleDashboardWrapper.style.position = simpleDashWrapperPosition; simpleDashboardWrapper.style.top = simpleDashWrapperTop; simpleDashboardWrapper.style.background = simpleDashWrapperBG; simpleDashboardWrapper.style.backgroundRepeat = simpleDashWrapperBGRepeat; document.body.appendChild(simpleDashboardWrapper); var randomColorPalleteWrapper = document.createElement("div"); randomColorPalleteWrapper.setAttribute("id", randomColorWrapperID); randomColorPalleteWrapper.style.width = randomColorWrapperWidth; randomColorPalleteWrapper.style.position = randomColorWrapperPosition; randomColorPalleteWrapper.style.top = randomColorWrapperTop; randomColorPalleteWrapper.style.border = randomColorWrapperBorder; randomColorPalleteWrapper.style.background = randomColorWrapperBackground; randomColorPalleteWrapper.style.borderRadius = randomColorWrapperCorner; randomColorPalleteWrapper.style.margin = randomColorWrapperMargin; randomColorPalleteWrapper.style.padding = randomColorWrapperPadding; simpleDashboardWrapper.appendChild(randomColorPalleteWrapper); for(i = INIT_RANDOM_COLORS; i &lt;= MAX_RANDOM_COLORS; i++){ var color = hsvToRgb(Math.random()*H, S, V); //Pruduces high intesity colors var r = Math.round(color[0]); var g = Math.round(color[1]); var b = Math.round(color[2]); var randomColor = document.createElement("div"); randomColor.setAttribute("id", randomColorID); randomColor.style.width = randomColorsWidth; randomColor.style.height = randomColorsHeight; randomColor.style.margin = randomColorsMargin; randomColor.style.border = randomColorsBorder; randomColor.style.float = randomColorsFloat; randomColor.style.borderRadius = randomColorCorner; randomColor.r = r; randomColor.b = b; randomColor.g = g; randomColor.style.background = "rgb("+ r + "," + b + "," + g +")"; randomColorsList[i] = randomColor; randomColor.addEventListener(EVENT_TYPE, colorListener); randomColorPalleteWrapper.appendChild(randomColor); } var newRandomColorsButton = document.createElement("div"); newRandomColorsButton.setAttribute("id", newRandomColorsID); newRandomColorsButton.style.width = newRandomColorWidth; newRandomColorsButton.style.height = newRandomColorHeight; newRandomColorsButton.style.borderRadius = newRandomColorsCorner; newRandomColorsButton.style.fontSize = newRandomColorFontSize; newRandomColorsButton.style.fontFamily = newRandomColorFontType; newRandomColorsButton.style.position = newRandomColorsPosition; newRandomColorsButton.style.top = newRandomColorsTop; newRandomColorsButton.style.left = newRandomColorsLeft; newRandomColorsButton.style.border = newRandomColorBorder; newRandomColorsButton.style.background = newRandomColorBG; newRandomColorsButton.addEventListener(EVENT_TYPE, randomColorButtonListener); simpleDashboardWrapper.appendChild(newRandomColorsButton); var newRandomColorButtonText = document.createElement("div"); newRandomColorButtonText.setAttribute("id", newRandomColorButtonTextID); newRandomColorButtonText.style.fontSize = newRandomColorButtomTextFontSize; newRandomColorButtonText.style.fontFamily = newRandomColorButtonTextFontFamily; newRandomColorButtonText.style.fontWeight = newRandomColorButtonTextFontWeight; newRandomColorButtonText.style.color = newRandomColorButtonTextColor; newRandomColorButtonText.style.position = newRandomColorButtonTextPosition; newRandomColorButtonText.style.left = newRandomColorButtonTextLeft; newRandomColorButtonText.style.top = newRandomColorButtonTextTop; newRandomColorButtonText.innerHTML = newRandomColorButtonTextInnerHTML; newRandomColorsButton.appendChild(newRandomColorButtonText); // STATIC COLORS WRAPPER var staticColorsWrapper = document.createElement("div"); staticColorsWrapper.setAttribute("id", staticColorsWrapperID); staticColorsWrapper.style.width = staticColorsWrapperWidth; staticColorsWrapper.style.position = staticColorsWrapperPosition; staticColorsWrapper.style.top = staticColorsWrapperTop; staticColorsWrapper.style.border = staticColorsWrapperBorder; staticColorsWrapper.style.background = staticColorsWrapperBackground; staticColorsWrapper.style.borderRadius = staticColorsWrapperCorner; staticColorsWrapper.style.margin = staticColorsWrapperMargin; staticColorsWrapper.style.padding = staticColorsWrapperPadding; simpleDashboardWrapper.appendChild(staticColorsWrapper); for(i = INIT_STATIC_COLORS; i &lt;= MAX_STATIC_COLORS; i++){ var staticColor = document.createElement("div"); staticColor.setAttribute("id", staticColorID) staticColor.style.width = staticColorWidth; staticColor.style.height = staticColorHeight; staticColor.style.margin = staticColorMargin; staticColor.style.border = staticColorBorder; staticColor.style.float = staticColorFloat; staticColor.style.borderRadius = staticColorCorner; staticColor.style.background = "rgb("+ staticColorsList[i][0] + "," + staticColorsList[i][1] + "," + staticColorsList[i][2] +")"; staticColor.r = staticColorsList[i][0]; // 0 = r staticColor.g = staticColorsList[i][1]; // 1 = g staticColor.b = staticColorsList[i][2]; // 2 = b staticColor.addEventListener(EVENT_TYPE, colorListener); staticColorsWrapper.appendChild(staticColor); } // OPTION BUTTONS WRAPPER optionsButtonWrapper = document.createElement("div"); optionsButtonWrapper.setAttribute("id", optionsMenuWrapperID); optionsButtonWrapper.style.width = optionsMenuWrapperWidth; optionsButtonWrapper.style.top = optionsMenuWrapperTop; optionsButtonWrapper.style.position = optionsMenuWrapperPosition; optionsButtonWrapper.style.border = optionsMenuWrapperBorder; optionsButtonWrapper.style.margin = optionsMenuWrapperMargin; optionsButtonWrapper.style.padding = optionsMenuWrapperPadding; simpleDashboardWrapper.appendChild(optionsButtonWrapper); //Option Button 1 optionButtonOne = document.createElement("div"); optionButtonOne.setAttribute("id", optionsButtonID); optionButtonOne.style.width = optionsButtonWidth; optionButtonOne.style.height = optionsButtonHeight; optionButtonOne.style.float = optionsButtonFloat; optionButtonOne.style.border = optionsButtonBorder; optionButtonOne.style.background = optionButtonOneBG; optionButtonOne.style.borderRadius = optionsButtonCorner; optionButtonOne.style.margin = optionsButtonMargin; optionButtonOne.style.padding = optionsButtonPadding; optionsButtonWrapper.appendChild(optionButtonOne); //Option Button 2 optionButtonTwo = document.createElement("div"); optionButtonTwo.setAttribute("id", optionsButtonID); optionButtonTwo.style.width = optionsButtonWidth; optionButtonTwo.style.height = optionsButtonHeight; optionButtonTwo.style.float = optionsButtonFloat; optionButtonTwo.style.border = optionsButtonBorder; optionButtonTwo.style.background = optionButtonTwoBG; optionButtonTwo.style.borderRadius = optionsButtonCorner; optionButtonTwo.style.margin = optionsButtonMargin; optionButtonTwo.style.padding = optionsButtonPadding; optionsButtonWrapper.appendChild(optionButtonTwo); //Option Button 3 optionButtonThree = document.createElement("div"); optionButtonThree.setAttribute("id", optionsButtonID); optionButtonThree.style.width = optionsButtonWidth; optionButtonThree.style.height = optionsButtonHeight; optionButtonThree.style.float = optionsButtonFloat; optionButtonThree.style.border = optionsButtonBorder; optionButtonThree.style.background = optionButtonThreeBG; optionButtonThree.style.borderRadius = optionsButtonCorner; optionButtonThree.style.margin = optionsButtonMargin; optionButtonThree.style.padding = optionsButtonPadding; optionsButtonWrapper.appendChild(optionButtonThree); //Option Button 4 optionButtonFour = document.createElement("div"); optionButtonFour.setAttribute("id", optionsButtonID); optionButtonFour.style.width = optionsButtonWidth; optionButtonFour.style.height = optionsButtonHeight; optionButtonFour.style.float = optionsButtonFloat; optionButtonFour.style.border = optionsButtonBorder; optionButtonFour.style.background = optionButtonFourBG; optionButtonFour.style.borderRadius = optionsButtonCorner; optionButtonFour.style.margin = optionsButtonMargin; optionButtonFour.style.padding = optionsButtonPadding; optionsButtonWrapper.appendChild(optionButtonFour); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T04:27:27.723", "Id": "26389", "Score": "3", "body": "Care to tell us what the code does? And, perhaps focus your question on one particular piece of code rather than several pages of code?" } ]
[ { "body": "<p>You are using a variable named <code>i</code>, but I don't see it being declared(<code>var i</code>). This might cause problems. Same with your RANDOM/STATIC color constants:</p>\n\n<pre><code>var INIT_RANDOM_COLORS = 0,\nMAX_RANDOM_COLORS = 15,\nINIT_STATIC_COLORS = 0,\nMAX_STATIC_COLORS = 15;\n</code></pre>\n\n<p>You seem to have a <em>lot</em> of duplicated code (particularly when you set the style). Don't Repeat Yourself. Instead, have those common commands go in a function.</p>\n\n<p>Alternatively, in <code>optionButtonN</code>, you might have more readable code by instead using <code>optionButtons[N]</code> and setting the styles in a for loop.</p>\n\n<pre><code>var optionButtonBackgrounds = [optionButtonOneBG, optionButtonTwoBG,\n optionButtonThreeBG, optionButtonFourBG];\n\nvar optionButtons = [];\n\nfor (var buttonNumber = 0; buttonNumber &lt; 4; ++buttonNumber) {\n var optionButton = document.createElement(\"div\");\n optionButton.setAttribute(\"id\", optionsButtonID);\n optionButton.style.width = optionsButtonWidth;\n optionButton.style.height = optionsButtonHeight;\n optionButton.style.float = optionsButtonFloat;\n optionButton.style.border = optionsButtonBorder;\n optionButton.style.background = optionButtonBackgrounds[buttonNumber];\n optionButton.style.borderRadius = optionsButtonCorner;\n optionButton.style.margin = optionsButtonMargin;\n optionButton.style.padding = optionsButtonPadding;\n optionsButtonWrapper.appendChild(optionButton);\n\n optionButtons.push(optionButton);\n}\n\noptionButtonOne = optionButtons[0];\noptionButtonTwo = optionButtons[1];\noptionButtonThree = optionButtons[2];\noptionButtonFour = optionButtons[3];\n</code></pre>\n\n<p>If you change portions of the rest of the code, the first and the last four lines in the code above may be removed, but I just wanted you to get the idea.</p>\n\n<p>Perhaps more importantly, most of your style attributes seem to be constant. Instead of having so many styles be assigned manually, you should just have optionButtons (and other elements) have a <code>class</code>, and then assign your styles in CSS instead of JavaScript.</p>\n\n<p>Also, the array syntax <code>[r = 255, g = 56, b = 30]</code> seems odd and is probably not what you wanted. Perhaps you meant <code>{\"r\" : 255, \"g\" : 56, \"b\" : 30 }</code> or just <code>[255, 56, 30]</code>.</p>\n\n<p>If you use CSS properly and for loops, I suspect your code will be reduced to less than a third.</p>\n\n<p>Also, I put your code in <a href=\"http://closure-compiler.appspot.com/home\" rel=\"nofollow\">Google Closure Compiler</a> and it reported a few errors:</p>\n\n<blockquote>\n <p>IE8 (and below) will parse trailing commas in array and object literals incorrectly.</p>\n</blockquote>\n\n<p>Apparently, the code <code>[..., [r = 112, g = 25, b = 3],]</code> (with the <code>,</code> right before the <code>]</code>) causes problems in some browsers. You can simply remove that last comma.</p>\n\n<p><code>swtich</code> should be <code>switch</code> and <code>switch(...)[]</code> does not exist in JavaScript. Did you mean <code>switch(...) {</code> instead? What were those <code>[]</code> supposed to mean?</p>\n\n<p><code>case default:</code> isn't valid JavaScript. Just have <code>default:</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T15:17:54.210", "Id": "26401", "Score": "0", "body": "Yes, the switch case is suppose to have a opening curly brace have no idea what the brackets are. You suggested {\"r\" : 255, \"g\" : 56, \"b\" : 30 } instead of my old array syntax, what is the difference if you don't mind me asking? Thanks for your feedback!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T15:20:44.940", "Id": "26402", "Score": "0", "body": "in `var x = {\"r\" : 2};`, `x.r` has the value `2`. In `var x = [r=2];`, `x[0]` has the value `2`, and the variable `r` is also assigned the same value. In other words, `var x = [r=2];` is equivalent to `r = 2; var x = [2];`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T12:31:35.250", "Id": "16224", "ParentId": "16216", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T02:53:03.757", "Id": "16216", "Score": "0", "Tags": [ "javascript" ], "Title": "Buttons and Random Colours" }
16216
<p>I'm working on a project in which the previous programmer seems to have loved using the AS keyword in the SELECT part of queries. I really don't like how it's written but if there is no performance difference I won't change existing code.</p> <p>My tests did give a slight advantage to not using the AS keyword but I'm clueless on how to properly test it(I ran the different queries using Navicat)</p> <p>And maybe there is also a difference between different types of databases and engines. I'm using MySQL InnoDB.</p> <p>Simplified query:</p> <pre><code> SELECT DISTINCT `sometable`.`id` AS `id`, `sometable`.`name` AS `name`, `sometable`.`description` AS `description`, `sometable`.`price` AS `price`, `sometable`.`size` AS `size`, `sometable`.`area` AS `area`, `sometable`.`center` AS `center` FROM `sometable` </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T13:09:18.930", "Id": "26399", "Score": "2", "body": "Since you are only changing the metadata, i.e. the name of the returned columns, it doesn't affect each row as it is processed. I'd expect the overhead to be inconsequential." } ]
[ { "body": "<p>I wouldn't expect much if any noticeable overhead as all that is doing is aliasing the name of the column in the result set.</p>\n\n<p>The question I would ask however, is <em>why it's being done in the first place?</em> All I can think of is to prevent the code which uses the query breaking if a column is renamed (as long as the alias isn't changed).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T18:51:29.030", "Id": "26409", "Score": "0", "body": "I have no idea why it was done, I suppose there is no good reason to it. I wonder, how would it not break this code if a column is renamed? You would still have to rename the key in the query itself so you could add the AS old_key when you do that. And please future programmers, add a comment why you added the alias and or changed the column name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T18:57:32.797", "Id": "26410", "Score": "1", "body": "Well I suppose that depends on where the query used, I was thinking that if it was in a stored procedure for example, if the column name in the table was changed, as long as the alias remained the same, the results of the stored procedure would remain consistent..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T19:06:52.317", "Id": "26412", "Score": "0", "body": "I didn't know/realized a stored procedure would do that. Thanks. Sadly, this is mysql_* in php." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T17:47:03.947", "Id": "16235", "ParentId": "16219", "Score": "1" } } ]
{ "AcceptedAnswerId": "16235", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T08:55:15.337", "Id": "16219", "Score": "1", "Tags": [ "performance", "mysql", "sql" ], "Title": "Is there a performance difference using AS keyword in SQL?" }
16219
<p>I'm working now on project, which is need some <strong>read more</strong> functionality and I tried to write this jquery plugin and <a href="https://github.com/matmuchrapna/jquery.readmore/blob/master/jquery.readmore.js" rel="nofollow"><strong>share</strong></a> it in my github account.</p> <p>Here is the full listing of code:</p> <pre><code>;(function ( $, window, document, undefined ) { function get_link(readmore_wrap_class, readmore_class, readmore_text ) { return $('&lt;a/&gt;') .addClass(readmore_wrap_class) .prop('href', '#') .html( $('&lt;span/&gt;') .addClass(readmore_class) .text(readmore_text) ); } function get_first_p(text, sentences_number) { var paragraph = text.find('p:first-child').clone(); return paragraph .text( paragraph .text().split('.', sentences_number) .join('. ') + '. ' ); } $.fn.readmore = function (options) { var settings = $.extend({ sentences_number: 3, readmore_text: 'Read more.', readmore_toggle_text: 'Read less.', readmore_wrap_class: 'readmore_link_wrap', readmore_class: 'readmore_link', bidirectional: false }, options); return this.each(function(index) { var text = $(this), // replace default settings with per text data attributes sentences_number = text.data('sentences_number') || settings.sentences_number, readmore_text = text.data('readmore_text') || settings.readmore_text, readmore_toggle_text = text.data('readmore_toggle_text') || settings.readmore_toggle_text, readmore_wrap_class = text.data('readmore_wrap_class') || settings.readmore_wrap_class, readmore_class = text.data('readmore_class') || settings.readmore_class, bidirectional = text.data('bidirectional') || settings.bidirectional; link = get_link(readmore_wrap_class, readmore_class, readmore_text), first_p = get_first_p(text, sentences_number); /* Copy first paragraph Save only first `sentences_number` sentences Add link `read more` Hide Original paragraphs On click on `read more` link delete rirst extra paragraph Show original paragraphs if bidirectional add 'readless' link to whole text On click to it delete it and run readmore again (go to 1 step) */ text.find('p').hide(); link .appendTo(first_p) .on('click', function(event) { first_p.remove(); text.find('p').show(); if (bidirectional) { get_link(readmore_wrap_class, readmore_class, readmore_toggle_text) .appendTo(text) .on('click', function(event) { $(this).remove(); text.readmore(); event.preventDefault(); }); } event.preventDefault(); }); text.prepend(first_p); }); }; ($('.readmore').length !== 0) &amp;&amp; $('.readmore').readmore(); // end of jquery plugin wrap })( jQuery, window, document ); </code></pre> <h2>Codereview goals:</h2> <ul> <li>What I have missed?</li> <li>What can I improve?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T09:59:37.730", "Id": "26395", "Score": "0", "body": "Is splitting on sentences really what you need? Other options are word count, letter count(but round on words), lines(use line-height * lines, is tricky) And in all cases I would not just get the text from the first paragraph because very often there is 1 paragraph per line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T15:57:54.867", "Id": "26534", "Score": "0", "body": "Don't forget to remove console.log!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T17:03:50.243", "Id": "26537", "Score": "0", "body": "@LarryBattle Thank you, but I have not such commands in code)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T22:40:20.223", "Id": "26546", "Score": "0", "body": "@VladimirStarkov Check out line 90 [here](https://github.com/matmuchrapna/jquery.readmore/blob/master/jquery.readmore.js)" } ]
[ { "body": "<p>The code is good, only a few ignorable pointers : </p>\n\n<ul>\n<li><p>lowerCamelCase is the standard for JavaScript, so</p>\n\n<ul>\n<li><code>get_link</code> -> <code>getLink</code> </li>\n<li><code>get_first_p</code> -> <code>getFirstParagraph</code></li>\n<li><code>readmore</code> -> <code>readMore</code> ?</li>\n</ul></li>\n<li><p>The code could be more DRY for the retrieval of settings.\nI would counter-propose something like this:</p></li>\n</ul>\n\n<blockquote>\n<pre><code> var defaultSettings = {\n sentences_number: 3,\n readMoreText: 'Read more.',\n readMoreToggle_text: 'Read less.',\n readMoreWrapClass: 'readmore_link_wrap',\n readMoreClass: 'readmore_link',\n bidirectional: false\n };\n\n var settings = $.extend({}, defaultSettings, options);\n\n return this.each(function(index) {\n\n var text = $(this),\n var elementSettings = {};\n\n //Optionally replace settings with per text data attributes\n for( key in defaultSettings )\n elementSettings[key] = text.data( key ) || settings[key];\n\n //Then you could either\n link = get_link( elementSettings ),\n //Or you could\n link = get_link(elementSettings.readmore_wrap_class, \n elementSettings.readmore_class, \n elementSettings.readmore_text);\n</code></pre>\n</blockquote>\n\n<ul>\n<li><p><code>($('.readmore').length !== 0) &amp;&amp; $('.readmore').readmore();</code> this is a bit too Golfic ( reminds me of code golf ) and has a repeated constant which should be extracted and part of your readMore object in my mind.</p></li>\n<li><p>Finally, your commenting is very un-even, one part has a lot, the rest has close to nothing. I'd say that your functions deserve each a <code>/* One liner */</code>.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-23T16:32:04.060", "Id": "37968", "ParentId": "16222", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T09:37:28.977", "Id": "16222", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "jquery.readmore plugin" }
16222
<p>Following is a chunk of code from my class which generates PDF documents. I am refactoring my code and in the process I have created short methods. But I have to pass 'table i.e PdfPTable' to my methods again and again. How can I avoid this?</p> <pre><code>PdfPTable orgTable = new PdfPTable(2); PdfPCell cell = null; string orgName = dr["OrganizationName"].ToString(); cell = new PdfPCell(new Phrase(orgName, Heading1)) {Colspan = 2, BackgroundColor = BckColor, HorizontalAlignment = Element.ALIGN_CENTER }; orgTable.AddCell(cell); AddOrganizationProfile(document, dr, orgTable); OrganizationHeadOffice(document, dr, orgTable); OrganizationContacts(document, orgTable, orgId); private void OrganizationHeadOffice(Document document, DataRow dr, PdfPTable table) { AddTitle("Office Contact &amp; Information:", table); // How to avoid passing table variable again and again here. AddLegend("Address:", table); AddDataValue(dr["address"].ToString(), table); AddLegend("Contact Number:", table); AddDataValue(phone1, table); } private void AddTitle(string title, PdfPTable table) { table.AddCell(new PdfPCell(new Phrase(title, TableFontCaption)) { Colspan = 2, BackgroundColor = BckColor }); } private void AddLegend(string legend, PdfPTable table) { table.AddCell(new PdfPCell() { Border = Rectangle.NO_BORDER, Phrase = new Phrase(legend, TableFontCaption) }); } private void AddDataValue(string dataValue, PdfPTable table) { table.AddCell(new PdfPCell() { Border = Rectangle.NO_BORDER, Phrase = new Phrase(dataValue, TableFont) }); } </code></pre>
[]
[ { "body": "<p>Make PdfPTable a property of the class and set it in the constructor.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T13:59:45.517", "Id": "16226", "ParentId": "16225", "Score": "5" } }, { "body": "<p>This looks like a good candidate for the <a href=\"http://en.wikipedia.org/wiki/Builder_pattern\">Builder pattern</a>.</p>\n\n<p>You have a PdfPTableBuilder class, whose sole responsibility is to (of course) <em>build</em> a PdfPTable instance. You initialize it and call various setter methods, and each method returns <code>this</code>, so that you can chain them:</p>\n\n<pre><code>PdfPTableBuilder builder = new PdfPTableBuilder();\nbuilder.AddLegend(\"Address:\").AddDataValue(dr[\"address\"].ToString());\n// etc.\nreturn builder.build();\n</code></pre>\n\n<p>The builder itself simply holds all the data it needs to construct the table instance, and pours that into the table in the <code>build</code> method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T14:03:07.573", "Id": "16227", "ParentId": "16225", "Score": "4" } }, { "body": "<p>Your methods, as they stand, appear to be able to be <code>static</code>. In other words, there is no reliance on class state at all. Make <code>orgTable</code> a member of the class and have each method access it as <code>this.orgTable</code> rather than as a method parameter.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T14:58:28.907", "Id": "16229", "ParentId": "16225", "Score": "1" } }, { "body": "<p>Expanding on the <a href=\"https://codereview.stackexchange.com/a/16227/7773\">answer from @CarlManaster</a>:</p>\n\n<p>You can have your \"builder\" extend IEnumerable, then add an <code>Add(PdfTableItemType cellType, string content)</code> method, and then add items using the <a href=\"http://msdn.microsoft.com/en-us/library/bb384062.aspx#sectionToggle2\" rel=\"nofollow noreferrer\">collection initializer</a>.</p>\n\n<h1>Sample usage</h1>\n\n<pre><code>public static PdfPTable ReticulateSplines() {\n PdfPTableBuilder builder = new PdfPTableBuilder() {\n { PdfTableItemType.Title, \"Office Contact &amp; Information:\" },\n { PdfTableItemType.Legend, \"Address:\" },\n // ...\n };\n // Or, if you prefer:\n builder.Add(PdfTableItemType.DataValue, \"address\".ToString());\n // etc.\n //return builder.Build();\n}\n</code></pre>\n\n<h1>Example skeleton for the builder</h1>\n\n<pre><code>public class PdfPTableBuilder : IEnumerable\n{\n public enum PdfTableItemType\n {\n Title,\n Legend,\n DataValue,\n }\n\n public IEnumerator GetEnumerator() {\n throw new NotImplementedException();\n }\n\n public void Add(PdfTableItemType cellType, string content) {\n switch (cellType) {\n case PdfTableItemType.Title:\n // table.AddCell(...);\n break;\n // etc;\n }\n }\n\n public PdfTable Build() {\n throw new NotImplementedException();\n }\n public class PdfTable { } // Dummy.\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T17:37:21.037", "Id": "26406", "Score": "0", "body": "The idea of using an enum and a switch doesn't make it very extensible as any time you want to add a new type you need to modify the enum and the class. Also, I fail to see what the point of the builder implementing IEnumerable is?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T19:10:07.697", "Id": "26414", "Score": "0", "body": "@TrevorPilley 1. the point of extending IEnumerable it to allow using the collection initializer syntax. Do you think this is convoluted? 2. Where did extensibility come into the picture? In any case, `any time you want to add a new type [of cell]` you would have to write **somewhere** the code for writing that type of cells. I don't see how having that code in a new switch case is any worse than having it in a new method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T11:47:12.280", "Id": "26438", "Score": "1", "body": "The reason is that it breaks OCP (Open Closed Principle), if you wanted to add another type of cell and you had a method per cell type, you could subclass the original class to add functionality without having to change the original implementation. Ok, I understand what you mean now re: implementing IEnumerable - however I think you are misusing it since you are not actually able to enumerate the class. It would probably be better to add a constructor which accepts the initial items in an IEnumerable of KeyValuePairs if you insist on the enum." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T12:37:50.030", "Id": "26513", "Score": "0", "body": "I understand. Very good points." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T17:11:55.450", "Id": "16232", "ParentId": "16225", "Score": "0" } }, { "body": "<p>Another option which has not yet been covered would be extension methods.</p>\n\n<p>If the code inside your methods is not specific to the class that is calling it, by which I mean if the AddTitle method would be exactly the same regardless of which class wanted to create a PDF, you could make it an extension method by moving it to a <code>static</code> class</p>\n\n<pre><code>public static class PdfPTableExtensions\n{\n public static void AddTitle(this PdfPTable table, string title)\n {\n table.AddCell(new PdfPCell(new Phrase(title, TableFontCaption)) { Colspan = 2, BackgroundColor = BckColor });\n }\n}\n</code></pre>\n\n<p>which you can then call as follows:</p>\n\n<pre><code>table.AddTitle(\"Office Contact &amp; Information:\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T17:35:05.093", "Id": "16234", "ParentId": "16225", "Score": "2" } } ]
{ "AcceptedAnswerId": "16226", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T13:23:43.093", "Id": "16225", "Score": "4", "Tags": [ "c#", "pdf" ], "Title": "Class for generating PDF documents" }
16225
<p>I need to check the end of a URL for the possible existence of /news_archive or /news_archive/5 in PHP. The below snippet does exactly what I want, but I know that I could achieve this with one <code>preg_match</code> rather than two. How can I improve this code to treat the /5 as an optional segment and capture it if it exists?</p> <pre><code>if (preg_match('~/[0-9A-Za-z_-]+_archive/[0-9]+$~', $_SERVER['HTTP_REFERER'], $matches) || preg_match('~/[0-9A-Za-z_-]+_archive$~', $_SERVER['HTTP_REFERER'], $matches)) { $page_info['parent_page']['page_label'] = ltrim($matches[0], '/'); } </code></pre>
[]
[ { "body": "<p>Consider your first pattern:</p>\n\n<pre><code>~/[0-9A-Za-z_-]+_archive/[0-9]+$~\n</code></pre>\n\n<p>Let's break it down:</p>\n\n<ol>\n<li><code>/</code> a literal string <code>/</code></li>\n<li><code>[0-9A-Za-z_-]+</code> one or more of <code>0-9</code>, <code>A-Z</code>, <code>a-z</code>, <code>_</code> or <code>-</code></li>\n<li><code>_archive</code> a literal string <code>_archive</code></li>\n<li><code>/</code> literal slash again</li>\n<li><code>[0-9]+</code> one or more digits</li>\n<li><code>$</code> the end of the string must follow the one or more digits</li>\n</ol>\n\n<p>So basically you want to make #4 and #5 optional. To be more specific, you want either both 4 and 5, or neither 4 nor 5.</p>\n\n<p>Consider this:</p>\n\n<p><code>(a[b]+)?</code></p>\n\n<p>This means that you have one <code>a</code> followed by one or more <code>b</code>, and that this grouped a/b entity is optional.</p>\n\n<p>Letting a be #4 and b be digits like in #5, we're left with:</p>\n\n<p><code>(/[0-9]+)?</code></p>\n\n<p>Or:</p>\n\n<pre><code>~/[0-9A-Za-z_-]+_archive(/[0-9]+)?$~\n</code></pre>\n\n<p>This will capture the entire group though, like <code>/5</code>:</p>\n\n<pre><code>php -r \"preg_match('~/[0-9A-Za-z_-]+_archive(/([0-9]+))?$~', '/news_archive/5', $m); var_dump($m);\"\narray(2) {\n [0] =&gt;\n string(15) \"/news_archive/5\"\n [1] =&gt;\n string(2) \"/5\"\n}\n</code></pre>\n\n<p>You can just add another group to remedy that though:</p>\n\n<pre><code>~/[0-9A-Za-z_-]+_archive(/([0-9]+))?$~\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>php -r \"preg_match('~/[0-9A-Za-z_-]+_archive(/([0-9]+))?$~', '/news_archive/44', $m); var_dump($m);\"\narray(3) {\n [0] =&gt;\n string(16) \"/news_archive/44\"\n [1] =&gt;\n string(3) \"/44\"\n [2] =&gt;\n string(2) \"44\"\n}\n</code></pre>\n\n<p>You could technically make the outside group a non-capturing group (like <code>(?:/([0-9]+))?</code>), but I don't think the added complication is worth not grabbing the <code>/</code> part too.</p>\n\n<p>(By the way, sorry if you're familiar with regex and you found this excessive. I tend to take a very verbose approach to any regex related question :).)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T22:43:37.927", "Id": "26422", "Score": "0", "body": "This is a fantastic response, and certainly more than I expected. In a good way. I am fairly unfamiliar with regex itself, so the thorough analysis was a pleasant and refreshing lesson! Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T03:58:53.350", "Id": "26431", "Score": "0", "body": "@davo0105 Glad I could help! :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T19:16:28.047", "Id": "16240", "ParentId": "16230", "Score": "3" } } ]
{ "AcceptedAnswerId": "16240", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T16:48:23.673", "Id": "16230", "Score": "3", "Tags": [ "php", "regex" ], "Title": "Capturing optional regex segment with PHP" }
16230
<p>This is my first jQuery plugin. It is a simple slider that requires very little mark up in html. It works for my purposes but I am not a jQuery expert and I am wondering if there are mistakes or shortcuts that I took in its creation.</p> <p>Thank you for taking a look at the plugin!</p> <h1>The HTML</h1> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function(){ $('.st-slider').stSlider(); }); &lt;/script&gt; &lt;div id="feature-slider" class="st-slider"&gt; &lt;ul&gt; &lt;li data-collection-name="Collection 1"&gt;&lt;a href="#"&gt;&lt;img src="images/slide1.jpg"&gt;&lt;/a&gt;&lt;/li&gt; &lt;li data-collection-name="Collection 2"&gt;&lt;a href="#"&gt;&lt;img src="images/slide2.jpg"&gt;&lt;/a&gt;&lt;/li&gt; &lt;li data-collection-name="Collection 3"&gt;&lt;a href="#"&gt;&lt;img src="images/slide3.jpg"&gt;&lt;/a&gt;&lt;/li&gt; &lt;li data-collection-name="Collection 4"&gt;&lt;a href="#"&gt;&lt;img src="images/slide4.jpg"&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <h1>The CSS</h1> <pre><code>.st-slider { overflow: hidden; width: 685px; height: 412px; margin-top: 15px; position: relative; margin-bottom: 70px; } .st-slider ul { margin: 0; padding: 0; position: relative; } .st-slider ul li { display: block; margin: 0; padding: 0; background: #fff; float: left; padding: 5px; border: 1px solid #ddd; } .st-slider .st-slider-caption { background: rgba(215,204,186,0.8); font-size: 18px; color: #fff; text-transform: uppercase; letter-spacing: .3em; position: relative; z-index: 2; text-align: center; height: 40px; top: 280px; width: 685px; } .st-slider .st-slider-caption span { position: absolute; top: 9px; left: 0; text-align: center; width: 685px; } .st-slider .st-slider-nav { position: relative; top: 229px; z-index: 3; height: 62px; width: 100%; } .st-slider .st-slider-nav div { background: url('../images/st-slider-nav.png'); width: 30px; height: 62px; position: absolute; cursor: pointer; } .st-slider .st-slider-nav .next { background-position: -30px 0; left: 655px; } .st-slider .st-slider-nav .prev:hover { background-position: -60px 0; } .st-slider .st-slider-nav .next:hover { background-position: -90px 0; } .st-slider-go-to-nav { display: block; margin-top: -55px; padding-top: 0; font-size: 12px; color: #aaa; float: right; } .st-slider-go-to-nav { list-style: none; } .st-slider-go-to-nav li { padding: 0; margin-right: 10px; float: left; } .st-slider-go-to-nav li:last-child { margin-right: 0; } .st-slider-go-to-nav li a { padding: 5px 8px; color: #aaa; text-decoration: none; cursor: pointer; } .st-slider-go-to-nav li a:hover, .st-slider-go-to-nav li.current a { color: #666; background: #eee; } </code></pre> <h1>The jQuery</h1> <pre><code>(function( $ ) { $.fn.stSlider = function() { var sliderContainer = $(this), slidePane = sliderContainer.find('ul'), cloneFirst = slidePane.find('li:first-child').clone(), cloneLast = slidePane.find('li:last-child').clone(); cloneFirst.attr('data-clone', 'last').appendTo(slidePane); cloneLast.attr('data-clone', 'first').prependTo(slidePane); var slides = slidePane.find('li'); var slideWidth = $(this).width(), negSlideWidth = 0 - slideWidth, slidesArray = $.makeArray(slides), slidePaneWidth = ( slidesArray.length * slideWidth ); // Build slider controls var captionHolderDiv = $('&lt;div class="st-slider-caption"&gt;&lt;/div&gt;'), captionDiv = $('&lt;span&gt;&lt;/span&gt; '), navDiv = $('&lt;div class="st-slider-nav"&gt;&lt;/div&gt;'), prevDiv = $('&lt;div class="prev"&gt;&lt;/div&gt;'), nextDiv = $('&lt;div class="next"&gt;&lt;/div&gt;'), goToNav = $('&lt;ul class="st-slider-go-to-nav"&gt;&lt;/ul&gt;'); // Insert slider controls into DOM slidePane.after(captionHolderDiv); captionDiv.appendTo(captionHolderDiv); captionHolderDiv.after(navDiv); prevDiv.appendTo(navDiv); nextDiv.appendTo(navDiv); sliderContainer.after(goToNav); // Build and insert each slide number link for(var i = 0; i &lt; slidesArray.length - 2; i++) { var count = i + 1; var goToNavItem = $('&lt;li id="' + count + '"&gt;&lt;a&gt;' + count + '&lt;/a&gt;&lt;/li&gt;'); goToNavItem.appendTo(goToNav); if ( count == 1 ) { goToNavItem.addClass('current'); } } var slideCaptionHolder = sliderContainer.find('.st-slider-caption span'), slideCaption = sliderContainer.find('li:nth-child(2)').data('collection-name'), goToArray = $('.st-slider-go-to-nav li'); slidePane.width(slidePaneWidth); slides.addClass('st-slider-slide'); slidePane.animate({left: negSlideWidth}, 0); slideCaptionHolder.html(slideCaption); function slide(direction, location) { var x = parseInt(slidePane.css('left'), 10), y = Math.abs(x), i = 0, theSlide = slides.eq(i), slideCaption = theSlide.data('collection-name'), slideClone = theSlide.data('clone'), lastPosition = 0 - slidePaneWidth + (slideWidth * 2); if ( direction == 'null' ) { } else if (direction == 'prev') { i = (y / slideWidth) -1; i = i % slidesArray.length; theSlide = slides.eq(i); slideCaption = theSlide.data('collection-name'); slideClone = theSlide.data('clone'); slidePane.animate({left: parseInt(slidePane.css('left'), 10) + slideWidth}, 600); slideCaptionHolder.fadeOut(300, function() { $(this).html(slideCaption); $(this).fadeIn(300, function(){ if ( slideClone &amp;&amp; slideClone == 'first' ) { slidePane.animate({left: lastPosition}, 0); } }); }); goToArray.removeClass('current'); if ( slideClone == 'last') { goToArray.eq(slidesArray.length - 2).addClass('current'); } else { goToArray.eq(i - 1).addClass('current'); } } else { i = (y / slideWidth) +1; i = i % slidesArray.length; theSlide = slides.eq(i); slideCaption = theSlide.data('collection-name'); slideClone = theSlide.data('clone'); slidePane.animate({left: parseInt(slidePane.css('left'), 10) - slideWidth }, 600); slideCaptionHolder.fadeOut(300, function() { $(this).html(slideCaption); $(this).fadeIn(300, function(){ if ( slideClone &amp;&amp; slideClone == 'last' ) { slidePane.animate({left: negSlideWidth }, 0); } }); }); goToArray.removeClass('current'); if ( slideClone == 'last') { goToArray.eq(0).addClass('current'); } else { goToArray.eq(i - 1).addClass('current'); } } if ( location ) { i = location; theSlide = slides.eq(i); slideCaption = theSlide.data('collection-name'); slideClone = theSlide.data('clone'); slidePane.animate({left: 0 - (i * slideWidth) }, 600); slideCaptionHolder.fadeOut(300, function() { $(this).html(slideCaption); $(this).fadeIn(300, function(){ if ( slideClone &amp;&amp; slideClone == 'last' ) { slidePane.animate({left: negSlideWidth }, 0); } else if ( slideClone &amp;&amp; slideClone == 'first' ) { slidePane.animate({left: lastPosition}, 0); } }); }); goToArray.removeClass('current'); goToArray.eq(i - 1).addClass('current'); } } timer = setInterval(slide, 5000); sliderContainer.hover(function(){ clearInterval(timer); }, function(){ timer = setInterval(slide, 5000); }); var slidePrev = sliderContainer.find('.prev'), slideNext = sliderContainer.find('.next'); slidePrev.click(function(){ slide('prev'); }); slideNext.click(function(){ slide(); }); $('.st-slider-go-to-nav li a').click(function(){ if ( $(this).parent().hasClass('current') ) { } else { var location = $(this).parent().attr('id'); slide('null', location); clearInterval(timer); timer = setInterval(slide, 5000); } }); }; })( jQuery ); </code></pre>
[]
[ { "body": "<p>Your code seems solid to me, only a few things my eye caught:</p>\n\n<ul>\n<li>you're using <code>$(this)</code> in multiple places, while your <code>sliderContainer</code> already holds that jQuery object. This object can be then reused instead of making jQuery convert DOM into jQuery several times</li>\n<li>instead of writing <code>cloneFirst.attr('data-clone', 'last').appendTo(slidePane);</code> it's advised to use jQuery's data() function to set data for DOM elements: <code>cloneFirst.data('clone', 'last').appendTo(slidePane);</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T21:44:03.600", "Id": "26457", "Score": "0", "body": "Wow! First of all, thank you so much for the feedback!\n\nSecond, thank you for the advice on using `$(this)`.\n\nAs for using `.data()`, I tried that first but it did not seem to create the `data-collection-name` attribute in the html since it wasn't already there. Perhaps I missed something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T21:55:09.950", "Id": "26458", "Score": "0", "body": "interesting remark with regards to the data() function... if that didn't work, perhaps it would be wise to ask/report this to jQuery forums / bug tracker?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T22:03:43.513", "Id": "26459", "Score": "0", "body": "This plugin does not seem to work when multiple instaces of the function is called on `$(document).ready();`. I am guessing I will need to loop through each function call to maintain the identity of the one that is being executed? I am not sure. It doesn't particularly matter for this project but it would be nice to have an idea if in the future I needed to expand to multiple instances." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T22:13:27.823", "Id": "26460", "Score": "0", "body": "I'm sorry, but I cannot answer that question... I have never done a jQuery plugin and I was merely reviewing the code for performance and best practices issues... perhaps you can try and ask on StackOverflow if you need to resolve the issue instead?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T18:46:17.730", "Id": "16237", "ParentId": "16236", "Score": "1" } } ]
{ "AcceptedAnswerId": "16237", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T17:59:40.953", "Id": "16236", "Score": "2", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "Review my first jQuery slider plugin" }
16236
<p>I'm starting to learn how to meld the worlds of C and Haskell. Looking for any feedback on this first function.</p> <p>The function takes in a pointer to an array of unsigned chars and returns a pointer to 32 unsigned shorts. Or at least I would like it too :).</p> <p>I am unsure about when the memory used to return the result is cleaned up. Is it possible that it will be garbage collected before I can use it on the C side?</p> <p>Anyway here's the code.</p> <pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE ForeignFunctionInterface #-} module JSFLPlugin where import Foreign.C.Types (CInt(..)) import Foreign.ForeignPtr (newForeignPtr_) import Foreign.Ptr (Ptr) import Data.Serialize (encode) import Foreign.ForeignPtr.Unsafe (unsafeForeignPtrToPtr) import Data.Digest.Pure.MD5 (md5) import Data.ByteString (unpack) import Data.ByteString.Internal (toForeignPtr, fromForeignPtr) import Data.ByteString.Lazy.Internal (chunk) import Data.ByteString.Lazy (empty) import Data.Word (Word8, Word16) import Data.Text.Format (hex) import Control.Applicative ((&lt;$&gt;)) import Data.Text.Lazy.Builder (toLazyText) import Data.Text.Lazy (toStrict) import Data.Text.Foreign (asForeignPtr) import Data.Monoid ((&lt;&gt;), mempty) -- | Hash pointer to array of unsigned chars hash :: CInt -&gt; Ptr Word8 -&gt; IO (Ptr Word16) hash count addr = do -- cast to ForeignPtr fptr &lt;- newForeignPtr_ addr -- Make a strict ByteString let sbyte = fromForeignPtr fptr 0 (fromIntegral count) -- Make a lazy ByteString from the strict one lbyte = chunk sbyte empty -- Hash with md5 and encode as a strict ByteString digest = encode . md5 $ lbyte -- Convert the each digest byte to a UTF-16 encoded hexdecimal character hexBytes = toLazyText . foldr (\x y -&gt; y &lt;&gt; hex x) mempty . unpack $ digest -- Convert to a strict Text and get the pointer to chars fmap (unsafeForeignPtrToPtr . fst) . asForeignPtr . toStrict $ hexBytes foreign export ccall hash :: CInt -&gt; Ptr Word8 -&gt; IO (Ptr Word16) </code></pre> <p>EDIT: New version per Joey's suggestions (compiled but not tested).</p> <pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE ForeignFunctionInterface #-} module JSFLPlugin where import Foreign.C.Types (CInt(..)) import Foreign.ForeignPtr (newForeignPtr_) import Foreign.Ptr (Ptr) import qualified Data.Serialize as Serialize import Data.Digest.Pure.MD5 (MD5Digest) import Data.ByteString (ByteString) import Data.ByteString.Internal (fromForeignPtr) import Data.Word (Word8, Word16) import Data.Text (Text) import Data.Text.Foreign (unsafeCopyToPtr) import qualified Data.ByteString.Base16 as Base16 import Data.Text.Encoding (decodeUtf8) import Crypto.Classes (hash') pureHash :: ByteString -&gt; Text pureHash = decodeUtf8 . Base16.encode . Serialize.encode . md5 where md5 s = hash' s :: MD5Digest hash :: CInt -&gt; Ptr Word8 -&gt; Ptr Word16 -&gt; IO () hash count input output = do fptr &lt;- newForeignPtr_ input let sbyte = fromForeignPtr fptr 0 $ fromIntegral count unsafeCopyToPtr (pureHash sbyte) output foreign export ccall hash :: CInt -&gt; Ptr Word8 -&gt; Ptr Word16 -&gt; IO () </code></pre>
[]
[ { "body": "<p>First, you have way too many comments. They clutter the code, and some of them are completely redundant.</p>\n\n<pre><code>-- | Hash pointer to array of unsigned chars\nhash :: CInt -&gt; Ptr Word8 -&gt; IO (Ptr Word16)\n</code></pre>\n\n<p>The comment provides no information beyond the function's name and signature. But it doesn't answer these questions:</p>\n\n<ul>\n<li><p>What hashing algorithm is being used?</p></li>\n<li><p>Why is the output <code>Ptr Word16</code>? UTF-16?</p></li>\n<li><p>Is the output in hexadecimal, or raw bytes? If it's hexadecimal, does it use capital or lowercase letters?</p></li>\n</ul>\n\n<p>Before we dive into foreign API details, we can do a little refactoring. There's a big chain of pure function application here. Let's move it outside so it doesn't clutter the scary foreign pointer stuff:</p>\n\n<pre><code>hashPure :: ByteString -&gt; Text\nhashPure sbyte =\n let lbyte = chunk sbyte empty\n digest = encode . md5 $ lbyte\n hexBytes = toLazyText . foldr (\\x y -&gt; y &lt;&gt; hex x) mempty . unpack $ digest \n in toStrict hexBytes\n</code></pre>\n\n<p>I think we can improve this a bit. Let's first take a step back. Here's all <code>hashPure</code> needs to do:</p>\n\n<ul>\n<li><p>Hash the input string (a strict ByteString) using MD5</p></li>\n<li><p>Convert it to a hex string (as Text)</p></li>\n</ul>\n\n<p>To get there, we have to do a bunch of annoying conversions. But we can avoid these if we tweak a couple of our library choices.</p>\n\n<p>Because of the <a href=\"http://hackage.haskell.org/packages/archive/crypto-api/latest/doc/html/Crypto-Classes.html\" rel=\"nofollow noreferrer\">Hash</a> instance on <a href=\"http://hackage.haskell.org/packages/archive/pureMD5/latest/doc/html/Data-Digest-Pure-MD5.html#t:MD5Digest\" rel=\"nofollow noreferrer\">MD5Digest</a>, we can eliminate a strict to lazy ByteString conversion:</p>\n\n<pre><code>import Crypto.Classes (hash')\nimport Data.Digest.Pure.MD5 (MD5Digest)\n\nhashPure :: ByteString -&gt; Text\nhashPure sbyte =\n let digest = encode (hash' sbyte :: MD5Digest)\n hexBytes = toLazyText . foldr (\\x y -&gt; y &lt;&gt; hex x) mempty . unpack $ digest \n in toStrict hexBytes\n</code></pre>\n\n<p>Your code for converting to hex is bogus. To illustrate why:</p>\n\n<pre><code>&gt;foldr (\\x y -&gt; y &lt;&gt; hex x) mempty [1,2,3]\n\"321\"\n</code></pre>\n\n<p>Namely:</p>\n\n<ul>\n<li><p>Your use of <code>foldr</code> flips the order. What you meant was: <code>foldr (\\x y -&gt; hex x &lt;&gt; y)</code></p></li>\n<li><p>The <a href=\"http://hackage.haskell.org/packages/archive/text-format/latest/doc/html/Data-Text-Format.html#v:hex\" rel=\"nofollow noreferrer\">hex function</a> does not pad the number to two characters.</p></li>\n</ul>\n\n<p>To avoid the first problem, you could have just said <code>mconcat (map hex)</code>. <a href=\"http://www.haskell.org/haskellwiki/Correctness_of_short_cut_fusion#foldr.2Fbuild\" rel=\"nofollow noreferrer\">foldr/build fusion</a> should optimize it.</p>\n\n<p>To fix the second problem, and avoid two more conversions, you can use the <a href=\"http://hackage.haskell.org/packages/archive/base16-bytestring/latest/doc/html/Data-ByteString-Base16.html\" rel=\"nofollow noreferrer\">base16-bytestring package</a>. You could avoid yet another conversion if you make <code>hash</code> return an array of chars instead of wide chars, but I won't do that yet.</p>\n\n<pre><code>hashPure :: ByteString -&gt; Text\nhashPure sbyte =\n let digest = encode (hash' sbyte :: MD5Digest)\n hexBytes = Base16.encode digest\n in decodeUtf8 hexBytes\n</code></pre>\n\n<p>We can make it a little prettier using point-free style:</p>\n\n<pre><code>hashPure :: ByteString -&gt; Text\nhashPure =\n decodeUtf8 . Base16.encode . Serialize.encode . md5\n where\n md5 s = hash' s :: MD5Digest\n</code></pre>\n\n<p>Now on to the ForeignPtr stuff. I saved the best for last.</p>\n\n<pre><code>hash :: CInt -&gt; Ptr Word8 -&gt; IO (Ptr Word16)\nhash count addr = do\n fptr &lt;- newForeignPtr_ addr\n let sbyte = fromForeignPtr fptr 0 (fromIntegral count)\n unsafeForeignPtrToPtr . fst &lt;$&gt; asForeignPtr (hashPure sbyte)\n</code></pre>\n\n<p>Your two points of interaction with C:</p>\n\n<ul>\n<li><p>Convert a C array of bytes to a <code>ByteString</code></p></li>\n<li><p>Convert a <code>Text</code> to a block of wide chars, and return a pointer to it.</p></li>\n</ul>\n\n<p>Your first conversion is sound, but I would use <a href=\"http://hackage.haskell.org/packages/archive/bytestring/latest/doc/html/Data-ByteString-Unsafe.html#v:unsafePackCStringLen\" rel=\"nofollow noreferrer\">unsafePackCStringLen</a> instead (<a href=\"http://hackage.haskell.org/packages/archive/bytestring/latest/doc/html/src/Data-ByteString-Unsafe.html#unsafePackCStringLen\" rel=\"nofollow noreferrer\">which does the same thing</a>):</p>\n\n<pre><code>hash :: CInt -&gt; Ptr Word8 -&gt; IO (Ptr Word16)\nhash count addr = do\n sbyte &lt;- unsafePackCStringLen (castPtr addr, fromIntegral count)\n unsafeForeignPtrToPtr . fst &lt;$&gt; asForeignPtr (hashPure sbyte)\n</code></pre>\n\n<p>The second conversion is wrong. ForeignPtr is for managing C objects in Haskell, not the other way around. The returned pointer will be invalidated when the ForeignPtr returned by <a href=\"http://hackage.haskell.org/packages/archive/text/latest/doc/html/Data-Text-Foreign.html#v:asForeignPtr\" rel=\"nofollow noreferrer\">asForeignPtr</a> is garbage collected.</p>\n\n<p>You fix this, you would need to <a href=\"http://hackage.haskell.org/packages/archive/base/latest/doc/html/Foreign-Marshal-Alloc.html#v:malloc\" rel=\"nofollow noreferrer\">malloc</a> a large enough buffer, then copy the text content into it. Unfortunately, <a href=\"http://hackage.haskell.org/packages/archive/text/latest/doc/html/Data-Text-Foreign.html\" rel=\"nofollow noreferrer\">Data.Text.Foreign</a> does not provide a convenient way to do this without a needless allocation.</p>\n\n<p>I would change the signature of the C function from this:</p>\n\n<pre><code>uint16_t *hash(int blksize, uint8_t *block);\n</code></pre>\n\n<p>To this:</p>\n\n<pre><code>void hash(uint8_t *block, size_t blksize, char out[33]);\n</code></pre>\n\n<p>Namely:</p>\n\n<ul>\n<li><p>Write a string to a caller-supplied buffer of the correct size, rather than allocating a buffer that the caller has to free. A hex-encoded MD5 hash is always 32 characters long. The 33rd byte is for the <a href=\"http://en.wikipedia.org/wiki/Null-terminated_string\" rel=\"nofollow noreferrer\">zero terminator</a>.</p></li>\n<li><p>Output a C string instead of UTF-16. Unless you plan to throw the output into a system call or something that takes UTF-16, <a href=\"https://softwareengineering.stackexchange.com/q/102205/3650\">you shouldn't be using UTF-16</a>.</p></li>\n<li><p>Flip pointer and size arguments. This is mainly a matter of taste.</p></li>\n</ul>\n\n<p>See if you can implement this part yourself. This post is already too long.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T02:34:33.113", "Id": "26426", "Score": "0", "body": "Great answer. As it turns out I do need UTF-16. I'll throw up a revised version with your edits after dinner." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:50:15.500", "Id": "16247", "ParentId": "16243", "Score": "4" } }, { "body": "<p>Here is a compositional rewriting of <code>hash</code>:</p>\n\n<pre><code>hash :: CInt -&gt; Ptr Word16 -&gt; Ptr Word8 -&gt; IO ()\nhash inputLength output input \n = (flip unsafeCopyToPtr output . pureHash . copyInput &lt;=&lt; newForeignPtr_) input\n where copyInput fptr = fromForeignPtr fptr 0 $ fromIntegral inputLength\n</code></pre>\n\n<p><code>&lt;=&lt;</code> is composition of kleisli arrows of a monad from <code>Control.Monad</code>. It has two advantages over <code>&gt;&gt;=</code> and <code>=&lt;&lt;</code>: it's associative and data flows in the same direction as in <code>.</code>. </p>\n\n<p>We get foreign pointer, copy data from it, calculate pure hash and copy result to output. This description is literally encoded in the pipeline, so I think the code is readable and maintainable.</p>\n\n<p>Note that I flipped the arguments so if you want you can eta-reduce <code>input</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T21:04:59.283", "Id": "26486", "Score": "0", "body": "I flirted with the idea of flipping unsafeCopyToPtr myself, but I think the local copyInput is overkill." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T11:09:52.063", "Id": "26575", "Score": "0", "body": "`copyInput` turns a long application of `fromForeignPtr` into a function with clearly understood semantics which composes nicely with other parts of pipeline. Inlining it as a lambda or flipping or resorting to `do` notation will clutter the code. Which of the options above you think is better? I just want to learn writing clear code - that's why I'm asking." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T17:39:03.750", "Id": "26622", "Score": "0", "body": "I am not so sure about the clear semantics part. Saying \"copy\" implies that there is an actually copying of bytes occurring, but fromForeignPtr is just a smart constructor. There is no copying. I guess fromForeignPtr' would be a better name. Also between the flip, new declaration, and kleisli arrow you've added complexity, and at best only removed a little bit." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T12:39:07.437", "Id": "16300", "ParentId": "16243", "Score": "0" } } ]
{ "AcceptedAnswerId": "16247", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T20:59:37.667", "Id": "16243", "Score": "2", "Tags": [ "c", "haskell" ], "Title": "Calling a Haskell MD5 hashing function from C, and returning the result back to C land" }
16243
<p>So, I needed to make me a register script for my website so pepole can register, and just wanted to know if It's okey. So, is there any vulns in this script i made?It works perfectly, just that i wanted to have someone to look over it here. Or if there could be some inprovments that could make it better.</p> <pre><code> &lt;?php $Username = $_POST['Username']; $Password = $_POST['Password']; $Email = $_POST['Email']; $IP = $_SERVER['REMOTE_ADDR']; if ($IP != "84.***.***.**") { die(); } // Beta, Restrict users from using it until it's done /* Random Activate code generator */ function GenerateCode() { $R1 = rand(1,9); $R2 = rand(1,9); $R3 = rand(1,9); $R4 = rand(1,9); $R5 = rand(1,9); $R6 = rand(1,9); $C1 = "$R1$R2$R3$R4$R5$R6"; // Simple complie method return $C1; } function Encrypt($Pass) { $B64 = base64_encode($Pass); $MD5 = md5($B64); $Hash = base64_encode($MD5); return $Hash; } /* Mysql data */ $MysqlUsername = "root"; $MysqlPassword = "**********"; $MysqlHostname = "localhost"; $MysqlDatabase = "teamgamersnet"; $Sql = new mysqli($MysqlHostname, $MysqlUsername, $MysqlPassword, $MysqlDatabase); if ($Sql-&gt;connect_error){ echo $Sql-&gt;connect_error; } $sUser = $Sql-&gt;real_escape_string($Username); $sPass = $Sql-&gt;real_escape_string($Password); $sMail = $Sql-&gt;real_escape_string($Email); $xPass = $Sql-&gt;real_escape_string(Encrypt($Password)); if (!$Username | !$Password | $Email) { die("Please fill in all the fields"); } $CheckUser = $Sql-&gt;query("SELECT Username FROM `users` WHERE `Username` = '".$sUser."'"); $CheckMail = $Sql-&gt;query("SELECT `E-Mail` FROM `users` WHERE `E-Mail` = '".$sMail."'"); if ($CheckUser-&gt;num_rows == 1) { die("Username allready exist"); } if ($CheckMail-&gt;num_rows == 1) { die("E-Mail allready exist"); } $xCode = GenerateCode(); $Insert = " INSERT INTO `teamgamersnet`.`users` (`ID`, `Username`, `Password`, `E-Mail`, `IP`, `Activated`, `ActivateId`) VALUES (NULL, '".$sUser."', '".$xPass."', '".$sMail."', '".$IP."', 'false', '".$xCode."'); "; $Create = $Sql-&gt;query($Insert); if (!$Create) { echo "S**t, a error happened D:";} $to = $Email; $subject = 'User account activation | Team Gamers Net'; $message = ' &lt;h3&gt;Thank you for registering at Team Gamers Net&lt;/h3&gt; &lt;p&gt;Just one more step and that is to activate your account&lt;/p&gt; &lt;p&gt;You registred with username '.$Username.'&lt;p&gt; &lt;p&gt;And your password you selected (not shown)&lt;/p&gt; &lt;p&gt;To activate and contiune, please click &lt;a href="http://TeamGamers.net/Activate.php"&gt;&lt;b&gt;HERE&lt;/b&gt;&lt;/a&gt;&lt;/p&gt; '; $headers = "From: DoNotReply@TeamGamers.Net \r\n"; $headers .= "Reply-To: Admin@heisteknikk.com \r\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; mail($to, $subject, $message, $headers); header("Location: /?register=true"); ?&gt; </code></pre>
[]
[ { "body": "<p>Ok, there are a couple of things wrong with your code and your method of organizing the code. I've pointed them out to you in the code below within comments. The comments preceded with <code>#</code> are my comments. </p>\n\n<pre><code>&lt;?php\n\n/* Mysql data */\n$MysqlUsername = \"root\";\n$MysqlPassword = \"**********\";\n$MysqlHostname = \"localhost\";\n$MysqlDatabase = \"teamgamersnet\";\n\n$Username = $_POST['Username'];\n$Password = $_POST['Password'];\n$Email = $_POST['Email'];\n\n# Check for empty variables \nif (empty($Username) || empty($Password) || empty($Email)) { die(\"Please fill in all the fields\"); }\n\n# We're only using $IP once, so why set it above? Let's do a direct comparison here\n// Beta, Restrict users from using it until it's done\n#OLD:: \n#if ($IP != \"84.***.***.***\") { die(); }\n\n#NEW::\nif ($_SERVER['REMOTE_ADDR'] != \"84.***.***.**\") { die(); } \n\n/* Random Activate code generator */\nfunction GenerateCode() {\n # You're setting 7 variables with like variables, and returning them\n #OLD::\n #$R1 = rand(1,9);\n #$R2 = rand(1,9);\n #$R3 = rand(1,9);\n #$R4 = rand(1,9);\n #$R5 = rand(1,9);\n #$R6 = rand(1,9);\n #$C1 = \"$R1$R2$R3$R4$R5$R6\";\n #return $C1;\n\n #NEW::\n return rand(1,9) . rand(1,9) . rand(1,9) . rand(1,9) . rand(1,9) . rand(1,9);\n}\n\n/* Encrypt the password */\nfunction Encrypt($Pass) {\n # Again, setting multiple variables in the name of readability over performance\n #OLD::\n #$B64 = base64_encode($Pass);\n #$MD5 = md5($B64);\n #$Hash = base64_encode($MD5);\n #return $Hash;\n\n #NEW::\n return base64_encode( md5( base64_encode($Pass) ) );\n}\n\n\n# Let's move the Mysql Connection Data to the top, so its easier to modify in the future\n#OLD::\n/* Mysql data */\n#$MysqlUsername = \"root\";\n#$MysqlPassword = \"**********\";\n#$MysqlHostname = \"localhost\";\n#$MysqlDatabase = \"teamgamersnet\";\n\n#NEW::\n# Moved to top\n\n$Sql = new mysqli($MysqlHostname, $MysqlUsername, $MysqlPassword, $MysqlDatabase);\nif ($Sql-&gt;connect_error){ echo $Sql-&gt;connect_error; }\n\n/* Let's add a comment here: Escape the user data */\n$sUser = $Sql-&gt;real_escape_string($Username);\n$sPass = $Sql-&gt;real_escape_string($Password);\n$sMail = $Sql-&gt;real_escape_string($Email);\n$xPass = $Sql-&gt;real_escape_string(Encrypt($Password));\n\n# Let's move this to the top, right after these are set from _POST, to avoid all the \n# prior computation before running into this. Also, use empty() or isset() instead of ! checking\n# See: http://www.phpbench.com/\n#OLD::\n#if (!$Username | !$Password | $Email) { die(\"Please fill in all the fields\"); }\n\n#NEW::\n# Moved to top, also - syntax errors fixed: it's || not | \n\n/* Let's add a comment here: Check if the user exists */\n$CheckUser = $Sql-&gt;query(\"SELECT Username FROM `users` WHERE `Username` = '\".$sUser.\"'\");\n$CheckMail = $Sql-&gt;query(\"SELECT `E-Mail` FROM `users` WHERE `E-Mail` = '\".$sMail.\"'\");\nif ($CheckUser-&gt;num_rows == 1) { die(\"Username allready exist\"); }\nif ($CheckMail-&gt;num_rows == 1) { die(\"E-Mail allready exist\"); }\n\n/* Let's add a comment here: Generate an activation code */\n$xCode = GenerateCode();\n\n/* Let's add a comment here: Write out the Insert statement */ \n$Insert = \"INSERT INTO `teamgamersnet`.`users` (`ID`, `Username`, `Password`, `E-Mail`, `IP`, `Activated`, `ActivateId`) \nVALUES (NULL, '\".$sUser.\"', '\".$xPass.\"', '\".$sMail.\"', '\".$IP.\"', 'false', '\".$xCode.\"');\";\n\n/* Let's add a comment here: Insert the SQL statement */\n$Create = $Sql-&gt;query($Insert);\n# Why are we echoing? Shouldn't we be dying?\n#OLD::\n#if (!$Create) { echo \"S**t, a error happened D:\";}\n\n#NEW::\nif ( empty($Create) || !isset($Create) ) { die(\"Sorry, an error occurred during Create.\"); }\n\n/* Let's add a comment here: Build the message, and send it to the user. */\n$to = $Email;\n$subject = 'User account activation | Team Gamers Net';\n$message = '\n&lt;h3&gt;Thank you for registering at Team Gamers Net&lt;/h3&gt;\n&lt;p&gt;Just one more step and that is to activate your account&lt;/p&gt;\n&lt;p&gt;You registred with username '.$Username.'&lt;p&gt;\n&lt;p&gt;And your password you selected (not shown)&lt;/p&gt;\n&lt;p&gt;To activate and contiune, please click &lt;a href=\"http://TeamGamers.net/Activate.php\"&gt;&lt;b&gt;HERE&lt;/b&gt;&lt;/a&gt;&lt;/p&gt;\n';\n$headers = \"From: DoNotReply@TeamGamers.Net \\r\\n\";\n$headers .= \"Reply-To: Admin@heisteknikk.com \\r\\n\";\n$headers .= \"MIME-Version: 1.0\\r\\n\";\n$headers .= \"Content-Type: text/html; charset=ISO-8859-1\\r\\n\";\nmail($to, $subject, $message, $headers);\n\nheader(\"Location: /?register=true\"); \n?&gt;\n</code></pre>\n\n<p>Here's the same code, with my comments removed:</p>\n\n<pre><code>&lt;?php\n\n/* Mysql connection data */\n$MysqlUsername = \"root\";\n$MysqlPassword = \"**********\";\n$MysqlHostname = \"localhost\";\n$MysqlDatabase = \"teamgamersnet\";\n\n$Username = $_POST['Username'];\n$Password = $_POST['Password'];\n$Email = $_POST['Email'];\n\n/* Check for empty variables */ \nif (empty($Username) || empty($Password) || empty($Email)) { die(\"Please fill in all the fields\"); }\n\n/* Beta, Restrict users from using it until it's done */\nif ($_SERVER['REMOTE_ADDR'] != \"84.***.***.**\") { die(); } \n\n/* Random Activate code generator */\nfunction GenerateCode() {\n return rand(1,9) . rand(1,9) . rand(1,9) . rand(1,9) . rand(1,9) . rand(1,9);\n}\n\n/* Encrypt the password */\nfunction Encrypt($Pass) { return base64_encode( md5( base64_encode($Pass) ) ); }\n\n$Sql = new mysqli($MysqlHostname, $MysqlUsername, $MysqlPassword, $MysqlDatabase);\nif ($Sql-&gt;connect_error){ echo $Sql-&gt;connect_error; }\n\n/* Escape the user data */\n$sUser = $Sql-&gt;real_escape_string($Username);\n$sPass = $Sql-&gt;real_escape_string($Password);\n$sMail = $Sql-&gt;real_escape_string($Email);\n$xPass = $Sql-&gt;real_escape_string(Encrypt($Password));\n\n/* Check if the user exists */\n$CheckUser = $Sql-&gt;query(\"SELECT Username FROM `users` WHERE `Username` = '\".$sUser.\"'\");\n$CheckMail = $Sql-&gt;query(\"SELECT `E-Mail` FROM `users` WHERE `E-Mail` = '\".$sMail.\"'\");\nif ($CheckUser-&gt;num_rows == 1) { die(\"Username allready exist\"); }\nif ($CheckMail-&gt;num_rows == 1) { die(\"E-Mail allready exist\"); }\n\n/* Generate an activation code */\n$xCode = GenerateCode();\n\n/* Write out the Insert statement */ \n$Insert = \"INSERT INTO `teamgamersnet`.`users` (`ID`, `Username`, `Password`, `E-Mail`, `IP`, `Activated`, `ActivateId`) \nVALUES (NULL, '\".$sUser.\"', '\".$xPass.\"', '\".$sMail.\"', '\".$IP.\"', 'false', '\".$xCode.\"');\";\n\n/* Insert the SQL statement */\n$Create = $Sql-&gt;query($Insert);\n\n/* Check if SQL insert went well, otherwise die */\nif ( empty($Create) || !isset($Create) ) { die(\"Sorry, an error occurred during Create.\"); }\n\n/* Build the message, and send it to the user. */\n$to = $Email;\n$subject = 'User account activation | Team Gamers Net';\n$message = '\n&lt;h3&gt;Thank you for registering at Team Gamers Net&lt;/h3&gt;\n&lt;p&gt;Just one more step and that is to activate your account&lt;/p&gt;\n&lt;p&gt;You registred with username '.$Username.'&lt;p&gt;\n&lt;p&gt;And your password you selected (not shown)&lt;/p&gt;\n&lt;p&gt;To activate and contiune, please click &lt;a href=\"http://TeamGamers.net/Activate.php\"&gt;&lt;b&gt;HERE&lt;/b&gt;&lt;/a&gt;&lt;/p&gt;\n';\n$headers = \"From: DoNotReply@TeamGamers.Net \\r\\n\";\n$headers .= \"Reply-To: Admin@heisteknikk.com \\r\\n\";\n$headers .= \"MIME-Version: 1.0\\r\\n\";\n$headers .= \"Content-Type: text/html; charset=ISO-8859-1\\r\\n\";\nmail($to, $subject, $message, $headers);\n\nheader(\"Location: /?register=true\"); \n?&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T01:08:35.307", "Id": "16251", "ParentId": "16246", "Score": "5" } }, { "body": "<p>You have bad security. First of all, <code>base64-&gt;md5-&gt;base64</code> is in no way more secure than <code>md5</code>. In addition, <code>md5</code> is not a cryptographic hash function to be used for passwords, and whatever hash you use, you <strong>need</strong> to salt. Also, following coding conventions will help people critique your code in the future.</p>\n\n<p>I recommend you use <a href=\"http://en.wikipedia.org/wiki/BCrypt\" rel=\"nofollow\">BCrypt</a> or SCrypt, but I'll demonstrate Sha256 here.</p>\n\n<pre><code>// X= function Encrypt($Pass) =X Hashing does NOT equal encrypting\nfunction hash_pass($pass, $salt) {\n return hash(\"sha256\", $pass . $salt);\n}\n\nfunction simple_salt() {\n mt_srand(microtime(true) * 100000 + memory_get_usage(true)); // Don't be scared, all this is doing is adding more entropy to the random seed\n return md5(uniqid(mt_rand(), true));\n}\n\n$salt = simple_salt(); // Store this as well\n$hash = hash_pass($pass, $salt);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T05:34:39.390", "Id": "26434", "Score": "0", "body": "This, times a million. I completely forgot about salting the hash." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T02:52:37.173", "Id": "16255", "ParentId": "16246", "Score": "2" } }, { "body": "<p>This answer is partially an extension of jsanc623's. He did a good job, but I thought I would clarify a few things he missed.</p>\n\n<p>First, There is still a lot of repetition here that can easily be solved by adding a loop or function. For instance, in jsan's answer he is using an unwound loop as a return for the <code>GenerateCode()</code> function. Unwinding loops is really unnecessary in PHP as its performance returns are negligible. Instead, if you used a for loop you could define the amount of random numbers you wished to generate, that way this would be reusable and extensible.</p>\n\n<pre><code>function GenerateCode( $length = 6 ) {\n $return = '';\n\n for( $i = 0; $i &lt; $length; $i++ ) {\n $return .= rand( 1, 9 );\n }\n\n return $return;\n}\n</code></pre>\n\n<p>Also, be wary of your line lengths. For instance, the following line is too long and can cause difficulties in legibility. Add a new line after the opening bracket, and if that isn't enough, don't be afraid to add whitespace and newlines inside the statement too.</p>\n\n<pre><code>if (empty($Username) || empty($Password) || empty($Email)) { die(\"Please fill in all the fields\"); }\n//better\nif (empty($Username) || empty($Password) || empty($Email)) {\n die(\"Please fill in all the fields\");\n}\n//also good\nif (\n empty($Username)\n || empty($Password)\n || empty($Email)\n) {\n die(\"Please fill in all the fields\");\n}\n</code></pre>\n\n<p>Finally, when you have large strings, you can either use heredoc or concatenation. The advantage of heredoc is that you don't have to worry about escaping entities, such as quotation marks, or even simple variables. When using straight concatenation, especially if you are not doing anything between the concatenations, then there is no need to redeclare the variable again and again.</p>\n\n<pre><code>//heredoc\n$message = &lt;&lt;&lt;HTML\n&lt;h3&gt;Thank you for registering at Team Gamers Net&lt;/h3&gt;\n&lt;p&gt;Just one more step and that is to activate your account&lt;/p&gt;\n&lt;p&gt;You registred with username $Username&lt;p&gt;\n&lt;p&gt;And your password you selected (not shown)&lt;/p&gt;\n&lt;p&gt;To activate and contiune, please click &lt;a href=\"http://TeamGamers.net/Activate.php\"&gt;&lt;b&gt;HERE&lt;/b&gt;&lt;/a&gt;&lt;/p&gt;\nHTML;//note that this MUST be unindented\n\n//straight concatenation\n$headers = \"From: DoNotReply@TeamGamers.Net \\r\\n\"\n . \"Reply-To: Admin@heisteknikk.com \\r\\n\"\n . \"MIME-Version: 1.0\\r\\n\"\n . \"Content-Type: text/html; charset=ISO-8859-1\\r\\n\"\n;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T16:40:53.163", "Id": "28023", "Score": "1", "body": "Thanks mseancole! Great points you made - especially the repetition and unwound loop (I've been stuck in opt mode lately it seems). I want to reiterate that the ending of the `heredoc` must NOT be indented - I don't believe you've put enough emphasis there, and god knows how much time I spent scratching my head when first encountering heredocs when I started coding." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T21:52:52.570", "Id": "16376", "ParentId": "16246", "Score": "5" } }, { "body": "<pre><code>function GenerateCode() {\n $R1 = rand(1,9);\n $R2 = rand(1,9);\n $R3 = rand(1,9);\n $R4 = rand(1,9);\n $R5 = rand(1,9);\n $R6 = rand(1,9);\n $C1 = \"$R1$R2$R3$R4$R5$R6\"; // Simple complie method\n return $C1;\n}\n</code></pre>\n\n<p>Can also be written as: </p>\n\n<pre><code>function GenerateCode()\n{\n return rand(100000, 999999);\n}\n</code></pre>\n\n<p>Since the random number generator is seeded automatically this will be just as random as concatenating 6 random generated digits.\nYou can optionally cast the number to a string like</p>\n\n<pre><code>return (string)rand(100000, 999999);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T15:05:58.327", "Id": "16474", "ParentId": "16246", "Score": "2" } }, { "body": "<p>Just adding my 2 cents in here, as I see nobody did this remark. Your code definitely lacks structure and you should get familiar with MVC pattern.</p>\n\n<p>Do not do that mixup of database logic and HTML output in a single file. Use objects to organise your data. </p>\n\n<pre><code>/* Mysql connection data */\n$mysqlUsername = \"root\";\ninclude 'UserModel.php'\n$mysqlPassword = \"**********\";\n$mysqlHostname = \"localhost\";\n$mysqlDatabase = \"teamgamersnet\";\n\n$username = $_POST['Username'];\n$password = $_POST['Password'];\n$email = $_POST['Email'];\n\n$userModel=new UserModel();\n$userModel-&gt;connect($mysqlHostname, $mysqlUsername, $mysqlPassword, $mysqlDatabase);\n$userModel-&gt;addUser($username, $password, $email)\n\n/* Build the message, and send it to the user. */\n$to = $Email;\n$subject = 'User account activation | Team Gamers Net';\n$message = '\n&lt;h3&gt;Thank you for registering at Team Gamers Net&lt;/h3&gt;\n&lt;p&gt;Just one more step and that is to activate your account&lt;/p&gt;\n&lt;p&gt;You registred with username '.$Username.'&lt;p&gt;\n&lt;p&gt;And your password you selected (not shown)&lt;/p&gt;\n&lt;p&gt;To activate and contiune, please click &lt;a href=\"http://TeamGamers.net/Activate.php\"&gt;&lt;b&gt;HERE&lt;/b&gt;&lt;/a&gt;&lt;/p&gt;\n';\n$headers = \"From: DoNotReply@TeamGamers.Net \\r\\n\";\n$headers .= \"Reply-To: Admin@heisteknikk.com \\r\\n\";\n$headers .= \"MIME-Version: 1.0\\r\\n\";\n$headers .= \"Content-Type: text/html; charset=ISO-8859-1\\r\\n\";\nmail($to, $subject, $message, $headers);\nheader(\"Location: /?register=true\"); \n\n\n/* UserModel.php \n * Wraps all your logic (no HTML here)\n*/\n&lt;?php\nclass UserModel {\n\n /* holds a mysql connection */\n private $sqlConnection;\n\n public function connect($mysqlHostname, $mysqlUsername, $mysqlPassword, $mysqlDatabase){\n $this-&gt;sqlConnection= new mysqli($mysqlHostname, $mysqlUsername, $mysqlPassword, $mysqlDatabase);\n if ($this-&gt;sqlConnection-&gt;connect_error){ \n die $this-&gt;sqlConnection-&gt;connect_error; \n }\n }\n public function generateCode() {\n return rand(1,9) . rand(1,9) . rand(1,9) . rand(1,9) . rand(1,9) . rand(1,9);\n }\n\n public function encrypt($pass) { \n return base64_encode( md5( base64_encode($pass) ) ); \n }\n\n public function addUser($username, $password, $email){\n if (empty($username) || empty($password) || empty($email)) { \n die(\"Please fill in all the fields\"); \n }\n /* Escape the user data */\n $sUser = $sqlConnection-&gt;real_escape_string($username);\n $sPass = $sqlConnection-&gt;real_escape_string($password);\n $sMail = $sqlConnection-&gt;real_escape_string($email);\n $xPass = $sqlConnection-&gt;real_escape_string(Encrypt($password));\n\n /* Check if the user exists */\n $checkUser = $sqlConnection-&gt;query(\"SELECT Username FROM `users` WHERE `Username` = '\".$sUser.\"'\");\n $checkMail = $sqlConnection-&gt;query(\"SELECT `E-Mail` FROM `users` WHERE `E-Mail` = '\".$sMail.\"'\");\n if ($checkUser-&gt;num_rows == 1) { \n die(\"Username allready exist\"); \n }\n if ($checkMail-&gt;num_rows == 1) { \n die(\"E-Mail allready exist\"); \n }\n\n /* Generate an activation code */\n $xCode = GenerateCode();\n\n /* Write out the Insert statement */ \n $insert = \"INSERT INTO `teamgamersnet`.`users` (`ID`, `Username`, `Password`, `E-Mail`, `IP`, `Activated`, `ActivateId`) \n VALUES (NULL, '\".$sUser.\"', '\".$xPass.\"', '\".$sMail.\"', '\".$IP.\"', 'false', '\".$xCode.\"');\";\n\n /* Insert the SQL statement */\n $result= $sql-&gt;query($insert);\n if ( empty($result) || !isset($result) ) { \n die(\"Sorry, an error occurred during Create.\"); \n }\n}\n</code></pre>\n\n<p>Here is an idea on how to clean-up a bit of that code, make it easier to understand and mantain.\nThis is only half finished, you can finish separating the concerns after you go through some MVC tutorials. Also there are some coding standards on which you should take a look. You could start <a href=\"http://framework.zend.com/manual/1.12/en/coding-standard.coding-style.html\" rel=\"nofollow\">here</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T23:55:33.400", "Id": "21321", "ParentId": "16246", "Score": "1" } } ]
{ "AcceptedAnswerId": "16376", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T23:15:02.667", "Id": "16246", "Score": "4", "Tags": [ "php" ], "Title": "User register script PHP" }
16246
<p>The following is my wordsearch solving algorithm. I'd greatly appreciate tips on how to improve it (e.g. improve efficiency, better approach, etc.):</p> <pre><code>public boolean traverse(Grid grid) { for (int r = 0; r &lt; grid.getRows(); r++) { for (int c = 0; c &lt; grid.getCols(); c++) { for (Direction direction : Direction.values()) { currentPoint.y = r; currentPoint.x = c; this.direction = direction; if (find(grid, currentPoint, 0)) { for (Point point : consideredPoints) { grid.markLetterAt(point); } return true; } } } } return false; } </code></pre> <p><code>Direction</code> is an enum with all the cardinal directions (N, NE, S, NW, etc...). It has a method (<code>updatePoint()</code>) which changes a <code>Point</code> to the direction (e.g. NE does <code>point.y -= 1</code>, <code>point.x += 1</code>)</p> <p>Here is <code>find</code>:</p> <pre><code>private boolean find(Grid grid, Point point, int count) { if (!grid.isValidLetter(point)) { // Checks if the point is valid (e.g not &lt; 0) consideredPoints.clear(); return false; } if (grid.getLetterAt(point).equals(word.substring(count, count + 1))) { consideredPoints.add(new Point(point)); if (count == word.length() - 1) { return true; } direction.updatePoint(point); return find(grid, point, count + 1); } consideredPoints.clear(); return false; } </code></pre>
[]
[ { "body": "<ul>\n<li>You are creating lots of Point() objects. For performance optimization in Java the very first thing is to avoid pressure on the garbage collector.</li>\n<li>You are doing lots of repeated calculations just for traversing the grid (in several directions). Performance wise it would be much better to <em>transform the whole grid</em> in advance to simplify the traversal calculation. E.g. it is very simple to search only words in East direction in a grid. And searching words in West direction could then be done by mirroring the grid against a vertical axis and searching again in East direction only.</li>\n<li>For just finding words, you can ignore the grid structure entirely. Take the complete first row as String, append a space, append the complete second row as String and so forth. You get one huge string representing the grid for searching in East direction. Your matching code is simply <code>hugeString.contains(searchWord)</code> (with a bit more complicated calculation of the original row and column information). You can do the same transformation from grid to a single String also for all other directions.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T06:02:10.333", "Id": "16293", "ParentId": "16252", "Score": "5" } } ]
{ "AcceptedAnswerId": "16293", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T01:20:30.190", "Id": "16252", "Score": "2", "Tags": [ "java", "optimization" ], "Title": "Word Search solving algorithm" }
16252
<p>I have the below function, it is designed so I can call:</p> <pre><code>$object-&gt;temp('one', 1); //add the key `one` to the temp array with value 1 $object-&gt;temp('two', 2); //add the key `two` to the temp array with value 2 $object-&gt;temp('three', 3); //add the key `three` to the temp array with value 3 $object-&gt;temp('three'); //returns 3 $object-&gt;temp('three', null); //removes the `three` key $object-&gt;temp(); //returns array('one' =&gt; 1, 'two' =&gt; 2) </code></pre> <p>and it works well, my only gripe is that I don't like using the <code>$value = 'read_temp</code> in the definition, it feels like a hack to me.</p> <p>So, is there anything wrong with that, and how can this function be optimized?</p> <pre><code>public function temp($key = null, $value = 'read_temp') { if($key === null) return $this-&gt;temp; if ($value === null){ unset($this-&gt;temp[$key]); } elseif ($value == 'read_temp' &amp;&amp; isset($this-&gt;temp[$key])) { $value = $this-&gt;temp[$key]; } else { $this-&gt;temp[$key] = $value; } return $value; } </code></pre> <p>I could split this into two <code>setTemp</code> <code>getTemp</code> (or three <code>clearTemp</code> to be pedantic) functions, but I would like to be able to have just one function call to do everything.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T09:16:28.950", "Id": "26435", "Score": "0", "body": "What is you actual reasoning to not split it into different functions? It would be much more readable to future coders. Depending on your object you could even use overloading http://www.php.net/manual/en/language.oop5.overloading.php" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T09:41:19.710", "Id": "26436", "Score": "0", "body": "more or less my reason is that, temp is a temporary storage on that instance of the object, it is a tiny, almost \"bootstrap\" part of the actual class, so I want to keep it as just one small interface instead of 2/3." } ]
[ { "body": "<p>Here's one way to do it</p>\n\n<pre><code>public function temp($key = null , $value = null) {\n $args = func_get_args();\n if( count($args) === 2 ) {\n $this-&gt;temp[$key] = $value;\n } elseif( count($args) === 1 ) {\n return @$this-&gt;temp[$key];\n } else {\n return $this-&gt;temp;\n }\n}\n</code></pre>\n\n<p><code>func_get_args()</code> will return an array of the arguments that were actually passed - i.e. excluding default values. So if no arguments were passed, return the array; if there's 1 argument (the key), return the corresponding value; and if there are 2 arguments, set the key/value pair.</p>\n\n<p>I'm using the warning-suppression <code>@</code> instead of explicitly checking <code>isset()</code>. Again, the end result is the same; if you check with <code>isset()</code> and don't (explicitly) return anything for missing keys, the function still returns NULL. If you simply return <code>$this-&gt;temp[$key]</code>with no checking, but suppress the \"undefined index\" warning that might occur, you also get NULL.</p>\n\n<p>I've also skipped the <code>unset()</code> call, since calling <code>$obj-&gt;tmp(\"key\", null)</code> does pretty much the same thing. If you request a value that hasn't been set, you get NULL. If you set that value to NULL, you get NULL. If you were to unset the value, you'd also get NULL.<br>\nBut if you want to keep the unset, you can just check <code>$value === null</code> in the first branch:</p>\n\n<pre><code>if( count($args) === 2 ) {\n if( $value === null ) {\n unset($this-&gt;temp[$key]);\n } else {\n $this-&gt;temp[$key] = $value;\n }\n} // ...\n</code></pre>\n\n<p>If you skip the <code>unset()</code> part, it'll obviously keep the array keys around, so you won't know for sure if a key whose value is NULL was \"deleted\", or if it was explicitly set to NULL on purpose.<br>\nOn the other hand, if you <code>unset()</code> when the passed value is NULL, you won't be able to set a value to NULL on purpose.</p>\n\n<p>The simplest solution is to not use <code>unset</code> in the <code>temp()</code> function, but instead add an extra <code>unset_temp_value($key)</code> function that does the unset. Then you can use that to explicitly remove all traces of a key/value pair, while still being able to store NULLs \"on purpose\" using <code>temp($key, null)</code>.</p>\n\n<hr>\n\n<p>As mseancole points out below, a <code>switch</code> statement could be used too</p>\n\n<pre><code>public function temp($key = null, $value = null) {\n $args = func_get_args();\n switch( count($args) ) {\n case 2:\n return $this-&gt;temp[$key] = $value;\n case 1:\n return @$this-&gt;temp[$key];\n default:\n return $this-&gt;temp;\n }\n}\n</code></pre>\n\n<p>Only difference is that this returns the value that's set in the first case (just because it's more compact then <code>break</code>ing)</p>\n\n<p>And just for fun, here's the same thing again in Unreadable Mode™</p>\n\n<pre><code>public function temp($key = null, $value = null) {\n $args = count(func_get_args());\n return ($args==2?($this-&gt;temp[$key]=$value):($args==1?@$this-&gt;temp[$key]:$this-&gt;tmp));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T13:35:45.033", "Id": "26441", "Score": "0", "body": "Cheers, just what I was looking for, but; I loathe the silence operator! so much infact that I have this set on my dev server; `ini_set('scream.enabled', true);` so I shall be using isset ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T13:38:52.923", "Id": "26442", "Score": "0", "body": "@Hailwood Heh, fair enough :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T21:25:06.450", "Id": "26636", "Score": "0", "body": "@Hailwood: Just a couple of things to add to Flambino's post. **1** Why are your statements inconsistent? You are using braceless and braced code interchangeably. I honestly don't think braceless should be used at all, being as how PHP does not completely support support it, but you should at the very least be consistent. **2** A switch statement might be more appropriate in Flambino's example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T22:16:45.363", "Id": "26640", "Score": "0", "body": "@mseancole Good point regarding `switch`, I'll add it to my answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T23:00:39.157", "Id": "26644", "Score": "0", "body": "(Warning: annoying literalness incoming.) @mseancole I understand what you mean, and agree with your sentiments, but \"PHP does not completely support [braceless syntax]\" is not true. PHP supports it perfectly. Its behavior is well defined, yatta yatta. Ease of misuse and lack of support are not the same thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T00:24:36.367", "Id": "26647", "Score": "0", "body": "@Corbin: If it fully supported braceless syntax we would not have to add braces after one line. It *is* inherently required. The half-assed version that PHP has implemented is just wrong and, imho, promotes bad habits. Just because you can do something doesn't mean you should, especially if it completely deviates from everything else. Sorry for the mini-rant, I just find this feature offensive. If PHP decides to fully implement pure braceless syntax, I will revisit this opinion, in the mean time, if you want to code this way, Python and Ruby are good alternatives. Sorry that sounds harsh." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T01:33:24.227", "Id": "26650", "Score": "0", "body": "@mseancole +1 for stressing consistency; Corbin +1 for pointing out that PHP's behavior _is_ well-defined (just ill-conceived); mseancole +1 for generally ranting on PHP. I may have answered the question, but, man, I'm glad my PHP days are behind me. (Disclaimer: Subjective opinion.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T02:20:02.370", "Id": "26652", "Score": "0", "body": "@mseancole The problem isn't PHP; it's your understanding of it. Look at any brace based language, and it's the same. The only reason Python is that way is because it is whitespace block-based. PHP's treatment of a lack of braces is just like any other brace-block-based language that has been influenced by C (C/C++/Java/C#/JavaScript/etc). (Disclaimer: Am not familiar with how braces work in Ruby, so maybe it does do something more logical. Also, \"influenced by C\" being directly related to braces is debatable, but hopefully the point got across.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T02:20:46.953", "Id": "26653", "Score": "0", "body": "@mseancole And for what it's worth, I'm a very strong advocate of always using braces. I don't think I've ever written an if statement without braces. It just irks the pedantic side of me to see PHP's handling called \"incomplete\" when it's not." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T12:18:58.140", "Id": "16263", "ParentId": "16257", "Score": "4" } } ]
{ "AcceptedAnswerId": "16263", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T06:55:14.207", "Id": "16257", "Score": "2", "Tags": [ "php" ], "Title": "Single function to read one, read all, or set" }
16257
<p>I sat down to write a demo HTML5-ish page that lets a user to perform following operations on a canvas - draw lines, draw a filled rectangle, and reset the canvas. Each operation is represented by a button, clicking on which the operation is carried out.</p> <p>My initial attempt ended up as a mingled HTML and JavaScript code. So, after a bit of reading, I used the <code>addEventListener()</code> method to add the events to the buttons, thus eliminating the onclick code in HTML.</p> <p>Now, I followed two approaches while writing the JavaScript code.</p> <p>The first, simpler approach:</p> <pre><code>// Instead of forcing all event handlers to know the canvasId by themselves, I chose to hardwire it in window.onload() function, inside which I also add the event handlers to their respective buttons. // I need to pass canvasId to the event handlers, thus forcing me to write anonymous functions. // I won't have a future reference to the event handlers unless, of course, I store them in variables, which I find clumsy. window.onload = function() { var canvasId = "DrawingBoard"; var rectangleButton = document.getElementById("rectangleButton"); rectangleButton.addEventListener("click", function() { drawFilledRectangle(canvasId); }, false); var linesButton = document.getElementById("linesButton"); linesButton.addEventListener("click", function() { drawLines(canvasId); }, false); var resetButton = document.getElementById("resetButton"); resetButton.addEventListener("click", function() { resetCanvas(canvasId); }, false); } function drawFilledRectangle(canvasId) { resetCanvas(canvasId); var canvas = document.getElementById(canvasId); var context = canvas.getContext("2d"); context.fillStyle = "#eee"; context.fillRect(50, 25, 150, 120); } function drawLines(canvasId) { resetCanvas(canvasId); var canvas = document.getElementById(canvasId); var context = canvas.getContext("2d"); for (var x = 0.5; x &lt; canvas.width; x += 10) { context.moveTo(x, 0); context.lineTo(x, canvas.height - 1); } context.strokeStyle = "#eee"; context.stroke(); } function resetCanvas(canvasId) { var canvas = document.getElementById(canvasId); var context = canvas.getContext("2d"); context.clearRect(0, 0, canvas.width, canvas.height); } </code></pre> <p>The second approach:</p> <pre><code>// I don't need to pass canvasId to each event handler. // This way, I don't have to create anonymous functions, meaning that I always have a reference to the function - the function name. // The structure still makes sense; this way, I have grouped the canvas operations along with the canvas id in a single namespace. // Whatever you need to do with canvas, you can just add a function to the object literal CanvasOperations. window.onload = function() { var rectangleButton = document.getElementById("rectangleButton"); rectangleButton.addEventListener("click", CanvasOperations.drawFilledRectangle, false); var linesButton = document.getElementById("linesButton"); linesButton.addEventListener("click", CanvasOperations.drawLines, false); var resetButton = document.getElementById("resetButton"); resetButton.addEventListener("click", CanvasOperations.resetCanvas, false); } var CanvasOperations = { canvasId : "DrawingBoard", resetCanvas : function() { var canvas = document.getElementById(CanvasOperations.canvasId); var context = canvas.getContext("2d"); context.clearRect(0, 0, canvas.width, canvas.height); }, drawLines : function() { CanvasOperations.resetCanvas(CanvasOperations.canvasId); var canvas = document.getElementById(CanvasOperations.canvasId); var context = canvas.getContext("2d"); for (var x = 0.5; x &lt; canvas.width; x += 10) { context.moveTo(x, 0); context.lineTo(x, canvas.height - 1); } context.strokeStyle = "#eee"; context.stroke(); }, drawFilledRectangle : function() { CanvasOperations.resetCanvas(CanvasOperations.canvasId); var canvas = document.getElementById(CanvasOperations.canvasId); var context = canvas.getContext("2d"); context.fillStyle = "#eee"; context.fillRect(50, 25, 150, 120); } }; </code></pre> <p>Note that I have provided my reasoning of both the approaches in their respective comments.</p> <ol> <li><p>Which approach is better?</p></li> <li><p>Are my reasons to lean towards the second one right?</p></li> <li><p>What approach should I take while using attributes like <code>id</code> or name of HTML elements in JavaScript code?</p></li> </ol> <p>I think hardwiring should be as less as possible. Is there anything you can point me to for learning? Or is it just intuition thing, to be decided by me? I did Google on this, but couldn't find a right solution; or I might have failed to frame a proper Google search.</p>
[]
[ { "body": "<p>The second one is indeed \"better\", in my opinion. Although, \"better\" is a bit hard to define when both versions work. \"More maintainable\" might be a more precise way of putting it.</p>\n\n<p>I might take it a step further, and add a constructor (i.e. class) that wraps the canvas element:</p>\n\n<pre><code>function DrawingCanvas(elementId) {\n this.element = document.getElementById(elementId);\n this.context = this.element.getContext(\"2d\");\n}\n\nDrawingCanvas.prototype = {\n reset: function () {\n this.context.clearRect(0, 0, this.element.width, this.element.height);\n },\n\n drawLines: function () { ... draw stuff ... },\n drawFilledRectangle: function () { ... draw different stuff ... },\n};\n</code></pre>\n\n<p>I'd also use <code>addEventListener</code> for the <code>onload</code> event:</p>\n\n<pre><code>window.addEventListener(\"load\", function () {\n var canvas = new DrawingCanvas(\"DrawingBoard\");\n document.getElementById(\"rectangleButton\").addEventListener(\"click\", canvas.drawFilledRectangle, false);\n document.getElementById(\"linesButton\").addEventListener(\"click\", canvas.drawLines, false);\n document.getElementById(\"resetButton\").addEventListener(\"click\", canvas.reset, false);\n}, false);\n</code></pre>\n\n<p>Finally, a word of general advice: Don't use the \"curly bracket on new line\"-style in JavaScript.<br>\nJavaScript has some dumb parts to it, and one of them is that it'll <em>automatically insert a semi-colon</em> at the end of a line, if it <em>thinks</em> it's missing.</p>\n\n<p>So, if you for instance have a function that returns an object literal, you can get into trouble:</p>\n\n<pre><code>function getObj() {\n return\n {\n x: 42\n }\n}\n</code></pre>\n\n<p>will be interpreted as</p>\n\n<pre><code>function getObj() {\n return; // &lt;- auto semi-colon\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T08:57:31.893", "Id": "26468", "Score": "0", "body": "Yeah. I had wanted to imply \"more maintainable\" by \"better\"; the right word just hadn't come to the sleepy brain. :-)\nYou are right about addEventListener() for window's onload, too; it's just that my main focus was the Canvas object.\nI will certainly read more about the constructor function; I bet that will be useful in future." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T08:58:39.240", "Id": "26469", "Score": "0", "body": "I wasn't aware of the parsing style of JavaScript. I read a bit on it after reading your braces issue. It seems I will have to drop my all-time favorite brace-on-new-line style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T10:41:05.697", "Id": "26472", "Score": "0", "body": "@MrBhoot Brace-on-new-line has _always_ been evil and wrong! Just kidding :) - you could also look into [CoffeeScript](http://coffeescript.org), which compiles to JS, but where you almost never use curlies, and there are structures such as `class` that translate to JS's constructors/prototypes. But first, read Douglas Crockford's \"JavaScript: The Good Parts\" if you want to dig deeper." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T05:48:22.793", "Id": "26505", "Score": "0", "body": "As you directed, I had a look at CoffeeScript; impressive, indeed! But I will concentrate on pure JavaScript for now, along with a library like jQuery. CoffeeScript - maybe some time later. :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T08:26:19.500", "Id": "26509", "Score": "0", "body": "@MrBhoot Excellent choice! While you can use jQuery or anything other JS library, and simply write your own code in CoffeeScript (it _is_ JS after all, just a different syntax), there's no substitute for _really_ learning pure JS first. Depending on what you're used it, JS has some strange, strange stuff in it (again, I can recommend googling for Douglas Crockford; you can find videos of his talks on the subject). Once you feel you \"get it\", CoffeeScript is a great next step." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T12:56:22.023", "Id": "16264", "ParentId": "16259", "Score": "2" } } ]
{ "AcceptedAnswerId": "16264", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T10:23:25.883", "Id": "16259", "Score": "2", "Tags": [ "javascript", "comparative-review", "html5", "canvas" ], "Title": "Two JavaScript snippets to allow drawing on a canvas" }
16259
<p>I have this function in my application that I need to simplify in order to improve the code quality:</p> <pre><code>void FilterValues() { List&lt;SecondaryStockRoomDefenition&gt; GridViewItems = new List&lt;SecondaryStockRoomDefenition&gt;(); GridViewItems = StockRooms.ToList(); if (cboPrimaryStockRoom.SelectedValue.ToString().Trim() != "0") { GridViewItems = StockRooms.Where((SecondaryStockRoomDefenition, index) =&gt; GridViewItems[index].DeletedSecondaryStockRoom == false &amp;&amp; GridViewItems[index].PrimaryStockroomCode == cboPrimaryStockRoom.SelectedValue.ToString().Trim()).ToList(); } if( txtSecondaryStockRoomCode.Text != "" ) { GridViewItems = GridViewItems.Where((SecondaryStockRoomDefenition,index) =&gt; GridViewItems[index].DeletedSecondaryStockRoom == false &amp;&amp; GridViewItems[index].SecondaryStockroomCode == txtSecondaryStockRoomCode.Text.Trim()).ToList(); } if (txtSecondaryStockRoomName.Text != "") { GridViewItems = GridViewItems.Where((SecondaryStockRoomDefenition, index) =&gt; GridViewItems[index].DeletedSecondaryStockRoom == false &amp;&amp; GridViewItems[index].SecondaryStockroomDescription.Contains(txtSecondaryStockRoomName.Text.Trim())).ToList(); } if (txtStockRoomLocationCode.Text != "") { GridViewItems = GridViewItems.Where((SecondaryStockRoomDefenition, index) =&gt; GridViewItems[index].DeletedSecondaryStockRoom == false &amp;&amp; GridViewItems[index].SecondaryStockroomLocationCode == txtStockRoomLocationCode.Text.Trim()).ToList(); } if (cboStockRoomCategory.SelectedValue.ToString().Trim() != "0") { GridViewItems = GridViewItems.Where((SecondaryStockRoomDefenition, index) =&gt; GridViewItems[index].DeletedSecondaryStockRoom == false &amp;&amp; GridViewItems[index].SecondaryStockroomCategory == cboStockRoomCategory.SelectedValue.ToString().Trim()).ToList(); } if (txtStockRoomType.Text != "") { GridViewItems = GridViewItems.Where((SecondaryStockRoomDefenition, index) =&gt; GridViewItems[index].DeletedSecondaryStockRoom == false &amp;&amp; GridViewItems[index].SecondaryStockroomType == txtStockRoomType.Text.Trim()).ToList(); } if (cboExpectedUserName.SelectedValue.ToString().Trim() != "0") { GridViewItems = GridViewItems.Where((SecondaryStockRoomDefenition, index) =&gt; GridViewItems[index].DeletedSecondaryStockRoom == false &amp;&amp; GridViewItems[index].ExpectedUserNameForCommissionEntry == cboExpectedUserName.SelectedValue.ToString().Trim()).ToList(); } dgvCompanyProfileDetails.DataSource = null; dgvCompanyProfileDetails.Rows.Clear(); dgvCompanyProfileDetails.DataSource = GridViewItems; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T17:45:15.573", "Id": "26798", "Score": "1", "body": "One tiny point: you may consider either switching your \"\"s with string.Empty, or (better yet) changing the checks to string.IsNullOrEmpty(string)/string.IsNullOrWhiteSpace(string)." } ]
[ { "body": "<p>Just a few things from me:</p>\n\n<ol>\n<li><p>Check the way you name variables. Local variables by defacto standard are lower case camel. See here for more details <a href=\"http://msdn.microsoft.com/en-us/library/xzf533w0%28v=vs.71%29.aspx\" rel=\"nofollow\">Microsoft naming conventions</a>.</p>\n\n<p><code>GridViewItems</code> becomes <code>gridViewItems</code></p></li>\n<li><p>I personally try to use implicit local variables where the type is obvious. This is more a personal preference but Microsoft do recommend as well. See <a href=\"http://msdn.microsoft.com/en-us/library/ff926074.aspx\" rel=\"nofollow\">C# coding conventions</a> for more details.</p></li>\n<li><p>If <code>gridViewItems</code> is going to be assigned to stockrooms immediately, why not just do straight off the cuff?</p>\n\n<pre><code>var gridViewItems = StockRooms.ToList();\n</code></pre></li>\n<li><p>I would convert this method into a bunch of smaller functions. Perhaps something like (excuse any compile options as I could not fully test this code):</p>\n\n<pre><code>void FilterValues()\n{\n dgvCompanyProfileDetails.DataSource = null;\n dgvCompanyProfileDetails.Rows.Clear();\n dgvCompanyProfileDetails.DataSource = Filter(StockRooms).ToList();\n}\n\nprivate IEnumerable&lt;SecondaryStockRoomDefenition&gt; Filter(IEnumerable&lt;SecondaryStockRoomDefenition&gt; stockRooms)\n{\n // filter the stock rooms on each function call\n stockRooms = FilterStockRooms(stockRooms, cboPrimaryStockRoom, p =&gt; p.PrimaryStockroomCode);\n stockRooms = FilterStockRooms(stockRooms, txtSecondaryStockRoomCode.Text, p =&gt; p.SecondaryStockroomCode);\n stockRooms = FilterStockRooms(stockRooms, txtSecondaryStockRoomName.Text, (p, v) =&gt; p.SecondaryStockroomDescription.Contains(v));\n stockRooms = FilterStockRooms(stockRooms, txtStockRoomLocationCode.Text, p =&gt; p.SecondaryStockroomLocationCode);\n // .. etc\n\n return stockRooms;\n}\n\nprivate IEnumerable&lt;SecondaryStockRoomDefenition&gt; FilterStockRooms(IEnumerable&lt;SecondaryStockRoomDefenition&gt; rooms, ComboBox combo, Func&lt;SecondaryStockRoomDefenition, string&gt; filter)\n{\n var value = combo.SelectedValue.ToString();\n\n return HasValue(value, \"0\") ? FilterStockRooms(rooms, v =&gt; filter(v).Equals(value, StringComparison.InvariantCultureIgnoreCase)) : rooms; \n}\n\nprivate IEnumerable&lt;SecondaryStockRoomDefenition&gt; FilterStockRooms(IEnumerable&lt;SecondaryStockRoomDefenition&gt; rooms, string text, Func&lt;SecondaryStockRoomDefenition, string&gt; filter)\n{\n return HasValue(text) ? FilterStockRooms(rooms, v =&gt; filter(v).Equals(text, StringComparison.InvariantCultureIgnoreCase)) : rooms;\n}\n\nprivate IEnumerable&lt;SecondaryStockRoomDefenition&gt; FilterStockRooms(IEnumerable&lt;SecondaryStockRoomDefenition&gt; rooms, string text, Func&lt;SecondaryStockRoomDefenition, string, bool&gt; filter)\n{\n return HasValue(text) ? FilterStockRooms(rooms, v =&gt; filter(v, text)) : rooms;\n}\n\n// The question marks are because I wasn't sure of the StockRooms type\nprivate IEnumerable&lt;SecondaryStockRoomDefenition&gt; FilterStockRooms(IEnumerable&lt;SecondaryStockRoomDefenition&gt; rooms, Func&lt;SecondaryStockRoomDefenition, bool&gt; filter)\n{\n return rooms.Where(p =&gt; p.DeletedSecondaryStockRoom == false &amp;&amp; filter(p));\n}\n\nprivate bool HasValue(string value)\n{\n return !string.IsNullOrWhiteSpace(value);\n}\n\nprivate bool HasValue(string value, string compareTo)\n{\n return HasValue(value) &amp;&amp; value.Trim() != compareTo;\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T19:29:46.727", "Id": "26800", "Score": "0", "body": "@JorisG Just wondering on the edits. Why would you ToList() the object going into the method and then ToList() it again on the way out? Would it not be best to only do it once at whichever stage you choose and potentially work with IEnumerable all the way though until the end?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T07:18:38.507", "Id": "27910", "Score": "0", "body": "Of course you're right, Filter(StockRooms).ToList() in the first method is probably the only one required. I looked over that. I would keep it on before the assignment to the datasource, the give it a fixed number of instances, because every time it queries the collection, it will have to re-evaluate all the applied filters." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T19:20:32.630", "Id": "16272", "ParentId": "16262", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T11:43:39.293", "Id": "16262", "Score": "6", "Tags": [ "c#" ], "Title": "Filtering values for GridViewItems" }
16262
<p>I have a N*N upper triangular matrix with property such that, all its diagonal elements are a1,a2,a3,...,aN. I want that a[i][j] (for all j>i) should be</p> <pre><code>(a[i][j-1] + a[i+1][j]) / 2. </code></pre> <p>I have many test cases, and I have to apply this property every time to calculate the answer. What is the most optimal way to do this, so that for all test cases the overall running time is less? Test cases: Inputs are N and a1,a2,...,aN.</p> <p>To calculate the answer, I need to do:</p> <pre><code>a[0][0] + a[0][2] + ... + a[0][n-1] + a[2][n-1] + a[4][n-1] + ... + a[n-1][n-1]. </code></pre> <p>My solution (which keeps getting timed out):</p> <pre><code>#include&lt;stdio.h&gt; double a[2000][2000]; int main(){ int test; scanf("%d",&amp;test); //int arr[2000]; while(test--){ int n,i,j; //scanf("%d",&amp;n); scanf("%d",&amp;n); for(i=0;i&lt;n;i++){ int num; scanf("%d",&amp;num); if(n!=1) a[i][i] = num*0.5; else a[i][i] = num; } for(j=1;j&lt;n;j++){ int k=j; for(i=0;i&lt;n-j;i++,k++){ if(i==0 &amp;&amp; k==n-1) a[i][k] = (a[i+1][k]+a[i][k-1]); else a[i][k] = (a[i+1][k]+a[i][k-1])*0.5; } } float sum=0.0; for(i=0;i&lt;n;i+=2){ if( i != n-1 ) sum+=a[0][i]+a[n-1-i][n-1]; else sum+=a[0][i]; } printf("%.3f\n",sum); } getch(); } </code></pre> <p>Please provide some hints how to optimize the above code.</p>
[]
[ { "body": "<p>I suggest dropping the floating point and doing it fixed point. To do this I\nwould make <code>a[][]</code> of type <code>int</code> or <code>short</code> (depending upon the input\nconstraints) and instead of storing values x and x * 0.5, store 2x and x\nrespectively. At the end of the summation you can then divide by 2 to get the\ntrue result.</p>\n\n<p>The only issue this raises is that of integer overflow. You don't state any\nnumerical constraints but the fixed size arrays (2000x2000) suggest overflow\nwill not occur with <code>long long</code>. Alternatively the summation itself could be\nfloating point while the array values remain integers. I notice that your\ncurrent summation uses <code>float</code> which might well be slower than <code>double</code>.</p>\n\n<p>Another minor point where you can improve the speed is in the input loop. You\nhave the conditional</p>\n\n<pre><code>if(n!=1)\n a[i][i] = num*0.5;\nelse\n a[i][i] = num;\n</code></pre>\n\n<p>As the loop variable <code>i</code> goes from 0 to <code>n</code>, if <code>n</code> is 1 then the loop only\nfills a[0][0] and so this conditional can be removed from the loop. But if n\nis small this will make little difference.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-06T03:00:04.293", "Id": "36747", "ParentId": "16265", "Score": "6" } }, { "body": "<p>@WilliamMorris had some good points on improving your code. I have a few things to add though.</p>\n\n<p>There is an implicit declaration of function <code>getch()</code> in your code, which is invalid in C99.</p>\n\n<pre><code>#include &lt;conio.h&gt; // on Linux\n#include &lt;curses.h&gt; // on Mac\n</code></pre>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/questions/814975/getch-is-deprecated\"><code>getch()</code> is (technically) deprecated.</a> It is still okay to use it, but I prefer <code>getchar()</code> instead. You also get rid of a dependency, which means your code will work on more systems (with <code>getch()</code>, your code would not work on my computer, but with <code>getchar()</code> it did).</p>\n\n<hr>\n\n<p>You don't check if your input is actually an <code>int</code>. That could lead to invalid input, and since your program isn't built to handle that it is considered a security flaw.</p>\n\n<pre><code>if (!isdigit(n))\n{\n printf(\"Invalid input.\\n\");\n return -1; // returning is kind of drastic.\n // It's better to let the user re-enter valid input in a loop. \n // I'll let you implement that in your code though if you deem it necessary\n}\n</code></pre>\n\n<p>With the addition of <code>isdigit()</code>, we will have to add a header.</p>\n\n<pre><code>#include &lt;ctype.h&gt;\n</code></pre>\n\n<p>Many systems support <code>&lt;ctype.h&gt;</code>, so while it is a dependency, it is minor and necessary.</p>\n\n<hr>\n\n<p>Everything feels very squished in your code with lack of whitespace. Let's add some space to let your code <em>breathe</em> and make it more readable. Don't take this too far though, because too much whitespace can also make your code unreadable. The place where I see this is needed the most is the adding of matrices.</p>\n\n<pre><code>sum+=a[0][i]+a[n-1-i][n-1]; // Takes a bit to read and understand\nsum += a[0][i] + a[n-1-i][n-1]; // Eases the reading and understanding process a bit.\n</code></pre>\n\n<hr>\n\n<p>Your variable names make this program a bit obfuscated in it's current stance. The variable names are somewhat acceptable in this case though, since you are dealing which the indexes of matrices, which are hard to give proper names.</p>\n\n<hr>\n\n<p>Final code:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;ctype.h&gt;\n\ndouble a[2000][2000];\nint main()\n{\n int test;\n scanf(\"%d\", &amp;test);\n if (!isdigit(test))\n {\n printf(\"Invalid input.\\n\");\n return -1;\n }\n while (test--)\n {\n int n, i, j;\n scanf(\"%d\", &amp;n);\n if (!isdigit(n))\n {\n printf(\"Invalid input.\\n\");\n return -1;\n }\n for (i=0; i&lt;n; i++)\n {\n int num;\n scanf(\"%d\", &amp;num);\n if (!isdigit(num))\n {\n printf(\"Invalid input.\\n\");\n return -1;\n }\n if (n !=1 ) a[i][i] = num * 0.5;\n else a[i][i] = num;\n }\n for (j=1; j&lt;n; j++)\n {\n int k = j;\n for(i=0; i &lt; n-j; i++, k++)\n {\n if(i == 0 &amp;&amp; k == n-1) a[i][k] = (a[i+1][k] + a[i][k-1]);\n else a[i][k] = (a[i+1][k] + a[i][k-1])*0.5;\n }\n }\n float sum = 0.0;\n for (i=0; i&lt;n; i+=2)\n {\n if( i != n-1 ) sum += a[0][i] + a[n-1-i][n-1];\n else sum += a[0][i];\n }\n printf(\"%.3f\\n\", sum);\n getchar();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-04T23:32:25.420", "Id": "38598", "ParentId": "16265", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T13:04:28.800", "Id": "16265", "Score": "10", "Tags": [ "c", "algorithm", "matrix", "floating-point" ], "Title": "How to increase efficiency of matrix operation in C?" }
16265
<p>I am learning Java Collections Framework. Can someone look at this code for <em>generating all subsets of a given set</em> and tell me any issues with it.</p> <pre><code>import java.util.*; public class AllSubsets { public static void main(String[] args) { Set&lt;Integer&gt; original = new HashSet&lt;Integer&gt;(); for (int i = Integer.parseInt(args[0]); i &gt; 0; i--) { original.add(i); } System.out.println(generateAllSubsets(original)); } public static HashSet&lt;HashSet&lt;Integer&gt;&gt; generateAllSubsets(Set&lt;Integer&gt; original) { HashSet&lt;HashSet&lt;Integer&gt;&gt; allSubsets = new HashSet&lt;HashSet&lt;Integer&gt;&gt;(); allSubsets.add(new HashSet&lt;Integer&gt;()); //Add empty set. Iterator it = original.iterator(); while(it.hasNext()) { Integer element = (Integer) it.next(); //Deep copy all subsets to temporary power set. HashSet&lt;HashSet&lt;Integer&gt;&gt; tempClone = new HashSet&lt;HashSet&lt;Integer&gt;&gt;(); for (HashSet&lt;Integer&gt; subset : allSubsets) { tempClone.add((HashSet&lt;Integer&gt;)subset.clone()); } //All element to all subsets of the temporary power set. Iterator it2 = tempClone.iterator(); while(it2.hasNext()) { Set&lt;Integer&gt; s = (HashSet&lt;Integer&gt;) it2.next(); s.add(element); } //Merge both power sets. allSubsets.addAll(tempClone); } return allSubsets; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T17:47:18.867", "Id": "26446", "Score": "0", "body": "you use vague algorithm, so no one wish to decrypt and and thus you received no answer. To represent a subset, usually an integer in binary representation is used: 0 in a given position means element is absent, 1 - present. To generate all subsets, start with 0 and add 1, counting all integers up to 2^N-1. If you have less than 64 elements, you can use `long` integer, other wise use BitSet, and implement operation of adding 1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T17:48:58.873", "Id": "26447", "Score": "0", "body": "@AlexeiKaigorodov, how can an implementation in an actual language be a \"vague algorithm\"? Pseudocode can be vague, but this isn't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-02T20:17:33.487", "Id": "64066", "Score": "0", "body": "[Guava](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Sets.html#powerSet(java.util.Set)) has same kind of method and check also in [SO](http://stackoverflow.com/questions/1670862/obtaining-powerset-of-a-set-in-java)" } ]
[ { "body": "<p>The first, obvious, issue is that generating the set in memory uses a lot of memory. However, making a lazy version is a bit more advanced, so don't worry about it for now.</p>\n\n<h3>1. Code to the interface, not the implementation</h3>\n\n<pre><code>public static HashSet&lt;HashSet&lt;Integer&gt;&gt; generateAllSubsets(Set&lt;Integer&gt; original) {\n</code></pre>\n\n<p>is bad.</p>\n\n<pre><code>public static Set&lt;Set&lt;Integer&gt;&gt; generateAllSubsets(Set&lt;Integer&gt; original) {\n</code></pre>\n\n<p>is better.</p>\n\n<h3>2. Generics reduce repetition</h3>\n\n<pre><code>public static &lt;T&gt; Set&lt;Set&lt;T&gt;&gt; generateAllSubsets(Set&lt;T&gt; original) {\n</code></pre>\n\n<p>is better still, because you can use it to find power sets of any set.</p>\n\n<h3>3. Generics remove the necessity to do most casts</h3>\n\n<pre><code> Iterator it = original.iterator();\n while(it.hasNext()) {\n Integer element = (Integer) it.next();\n</code></pre>\n\n<p>and</p>\n\n<pre><code> Iterator it2 = tempClone.iterator();\n while(it2.hasNext()) {\n Set&lt;Integer&gt; s = (HashSet&lt;Integer&gt;) it2.next();\n</code></pre>\n\n<p>have wholly unnecessary explicit casts (which in the second case generates a warning) because you're using the raw type <code>Iterator</code>. Both can also be simplified using the same <code>foreach</code> syntax which you use when making the copy of the power set so far.</p>\n\n<h3>4. KISS</h3>\n\n<p>You have three loops (including the one hidden behind <code>allSubsets.addAll</code>), which seems to me to be unnecessarily complicated. If you make a shallow copy first then you can combine the deep copy with the adding an element.</p>\n\n<pre><code>public static &lt;T&gt; Set&lt;Set&lt;T&gt;&gt; generateAllSubsets(Set&lt;T&gt; original) {\n Set&lt;Set&lt;T&gt;&gt; allSubsets = new HashSet&lt;Set&lt;T&gt;&gt;();\n\n allSubsets.add(new HashSet&lt;T&gt;()); //Add empty set.\n\n for (T element : original) {\n // Copy subsets so we can iterate over them without ConcurrentModificationException\n Set&lt;Set&lt;T&gt;&gt; tempClone = new HashSet&lt;Set&lt;T&gt;&gt;(allSubsets);\n\n // All element to all subsets of the current power set.\n for (Set&lt;T&gt; subset : tempClone) {\n Set&lt;T&gt; extended = new HashSet&lt;T&gt;(subset);\n extended.add(element);\n allSubsets.add(extended);\n }\n }\n\n return allSubsets;\n}\n</code></pre>\n\n<p>You'll note that I'm using the copy-constructor rather than <code>clone()</code>. That's a matter of taste: fundamentally there's no real difference, because they're both special-cased.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T17:47:15.620", "Id": "16270", "ParentId": "16267", "Score": "3" } } ]
{ "AcceptedAnswerId": "16270", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T13:18:02.567", "Id": "16267", "Score": "3", "Tags": [ "java", "collections", "combinatorics" ], "Title": "Generating all subsets of a given set" }
16267
<p>I defined the class <code>Rectangle</code>:</p> <pre><code>class Rectangle attr_reader :b, :h def initialize(b, h) @b = b @h = h end def area @b*@h end def to_s "Rectangle #{@b}x{@h}" end end </code></pre> <p>and its subclass <code>Square</code>:</p> <pre><code>class Square &lt; Rectangle attr_reader :s def initialize(s) @s = s super(@s, @s) end def to_s "Square of side #{@s}" end end </code></pre> <p>Now, let's say I defined a Rectangle object <code>r = Rectangle.new(5, 5)</code>, but actually it should be a <code>Square</code> because I'd like <code>r.to_s</code> to return <code>"Square of side 5"</code>.</p> <p>I can define a <code>to_square</code> method in the <code>Rectangle</code> class that returns a <code>Square</code> object equivalent to <code>r</code>, but, is it possible to write a <code>to_square!</code> method that would actually change the <code>r</code> class to <code>Square</code> without returning another object, so that <code>r.class</code> would now return <code>Square</code> instead of <code>Rectangle</code>?</p> <p>And, what if I'd like:</p> <pre><code>Square(r) </code></pre> <p>to return the <code>Square</code> equivalent object of <code>r</code>, just like:</p> <pre><code>Integer("3") </code></pre> <p>which returns the Integer <code>3</code>?</p> <p>Is that possible? And, if so, <em>how</em>?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-22T00:19:52.773", "Id": "88673", "Score": "1", "body": "Don't close questions if you can migrate them to SO!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-11T16:08:16.840", "Id": "396268", "Score": "1", "body": "the hall monitors strike again. i wish you guys wouldn't do this. i got here from google, it was exactly what i needed and rather then find help, i find know it alls telling the submitter and me how stupid we are." } ]
[ { "body": "<p>First off, why bother with a separate <code>Square</code> class?</p>\n\n<p>Personally, I'd make a <code>Rectangle</code> class' <code>to_square!</code> method simply set both width and height to <code>Math.sqrt(area)</code>. The result is still a <code>Rectangle</code>, just a square one.</p>\n\n<p>The Rectangle's initializer method could also be written with an optional second argument; If there's only one argument, use that for both width and height, and you have a square.</p>\n\n<p>Furthermore, I'd add a <code>square?</code> method. Checking <code>obj.square?</code> is, in my view, preferable to checking <code>obj.class == Square</code>. You could also use <code>square?</code> in <code>to_s</code> to return one string or the other.</p>\n\n<p>To answer your question, though, I don't know of any way to just change an instance's class. You could however experiment with including different modules depending on whether the rectangle in question is a square or not. But that all seems pretty complex.</p>\n\n<p>Finally, if you want a <code>Square</code> <em>method</em>, simply define one:</p>\n\n<pre><code>def Square(side)\n Rectangle.new(side, side)\nend\n</code></pre>\n\n<p>Even if you have a <code>Square</code> <em>class</em> already, you can still have a <em>method</em> of the same name:</p>\n\n<pre><code>class Square\n # ...\nend\n\ndef Square(side) # no naming conflict\n Square.new(side)\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T13:07:39.213", "Id": "26474", "Score": "0", "body": "Because I'm studying inheritance and subclassing :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T13:27:24.430", "Id": "26475", "Score": "1", "body": "@DuccioArmenise Ah, well that explains it :) In that case, I'd definitely go with tokland's suggestion of a factory method on the class, or a `Square()` factory outside the class (like you see above), and/or have `Rectangle#to_square` (no bang) return a new `Square` instance. Don't start changing the class of an instantiated object, even if you can (and again, I doubt you can - it'd get confusing in a hurry)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T13:40:18.767", "Id": "26477", "Score": "0", "body": "Ok, but what about if `r`, instance of `Rectangle`, can't be converted in a Square because it isn't a square. _Conventionally speaking_, it would be right to assume that `r.to_square` should return `false` while `r.to_square!` should raise an exception?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T14:14:22.237", "Id": "26478", "Score": "0", "body": "@DuccioArmenise Depends on what you want to enforce. I imagine a `to_square` that returns a square with the same area as `r`, regardless of whether `r` is already a square. Same as calling `to_i` on a float returns an int even if the float can't be perfectly expressed as an int; `to_i` doesn't raise. Alternatively, you _could_ have a `to_square` that raises an exception for a non-square `r`, while a `to_square!` forcibly returns a \"squared square\". However, in this context, I'd say that's a bad use of the bang-suffix." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T14:31:31.620", "Id": "26479", "Score": "0", "body": "Just found this statement of Matz's about it: \"The bang (!) does not mean \"destructive\" nor lack of it mean non\ndestructive either. The bang sign means \"the bang version is more dangerous than its non bang counterpart; handle with care\" (http://www.wobblini.net/bang.txt) And, from the Pickaxe: \"Methods that are dangerous, or that modify their receiver, may be named with a trailing exclamation mark\" (http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_methods.html). :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T14:39:19.563", "Id": "26480", "Score": "0", "body": "@DuccioArmenise Exactly, I just didn't have enough characters left to write all that :) - Since most bang methods in Ruby mean \"modify the receiver\", it's a little iffy to use one to return another object; that doesn't seem \"more dangerous\", so to speak. You could however have a bang method that turns a rectangle into a \"square rectangle\" by setting its sides to the same value - but you can't have one that turns it into an instance of `Square`. So it'd be misleading to have both `to_square` and `to_square!`, where one returns a `Square` obj, and the other changes the `Rectangle`... dilemma! :)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T22:29:56.820", "Id": "16284", "ParentId": "16268", "Score": "1" } }, { "body": "<p>If you make the expression <code>ClassName.new</code> return something different than an instance of <code>ClassName</code> you will be breaking the programmer's expectations. The most idiomatic, and simple, way is writing a factory method:</p>\n\n<pre><code>class Rectangle\n # same code you have\n\n def self.with_sides(b, h)\n b == h ? Square.new(b) : Rectangle.new(b, h)\n end\nend\n\nRectangle.with_sides(1, 2).to_s # Rectangle 1x2\nRectangle.with_sides(2, 2).to_s # Square of side 2\n</code></pre>\n\n<p>Of course, you can always do <a href=\"http://ola-bini.blogspot.com.es/2007/12/code-size-and-dynamic-languages.html\" rel=\"nofollow\">black magic with Ruby's new</a>, but I'd advise against it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T13:35:51.270", "Id": "26476", "Score": "0", "body": "Really interesting answer and article, thank you. But I didn't ask for `ClassName.new` to return something different from an instance of `ClassName`. Instead I asked if it's possible to change the class of an existing instance in Ruby (I guess it's not possible, as in Java, and for good reasons, but I don't know for sure yet). And I agree with @Flambino when he sais that even if it would be possible it would be a bad idea." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T11:26:15.360", "Id": "16298", "ParentId": "16268", "Score": "1" } } ]
{ "AcceptedAnswerId": "16284", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T13:20:41.093", "Id": "16268", "Score": "0", "Tags": [ "ruby", "casting" ], "Title": "(sort of) casting types in Ruby: changing class of an instance" }
16268
<p>I think this code to parse a contrived message protocol with first byte data length followed by data is a little ugly. Has anyone got any suggestions on how to make it more elegant and more robust?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define LENGTHBYTES 1 void splitmessages(unsigned char* bstream, int length); void printmsg(unsigned char* msg); int main() { unsigned char stream[] = {2, 'A', 'A', 1, 'B', 3, 'C', 'C', 'C', 1, 'D' }; int len = sizeof(stream) / sizeof(stream[0]); printf("\nTest 1 - four messages together\n"); splitmessages(stream, len); //works printf("\nTest 2 - two complete msgs, then 2 complete msgs\n"); splitmessages(stream, len-2); //works splitmessages(stream+9, 2); //split across a message - in data printf("\nTest 3 - messages split across data part\n"); splitmessages(stream, len-4); //works splitmessages(stream+7, 4); //split across a message - just after size printf("\nTest 4 - messages split just after size part\n"); splitmessages(stream, len-5); splitmessages(stream+6, 5); //split across a message - just before size printf("\nTest 5 - messages split just before size part\n"); splitmessages(stream, len-6); splitmessages(stream+5, 6); return 0; } void splitmessages(unsigned char* bstream, int length) { //Create msg as soon as you have size and save as static static unsigned char* msg = 0; static int tempbufposition = 0; static int tocompletemsg = 0; enum STAGE { SIZE, DATA }; STAGE stage = SIZE; int size = 0; //adjust stage to DATA if already have start of msg if (tocompletemsg != 0) stage = DATA; //get cached size if(tempbufposition != 0 &amp;&amp; msg) size = msg[0]; for(int i=0; i&lt;length; ++i){ switch(stage) { case SIZE: size = bstream[i]; if(msg) { free(msg); msg = 0; tempbufposition = 0; tocompletemsg = 0; } //re-create complete msg so add 1 byte for size msg = (unsigned char*)malloc(size+LENGTHBYTES); msg[0] = size; tempbufposition = 1; tocompletemsg = size; stage = DATA; break; case DATA: //do we have enough data for a complete message if(i + tocompletemsg &lt;= length) { memcpy(msg+tempbufposition, &amp;bstream[i], tocompletemsg); printmsg(msg); stage = SIZE; i += tocompletemsg-1; tocompletemsg = 0; tempbufposition = 0; } else { //add available data memcpy(msg+tempbufposition, &amp;bstream[i], length-i); tempbufposition +=(length-i); tocompletemsg -= (length-i); i += (length-i)-1; } break; } } } void printmsg(unsigned char* msg) { if(msg &amp;&amp; *msg) { int size = msg[0]; printf("%d ", msg[0]); for(int i = 1; i &lt;= size; ++i) printf("%c ", msg[i]); printf("\n"); } } </code></pre>
[]
[ { "body": "<p>Below is an alternative example of how messages could be extracted. Instead of a state machine with saved-state inside your splitmessages function, I have moved the saved-state out of the function into a structure that is passed-in. I have also checked for unexpected data at the start of the function. The return value is 0 on failure or the number of bytes consumed from the input stream on success. I didn't check for size bytes occurring in the wrong place - replace the memcpy with a function that checks the bytes copied for that.</p>\n\n<p>Note that your protocol has to distinguish between data bytes and size bytes. I have arbitrarily made the boundary 32, the first printable char.</p>\n\n<pre><code>#include &lt;string.h&gt;\n#include &lt;assert.h&gt;\n\n#define DATA_MIN_VALUE 32\n#define DATA_MAX_SIZE (DATA_MIN_VALUE)\n\nstruct message {\n size_t size;\n size_t remaining;\n char data[DATA_MAX_SIZE];\n}; \ntypedef struct message Message;\n\nstatic inline size_t min(size_t a, size_t b)\n{\n return a &lt; b ? a : b;\n}\n\nstatic inline int is_data(unsigned char ch)\n{\n return ch &gt;= DATA_MIN_VALUE;\n}\n\nstatic size_t\nget_message(Message *msg, const unsigned char *bstream, size_t length)\n{\n size_t len;\n assert(length);\n\n if ((msg-&gt;remaining == 0) &amp;&amp; is_data(bstream[0])) {\n /* Data instead of message; caller must handle - eg. discard data up\n * to next message */\n return 0;\n }\n\n if (is_data(bstream[0])) {\n msg-&gt;size = 0;\n msg-&gt;remaining = bstream[0];\n }\n\n len = min(length-1, msg-&gt;remaining);\n\n memcpy(&amp;msg-&gt;data[msg-&gt;size], &amp;bstream[1], len);\n msg-&gt;size += len;\n msg-&gt;remaining -= len;\n\n return len + 1;\n}\n</code></pre>\n\n<p>The code should compile but is untested. Hope it helps to have another perspective.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T02:26:46.680", "Id": "16496", "ParentId": "16269", "Score": "2" } } ]
{ "AcceptedAnswerId": "16496", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T15:55:49.017", "Id": "16269", "Score": "3", "Tags": [ "c", "parsing" ], "Title": "Parse a contrived message protocol with first byte data length followed by data" }
16269
<p>I have two different set of checkboxes. With the coffescript code below I set the maximum amount of checkable items at 3. I would like to refactor this code, to be cleaner and compact, but I can't get it.</p> <pre><code>$("div.feature_list :checkbox").click -&gt; if $("div.feature_list :checked").length &gt;= 3 $("div.feature_list :checkbox:not(:checked)").attr "disabled", "disabled" $("div.feature_list :checkbox:not(:checked)").button disabled: true else $("div.feature_list :checkbox:not(:checked)").button disabled: false $("div.style_list :checkbox").click -&gt; if $("div.style_list :checked").length &gt;= 3 $("div.style_list :checkbox:not(:checked)").attr "disabled", "disabled" $("div.style_list :checkbox:not(:checked)").button disabled: true else $("div.style_list :checkbox:not(:checked)").button disabled: false </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T19:17:42.773", "Id": "26452", "Score": "1", "body": "FYI, to enable/disable a button use `.prop('disabled', true_or_false)` instead of setting the attribute." } ]
[ { "body": "<p>Step 1: DRY. Encapsulate the \"limit checkboxes\" behavior in a function</p>\n\n<pre><code>limitCheckboxesIn = (container, limit = 3) -&gt;\n checkboxes = $(container).find \":checkbox\"\n checkboxes.on \"click\", (event) -&gt;\n checked = checkboxes.filter \":checked\"\n unchecked = checkboxes.not checked\n state = disabled: checked.length &gt;= limit\n unchecked.prop(state).button state\n</code></pre>\n\n<p>Step 2: ... well, that pretty much it. Call it like so:</p>\n\n<pre><code>$ -&gt;\n limitCheckboxesIn \"div.feature_list\"\n limitCheckboxesIn \"div.style_list\"\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/7C3Z7/3/\" rel=\"nofollow\">Here's a demo</a></p>\n\n<p>By the way, if you just want the most compact solution, you can skip some assignments:</p>\n\n<pre><code>limitCheckboxesIn = (container, limit = 3) -&gt;\n checkboxes = $(container).find \":checkbox\"\n checkboxes.on \"click\", (event) -&gt;\n disabled = checkboxes.filter(\":checked\").length &gt;= limit\n checkboxes.not(\":checked\").prop({disabled}).button {disabled}\n</code></pre>\n\n<p>Personally, I find this a little less readable, but it's a matter of taste; the code's functionally identical.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T00:29:59.443", "Id": "26463", "Score": "0", "body": "It works with plain checkboxes but it doesnt work with jquery ui buttonset. I think the last line should be different" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T10:33:12.460", "Id": "26471", "Score": "0", "body": "@framomo86 Whoops, you're right - I've corrected my answer, and the demo." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T20:27:26.117", "Id": "16274", "ParentId": "16271", "Score": "5" } } ]
{ "AcceptedAnswerId": "16274", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T19:16:13.827", "Id": "16271", "Score": "2", "Tags": [ "jquery", "coffeescript", "jquery-ui" ], "Title": "Refactor jquery (coffescript) code with checkboxes" }
16271
<p>This code works fine, but I just don't like all the <code>if else</code>. If I keep adding field to filter, it's going to get messy.</p> <p>I am not using EF and cannot on this.</p> <p>Controller code:</p> <pre><code>var books = bookRepository.GetDogs(); if (!String.IsNullOrEmpty(searchString)) { if (!String.IsNullOrWhiteSpace(searchString) &amp;&amp; searchGender != String.Empty &amp;&amp; searchHand != String.Empty) { books = books.Where(b =&gt; b.Name.ToUpper().Contains(searchString.ToUpper()) &amp;&amp; b.Gender == searchGender &amp;&amp; b.Handedness == searchHand); } else if (!String.IsNullOrWhiteSpace(searchGender) &amp;&amp; searchString == String.Empty &amp;&amp; searchHand == String.Empty) { books = books.Where(b =&gt; b.Gender == searchGender); } else if (String.IsNullOrWhiteSpace(searchGender) &amp;&amp; searchString != String.Empty &amp;&amp; searchHand == String.Empty) { books = books.Where(b =&gt; b.Name.ToUpper().Contains(searchString.ToUpper())); } } return View(books); </code></pre> <p>My view:</p> <pre><code>&lt;p&gt;Find by Name : @Html.TextBox("searchString", ViewBag.CurrentFilter as string) @Html.DropDownList("searchGender", new SelectList(ViewBag.BookNames), "-- Select All --") @Html.DropDownList("searchHand", new SelectList(ViewBag.HandNames), "---Select All--") </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T20:38:02.237", "Id": "26453", "Score": "0", "body": "I only ever use the lambda syntax so I might be wrong but isn't `var books = from b in bookRepository.GetDogs() select b;` equivalent to `bookRepository.GetDogs()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T17:24:20.033", "Id": "26538", "Score": "0", "body": "I think your right. I am new to the MVC and linq. I am going to make that change." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T22:40:36.433", "Id": "26547", "Score": "0", "body": "If you're new to LINQ then you should definitely use only the lambda syntax. It is far more powerful and makes it much more clear what is actually going on. There are really very very few instances where I would recommend using the sql-style syntax." } ]
[ { "body": "<p>Just put <code>if</code>, not <code>else if</code> so you can have a cumulative multi criteria search, and one condition in every <code>if</code>.</p>\n\n<p>So every condition is easy to read, and if more than one criteria is filled, they will cumulate fine.</p>\n\n<pre><code>if (!String.IsNullOrWhiteSpace(searchString))\n books = books.Where(b =&gt; b.Name.ToUpper().Contains(searchString.ToUpper()); \n\nif (!String.IsNullOrWhiteSpace(searchGender))\n books = books.Where(b =&gt; b.Gender == searchGender);\n\nif (String.IsNullOrWhiteSpace(searchHand))\n books = books.Where(b =&gt; b.Handedness == searchHand);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T16:50:12.860", "Id": "16276", "ParentId": "16275", "Score": "5" } }, { "body": "<p>Ok, so I just recently arrived at a way of doing this sort of thing that I actually like so let me share.</p>\n\n<p>In my opinion, the if statements aren't really the problem, its more that they are not really pertinent to controller code. Actions should strive to contain code only about major decisions of what code path will be executed.</p>\n\n<p>Solution: You take advantage of the fact that a Linq query returns an IQueryable to store the query logic along with the model and an extension method to give it a nice DSL like interface. Similar to the pipes and filters pattern.</p>\n\n<p>This is what the action is going to look like:</p>\n\n<pre><code>public ViewResult Index(SearchModel searchQuery) \n{\n var books = entities.Get&lt;Book&gt;()\n .Where(b=&gt;b.IsInPrint)\n .FilterBy(searchQuery);\n return View(books);\n}\n</code></pre>\n\n<p>And this is what my model looks like:</p>\n\n<pre><code>public class SearchModel \n{\n public string Text { get; set; }\n public bool InStockOnly { get; set; }\n}\npublic static class SearchModelFilterQueryEx\n{\n public static IQueryable&lt;Book&gt; FilterBy(this IQueryable&lt;Book&gt; query, SearchModel search)\n {\n if(search == null)\n return query;\n if(!String.IsNullOrWhiteSpace(search.Text)) \n query = query.Where(b=&gt;b.Name.Contains(search.Text));\n if(String.InStockOnly)\n query = query.Where(b=&gt;b.NumberInStock &gt; 0);\n return query;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-19T19:44:03.570", "Id": "77919", "Score": "0", "body": "I'm not a huge fan of using IQueryable in views. I think it would be best to at least ToList() the books before passing into the view itself. However in saying that I still like this idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T14:30:30.100", "Id": "78107", "Score": "0", "body": "Fine point @dreza" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T20:46:44.010", "Id": "16279", "ParentId": "16275", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T15:12:10.557", "Id": "16275", "Score": "4", "Tags": [ "c#", "linq", "asp.net-mvc-3", "controller" ], "Title": "Search and filter in MVC3 Razor using Linq" }
16275
<p>I have the following which searches my graph to see if a vertex is reachable from the first vertex, which everything should be connected to. I do this to ensure there are no disconnected parts.</p> <p>Unfortunately it is very slow.</p> <p>Is there something I could do or store to optimize this?</p> <p>I want to learn about graphs and generated cities so Im not using a real graph library.</p> <pre><code>private void removeDisconnectedSquares() { for(int i = 0; i &lt; getNumXNodes(); ++i) { for(int j = 0; j &lt; getNumYNodes(); ++j) { //removeDisconnectedSquare(i, j); visitedNodes.clear(); if(!isNodeReachableFrom(getNodeAt(i, j), getNodeAt(0, 0))) { removeVertex(i, j); } } } } private boolean isNodeReachableFrom(GraphNode node, GraphNode target) { if(node == null) { return false; } if(visitedNodes.contains(node)) { return false; } else { visitedNodes.add(node); } if(node == target) { return true; } if(node.contains(target)) { return true; } for(int i = 0; i &lt; node.getSize(); ++i) { if(isNodeReachableFrom(node.at(i), target)) { return true; } } return false; } </code></pre>
[]
[ { "body": "<p>Rather than using recursion (which is pretty slow), you can for this using a Set of all reachable nodes, and a Queue of nodes you still haven't searched. This is a basic implementation of Breadth-First Search.</p>\n\n<pre><code>private boolean isNodeReachableFrom(GraphNode start, GraphNode target) {\n\n // These are GraphNodes who's connected GraphNodes we haven't looked at yet.\n // Maybe the target is connected to one of these!\n Queue nodesToSearch = new LinkedList&lt;GraphNode&gt;();\n nodesToSearch.add(start);\n\n // These are GraphsNodes which we have proved are reachable from the given node.\n // If we are ever about to add the given target to this list, we return true.\n Set reachableNodes = new HashSet&lt;GraphNode&gt;();\n\n // As long as there are still nodesToSearch, we could still find our target.\n while (nodesToSearch.peek() != null) {\n GraphNode node = nodesToSearch.remove();\n\n // If we have already seen this node, we don't want to look at its connected\n // nodes again, because we could get stuck in a cycle.\n boolean isNewNode = reachableNodes.add(node);\n\n // If this is a new node, see if the target is connected. If it is, we are\n // done successfully. Otherwise, add all of the connected nodes to our\n // list of nodesToSearch.\n if (isNewNode) {\n for (GraphNode connectedNode : getConnectedNodes(node)) {\n if (connetedNode.equals(target)) {\n return true;\n }\n nodesToSearch.add(connectedNode);\n }\n }\n }\n\n // There are no nodes we haven't searched, so the target is not reachable.\n return false;\n}\n</code></pre>\n\n<p>Note: I made up <code>getConnectedNodes(node)</code> because your code didn't show me how to do this with the GraphNode object.</p>\n\n<p>Note that this is an implementation of <code>isNodeReachableFrom</code>. However, you seem to want to figure out the list of nodes which <em>aren't</em> reachable from a starting node. Notice that we build up the list of all <code>reachableNodes</code> in the call above, which is probably what you really want. You could write a function to return that reachableNodes structure, which would reuse the above logic without the <code>target</code> sections. Something like this:</p>\n\n<pre><code>public Set&lt;GraphNode&gt; getReachableNodes(GraphNode start) { ... }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T20:55:58.853", "Id": "16280", "ParentId": "16278", "Score": "3" } } ]
{ "AcceptedAnswerId": "16280", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T20:36:34.040", "Id": "16278", "Score": "2", "Tags": [ "java" ], "Title": "Can this graph search be optimized?" }
16278
<p>I started porting an API wrapper from Java to Python for practice. I am looking for ways to improve the readability/maintainability this code.</p> <p>I have done some reading about "pythonic" style and I am hoping someone could provide some feedback as to how one goes about making their code more pythonic.</p> <p>All source can be found <a href="//github.com/mccannm11/helpscout-api-python" rel="nofollow">here</a>.</p> <p>The models module is what contains the custom types that the parser creates.</p> <pre><code>import requests import json import base64 import models class ApiClient: BASE_URL = "https://api.helpscout.net/v1/" apiKey = "" def getMailbox(self, mailbox_id, fields=None): url = "mailboxes/" + str(mailbox_id) + ".json" if fields != None: url = self.setFields(url, fields) return self.getItem(url, "Mailbox", 200) def getMailboxes(self, fields=None): url = "mailboxes.json" if fields != None: url = self.setFields(url, fields) return self.getPage(url,"Mailbox", fields) def getFolders(self, mailbox_id, fields=None): url = "mailboxes/" + str(mailbox_id) + "/folders.json" if fields != None: url = self.setFields(url, fields) return self.getPage(url, "Folder", 200) def getConverstationsForFolders(self, mailbox_id, folder_id, fields=None): url = "mailboxes/" + str(mailbox_id) + "/folder/" + str(folder_id) + "conversations.json" if fields != None: url = self.setFields(url, fields) return self.getPage(url, "Conversation", 200) def getConversationsForMailbox(self, mailbox_id, fields=None): url = "mailbox/" + str(mailbox_id) + "/conversations.json" if fields != None : url = self.setFields(url, fields) return self.getPage(url) def getConversationForCustomerByMailbox(self, mailbox_id, customer_id, fields=None): url = "mailboxes/" + str(mailbox_id) + "/customers/" + str(customer_id) + "/conversations.json" if fields != None: url = self.setFields(url, fields) return self.getPage(url, "Conversation", 200) def getConversation(self, conversation_id, fields=None): url = "conversations/" + str(conversation_id) + ".json" if fields != None: url = self.setFields(url, fields) return self.getItem(url, "Conversation", 200) def getAttachmentData(self, attachment_id): url = "attachments/" + str(attachment_id) + "/data.json" json_string = self.callServer(url, 200) json_obj = json.loads(json_string) item = json_obj["item"] return item["data"] def getCustomers(self, fields=None): url = "customers.json" if fields != None: url = self.setFields(url, fields) return self.getPage(url, "Customer", 200) def getCustomer(self, customer_id, fields=None): url = "customers/" + str(customer_id) + ".json" if fields != None: url = self.setFields(url, fields) return self.getPage(url, "Customer", 200) def getUser(self, user_id, fields=None): url = "users/" + str(user_id) + ".json" if fields != None: url = self.setFields(url, fields) return self.getItem(url, "User", 200) def getUsers(self, fields=None): url = "users.json" if fields != None: url = self.setFields(url, fields) return self.getPage(url, "User", 200) def getUsersForMailbox(self, mailbox_id, fields=None): url = "mailboxes/" + str(mailbox_id) + "users.json" if fields != None: url = self.setFields(url, fields) return getPage(url, "User", 200) def callServer(self, url, expected_code): auth = "Basic " + self.getEncoded() headers= {'Content-Type': 'application-json' , 'Accept' : 'application-json' , 'Authorization' : str(auth) , 'Accept-Encoding' : 'gzip, deflate' } r = requests.get(self.BASE_URL + url, headers=headers) self.checkStatusCode(r.status_code, expected_code) return r.text def getItem(self, url, clazz, expected_code): string_json = self.callServer( url, expected_code ) return Parser.parse(json.loads(string_json)["item"], clazz) def getPage(self, url, clazz, expected_code): string_json = self.callServer(url, expected_code) json_obj = json.loads(string_json) p = Page() for i in json_obj: setattr(p, i, json_obj[i]) return p def getEncoded(self): raw = str(self.apiKey) + ":x" return base64.b64encode(raw) def getDecoded(val): return base64.b64decode(val) def setFields(self, url, fields): final_str = url + "?fields=" if (fields != None and len(fields) &gt; 0 ): sep = "" for i in fields: final_str += sep + fields[i] sep = "," return final_str def checkStatusCode(self, code, expected): if code == expected: return """ @todo gotta be a better way to do this """ if (code == 400): raise Exception("The request was not formatted correctly") elif(code == 401): raise Exception("Invalid Api Key") elif(code == 402): raise Exception("API Key Suspended") elif (code == 403): raise Exception("Access Denied") elif (code == 404): raise Exception("Resource Not Found") elif (code == 405): raise Exception("Invalid method Type") elif(code == 429): raise Exception("Throttle Limit Reached. Too Many requests") elif(code == 500): raise Exception("Application Error or server error") elif(code == 503): raise Exception("Service Temporarily Unavailable") else: raise Exception("API Key Suspended") class Page: def __init__(self): self.page = None self.pages = None self.count = None self.items = None class ApiException(Exception): def __init__(self, message): Exception.__init__(self,message) class Parser: @staticmethod def parse(json, clazz): c = getattr(globals()["models"], clazz)() for i in json: setattr(c, i, json[i]) return c </code></pre>
[]
[ { "body": "<p>Depends on your definition of \"pythonic\", if you haven't already check out already <a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow\">PEP 20</a>, \"The Zen of Python\" gives some good pragmatic guidelines and <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a> gives some style guidelines.</p>\n\n<p>Personally, pythonic or not, I like things to be easy to read and concise, so here are a couple suggestions</p>\n\n<pre><code>def getFolders(self, mailbox_id, fields=None):\n # if there's no mailbox_id shouldn't this throw an Exception?\n url = \"mailboxes/%s/folders.json\" % mailbox_id\n if fields:\n url = self.setFields(url, fields)\n return self.getPage(url, \"Folder\", 200)\n</code></pre>\n\n<p>Since this doesn't depend on anything in the class and looks like a utility method, you could just move it outside of the class completely and omit <code>self</code> and you might want to check if the url is <code>None</code></p>\n\n<pre><code>def setFields(url, fields):\n # checks None and length\n if not fields:\n return url\n # if speed is important, you can concatenate instead\n # return url + \"?fields=\" + \",\".join(fields);\n return \"%s?fields=%s\" % (url, \",\".join(fields))\n</code></pre>\n\n<p>Here's an alternative to the if/else statements to simulate <code>case/switch</code>:</p>\n\n<pre><code>def checkStatus(self, code, expected):\n if code == expected:\n return\n def error_codes(code):\n messages = { \n 400 : \"The request was not formatted correctly\",\n 401 : \"Invalid API Key\" }\n default_message = \"API Key Suspended\"\n return messages.get(code, default_message)\n raise Exception(error_codes(code))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-10T19:48:34.707", "Id": "86886", "Score": "1", "body": "Using the returned status code as a key for the error dict is really nice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T23:08:13.813", "Id": "16286", "ParentId": "16282", "Score": "3" } }, { "body": "<pre><code>class ApiClient:\n</code></pre>\n\n<p>If using Python 2.x, consider inheriting from <code>object</code>. It makes a couple of advanced features work.</p>\n\n<pre><code> BASE_URL = \"https://api.helpscout.net/v1/\"\n apiKey = \"\"\n</code></pre>\n\n<p>Class constants, like this <code>apiKey</code>, should be in <code>ALL_CAPS</code>.</p>\n\n<pre><code>def setFields(self, url, fields):\n</code></pre>\n\n<p>The Python style guide recommends <code>lowercase_with_underscores</code> for method names. The name is also misleading: it suggests that you are setting a <code>fields</code> property on the object.</p>\n\n<pre><code> final_str = url + \"?fields=\"\n if (fields != None and len(fields) &gt; 0 ):\n</code></pre>\n\n<p>You don't need those parens. It's best to check against <code>None</code> using <code>is not None</code>. As @Ichau suggested, you can actually just check <code>if fields:</code></p>\n\n<pre><code> sep = \"\"\n for i in fields:\n</code></pre>\n\n<p>Use <code>for key, value in fields.items()</code> to avoid having to relookup each key</p>\n\n<pre><code> final_str += sep + fields[i]\n sep = \",\"\n</code></pre>\n\n<p>Adding strings together is not a good idea because it's not very efficient. Better to put all the pieces in a list and join it. The name <code>sep</code> is also confusing because I'd think it stands for seperator, but that's not how you are using it.</p>\n\n<pre><code> return final_str\n\ndef getMailbox(self, mailbox_id, fields=None):\n</code></pre>\n\n<p>There is very little point to prefixes like <code>get</code>. More pythonic would be to call this method <code>mailbox</code>.</p>\n\n<pre><code> url = \"mailboxes/\" + str(mailbox_id) + \".json\"\n if fields != None: \n</code></pre>\n\n<p>Firstly, <code>setFields</code> already handles <code>None</code> correctly. There's no point in checking for it here. Secondly, you do these two lines in pretty much every method. It'd be better to pass the fields parameter to getItem/getPage/etc and handle it consistently in all cases.</p>\n\n<pre><code> url = self.setFields(url, fields)\n return self.getItem(url, \"Mailbox\", 200)\n\n\ndef getDecoded(val):\n return base64.b64decode(val)\n</code></pre>\n\n<p>You seem to be missing a <code>self</code> parameter.</p>\n\n<pre><code>def checkStatusCode(self, code, expected):\n if code == expected:\n return\n</code></pre>\n\n<p>I don't like the happy case bailing out like this. I'd use <code>pass</code>/<code>else</code> rather then a <code>return</code> here.</p>\n\n<pre><code> \"\"\" @todo gotta be a better way to do this \"\"\"\n if (code == 400):\n raise Exception(\"The request was not formatted correctly\")\n elif(code == 401):\n raise Exception(\"Invalid Api Key\")\n elif(code == 402):\n raise Exception(\"API Key Suspended\")\n elif (code == 403):\n raise Exception(\"Access Denied\")\n elif (code == 404):\n raise Exception(\"Resource Not Found\")\n elif (code == 405):\n raise Exception(\"Invalid method Type\")\n elif(code == 429):\n raise Exception(\"Throttle Limit Reached. Too Many requests\")\n elif(code == 500):\n raise Exception(\"Application Error or server error\")\n elif(code == 503):\n raise Exception(\"Service Temporarily Unavailable\")\n</code></pre>\n\n<p>Rather then all that, have a global dict mapping numbers to strings and use that. Also, why <code>Exception</code> and not <code>ApiException</code>?</p>\n\n<pre><code> else:\n raise Exception(\"API Key Suspended\")\n\nclass Parser:\n</code></pre>\n\n<p>This doesn't really fit the definition of a parser.</p>\n\n<pre><code> @staticmethod\n def parse(json, clazz):\n</code></pre>\n\n<p>Why make it a staticmethod rather than just a global function?</p>\n\n<pre><code> c = getattr(globals()[\"models\"], clazz)()\n</code></pre>\n\n<p>You can just refer to <code>models</code> here, no need to mess with globals. Furthermore instead of passing strings around, you can just the class directly and skip this lookup altogether.</p>\n\n<pre><code> for i in json:\n setattr(c, i, json[i])\n</code></pre>\n\n<p>I don't like doing this. The problem is that you don't know what is in that JSON and so any attributes whatsoever can be set. I'd maintain a list of the attributes I expect and check those against the ones present.</p>\n\n<pre><code> return c \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T17:20:44.227", "Id": "26483", "Score": "0", "body": "Thank you! This is wonderful feedback. I'm working on improvements right now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-10-06T23:22:18.663", "Id": "16287", "ParentId": "16282", "Score": "3" } } ]
{ "AcceptedAnswerId": "16287", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T21:22:28.560", "Id": "16282", "Score": "4", "Tags": [ "python", "parsing", "api", "python-2.x" ], "Title": "Python wrapper for the Help Scout API" }
16282
<p>What does this script tell you about how I need to improve as a programmer? I'm somewhat new to both Python and programming, so feel free to minimize your assumptions about my knowledge. </p> <p>The purpose of this script is to read a .csv of names and emails addresses that are improperly organized -- sometimes there is only one name, sometimes three names (first, middle, last) are in the same cell, and sometimes the person has a title (Mr., Mrs.) with their name. </p> <p><img src="https://i.stack.imgur.com/bLKpV.png" alt="enter image description here"></p> <p>Right now, the code does "work". It will execute, but there's a few small issues with some of these functions -- for example, the names aren't properly distributed to columns before the file is written. I'm less interested in these smaller things right now, and would rather have a bigger picture review. </p> <p>I'll happily accept whatever advice you'll offer, but I'd most appreciate feedback on how I've accepted command line arguments, and the layout of the "engine" that controls the flow of operation and calls functions, and specific changes to how I've written the internals of each function -- for example, how could they be faster? </p> <p>I've also posted general questions I've had along the way. If you're interested, please weigh in on those (see below code). I'm also less interested in unanticipated cases, but welcome them if you're inspired.</p> <pre><code>import csv import sys # This script will expext three arguments: # 1. File with data to be scrubbed (CleanCsv.in_file) # 2. File name to output clean data (CleanCsv.clean_out_file) # 3. File name to output data that's needs review (CleanCsv.dirty_out_file) class CleanCsv(object): def __init__(self, args): self.in_file = args[1] # Storing original (necc?) self.clean_out_file = args[2] self.dirty_out_file = args[3] self.flags = [x for x in args[4:] if sys.argv != ""] # Unnecessary? sys.argv will never be blank---&gt; ^^^ self.manual_repair = [] self.rows = [] self.functions = [ 'strip_blank_fields', 'strip_whitespace', 'capitalize', 'strip_blank_lists', 'split_on_blanks', 'remove_duplicate_names', 'remove_bad_rows', 'columnize', ] def do_scrub(self): """Runs all functions in self.functions that weren't negated by command- line arguments. Writes a clean file and, optionally, a file of rows that couldn't be properly scrubbed """ self.fxns = [x for x in self.functions if x not in self.flags] self.grab_file_data(self.in_file) for fx in self.fxns: next_operation = getattr(self, fx) next_operation() if self.manual_repair: self.write_csv(self.manual_repair, self.dirty_out_file) self.write_csv(self.rows, self.clean_out_file) def grab_file_data(self, filename): """Opens the file passed as filename and writes rows to a list of lists. """ with open(filename, 'rt') as opened_file: read_file = csv.reader(opened_file) for row in read_file: # [q1] self.rows.append(row) opened_file.close def strip_blank_fields(self): """If there are any blank fields in a row, take them output. """ for row in self.rows: while "" in row: row.remove("") def strip_whitespace(self): """If there is whitespace in a field, take it out.""" for row in self.rows: for num, field in enumerate(row): row[num] = field.strip() def capitalize(self): """Make all non email fields capitalized (string.title()). """ for row in self.rows: for num, field in enumerate(row): if "@" not in field and not field.istitle(): row[num] = field.title() def strip_blank_lists(self): """Remove any rows that are blank. """ while [] in self.rows: self.rows.remove([]) def split_on_blanks(self): """For fields that have a space between two words, split them out into seperate fields """ for row in self.rows: for num, field in enumerate(row): if ' ' in field: x = field.split(' ') row.pop(num) for i in x: row.append(i) # Move all the emails addresses to the last column. for row in self.rows: for num, field in enumerate(row): if "@" in field: x = row.pop(num) row.append(x) def remove_duplicate_names(self): """If two columns have the same name in them, remove one of the names. """ for num, row in (enumerate(self.rows)): for x in xrange(len(row)): if row.count(row[x]) &gt; 1: row.pop(x) break def remove_bad_rows(self): """Remove all rows that don't have at least three fields filled. Assumes that rows with less than three fields means either missing first, last, or email. """ for num, row in enumerate(self.rows): if len(row) &lt; 3: x = self.rows.pop(num) self.manual_repair.append(x) # Remove all rows that don't have an email address. [q2] for num, row in enumerate(self.rows): bad = True for field in row: if '@' in field: bad = False break if bad == True: x = self.rows.pop(num) self.manual_repair.append(x) def columnize(self): """If there's no title (Mr, Mrs, etc), put a space in the first column. """ titles = [ 'Mr', 'Mrs', 'Mr.', 'Mrs.', 'mr', 'mrs', 'mr.', 'mrs.', 'Miss', 'miss' ] for row in self.rows: if set(row).isdisjoint(set(titles)): row.insert(0, '') def write_csv(self, rows, name_to_write): """Writes a csv based on a list of lists as data for the rows, and a name of the file to write (string). """ f = open(name_to_write, 'wt') try: writer = csv.writer(f) writer.writerow(('Title', 'First', 'Middle', 'Last', 'Email')) for row in rows: writer.writerow(row) finally: f.close() if __name__ == "__main__": x = CleanCsv(sys.argv) x.do_scrub() </code></pre> <p>General questions:</p> <ol> <li>Is this well suited as an OOP? It makes it easier to organize, but what are the downsides of using OOP in this case? Should I separate the worker functions into a different class from the engine/control functions? </li> <li>Am I missing any PEP8 stuff? </li> <li>There's a bunch of other classes and functions in the csv module. Is there anything I could have used? </li> <li>Is there any reason to split this into two different files? </li> <li>What are the components of the Python language that I'm missing? What features of the standard library could I use to make this better? </li> <li>Is there too much nesting? My general sense is that less nesting is better for clarity, but I haven't seen a way to get around it here. </li> </ol> <p>Specific in-line questions:</p> <ol> <li>Should I be able to access this without having to re-write it to lists? </li> <li>Should this loop be moved into another function for modularity?</li> </ol>
[]
[ { "body": "<h3>Design</h3>\n\n<p>As far as I can tell, what you are actually trying to do is to clean up a CSV file so that it has five fields (title, first name, middle name, last name, and e-mail address), by applying a sequence of heuristics. You then allow the caller to specify flags to turns these heuristics off if they are not working.</p>\n\n<p>There are several problems with this approach:</p>\n\n<ol>\n<li><p>You end up pushing the responsibility for working out which heuristics to apply onto the user of your program.</p></li>\n<li><p>In order for the user to be able to figure out which heuristics to turn on, the documentation is going to have to be complex, and most likely hard to understand.</p></li>\n<li><p>The heuristics interact with each other. For example, <code>columnize</code> adds blank fields, but <code>strip_blank_fields</code> removes blank fields: which wins? How will you explain this in the documentation?</p></li>\n<li><p>In any case, the heuristics don’t achieve what you are trying to do: for example you don’t move the title to the beginning of the row, or the e-mail address to the end.</p></li>\n</ol>\n\n<p>So, although it’s probably not what you were hoping to hear, I think that your code would be more reliable, easier to use and easier to understand if you implemented your clean-up as a straightforward algorithm, rather than as a configurable collection of interacting heuristics. If you find that the algorithm doesn’t work on some of your data, then improve it until it does (instead of adding yet more optional heuristics).</p>\n\n<p>I’ve put some revised code at the end of this answer showing how you might implement my suggested approach.</p>\n\n<h3>Comments</h3>\n\n<ol>\n<li><p>There’s no docstring for the <code>CleanCsv</code> class. Users will like to be able to run <code>help(CleanCsv)</code> to learn how to use the class.</p></li>\n<li><p>The <code>CleanCsv</code> class starts by processing the command-line arguments. This design decision means that you can only easily use this class from the command-line. If you want to use it from another program or from a test suite, or interactively from the Python interpreter, then you have to mock up an <code>argv</code> array. The class would be more widely useful if it took its arguments directly, leavng the command-line processing to be done in the command-line case.</p></li>\n<li><p>It seems perverse to me that you interpret the command-line argument <code>capitalize</code> to mean “don’t capitalize”. The argument should be something like <code>--dont-capitalize</code> or <code>--no-capitalization</code> to make it clear what it does.</p></li>\n<li><p>You don’t check the command-line arguments to see if they contain errors. This means that misspellings like <code>capitalise</code> won’t be detected.</p></li>\n<li><p>If you’re going to process command-line arguments, it would be a good idea to use the <a href=\"http://docs.python.org/library/argparse.html\" rel=\"nofollow\"><code>argparse</code> module</a> in the standard library. This gives you help text and error messages.</p></li>\n<li><p>You do your processing with the whole of the input and output in memory: you read the whole of the input CSV file into a list; then you apply each function to the whole list; then you write out the whole list to the output CSV file. This means that your memory usage is going to depend on the size of the CSV file, and means that your program will behave poorly (lots of swapping) if you need to process very large CSV files.</p>\n\n<p>You could change the code so that it works row-by-row instead of function-by-function: read a single line at a time from the input CSV file, apply each function to that line, and then write out the updated line to one of the output CSV files. That way the memory footprint doesn’t need to be much bigger than the biggest line in the input.</p></li>\n<li><p>All of your functions that operate on rows in the input have boilerplate of the form</p>\n\n<pre><code>for row in self.rows:\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for num, row in (enumerate(self.rows)):\n</code></pre>\n\n<p>if you refactored the code so that it worked row-by-row then you would be able to avoid this (each function would operate on a single row).</p></li>\n<li><p>This line is bogus (as you say in your comment):</p>\n\n<pre><code>self.flags = [x for x in args[4:] if sys.argv != \"\"]\n# Unnecessary? sys.argv will never be blank---&gt; ^^^\n</code></pre>\n\n<p>You’re checking <code>sys.argv</code> each time around the loop to see if it’s equal to the empty string, which of course it isn’t (it’s an array, not a string). Probably you meant to write</p>\n\n<pre><code>self.flags = [x for x in args[4:] if x != \"\"]\n</code></pre>\n\n<p>which could be abbreviated to</p>\n\n<pre><code>self.flags = [x for x in args[4:] if x]\n</code></pre>\n\n<p>since only empty strings test false, but since what you are actually going to do is look up function names to see if they appear in this list, it would be more efficient to use a set than a list (sets can test membership in O(1) but lists take O(<em>n</em>)):</p>\n\n<pre><code>self.flags = {x for x in args[4:] if x}\n</code></pre>\n\n<p>but in practice you don’t care about whether this set contains the blank string or not (you’re never going to look it up), so you could just write </p>\n\n<pre><code>self.flags = set(args[4:])\n</code></pre>\n\n<p>but I still think using <code>argparse</code> would be even better.</p></li>\n<li><p>This operation is O(<em>n</em><sup>2</sup>):</p>\n\n<pre><code>while [] in self.rows:\n self.rows.remove([])\n</code></pre>\n\n<p>(Consider a row whose first half is non-blank and whose second half is blank.) The natural way to remove blank entries from a list in Python is to filter the list:</p>\n\n<pre><code>self.rows = [row for row in self.rows if rows]\n</code></pre>\n\n<p>You have several other O(<em>n</em><sup>2</sup>) operations in your code. In <code>strip_blank_fields</code> you have</p>\n\n<pre><code>while \"\" in row:\n row.remove(\"\")\n</code></pre>\n\n<p>which could be turned into:</p>\n\n<pre><code>row = [f for f in row if f]\n</code></pre>\n\n<p>In <code>split_on_blanks</code> you have</p>\n\n<pre><code>for num, field in enumerate(row):\n if ' ' in field:\n x = field.split(' ')\n row.pop(num)\n for i in x:\n row.append(i)\n</code></pre>\n\n<p>which could be turned into a double comprehension:</p>\n\n<pre><code>row = [f for field in row for f in field.split(' ')]\n</code></pre>\n\n<p>(In all these cases you’d want to reorganize your code, because you are currently relying on being able to update your rows in-place. You could write</p>\n\n<pre><code>row[:] = # ... filtering code here ...\n</code></pre>\n\n<p>but it would be better to reorganize so you didn’t have to.)</p></li>\n<li><p>Splitting fields on single spaces is probably not what you want, because if there are multiple contiguous spaces you get useless empty strings:</p>\n\n<pre><code>&gt;&gt;&gt; 'First Last'.split(' ')\n['First', '', 'Last']\n</code></pre>\n\n<p>You probably want to split on any contiguous sequence of whitespace:</p>\n\n<pre><code>&gt;&gt;&gt; 'First Last'.split()\n['First', 'Last']\n</code></pre></li>\n<li><p>This code in <code>remove_duplicate_names</code> is not only O(<em>n</em><sup>2</sup>) but only removes the first duplicate it finds:</p>\n\n<pre><code>for x in xrange(len(row)):\n if row.count(row[x]) &gt; 1:\n row.pop(x)\n break\n</code></pre>\n\n<p>So it turns <code>['A','A','A']</code> into <code>['A','A']</code> which is probably not what you want. It isn’t clear to me what you actually want to do here, but if the specification is to keep only the first copy of each duplicated field, then the <a href=\"http://docs.python.org/library/collections.html#collections.OrderedDict\" rel=\"nofollow\"><code>OrderedDict</code></a> class in the <a href=\"http://docs.python.org/library/collections.html\" rel=\"nofollow\"><code>collections</code> module</a> does what you need, like this:</p>\n\n<pre><code>row = OrderedDict((f, None) for f in row).keys()\n</code></pre>\n\n<p>(Morally speaking you want an ordered set here rather than an ordered dictionary, but there’s no ordered set in the standard library. You could use <a href=\"http://code.activestate.com/recipes/576694/\" rel=\"nofollow\">this recipe</a> if you care about this issue.)</p></li>\n<li><p>This docstring doesn’t accurately describe what the function does:</p>\n\n<pre><code>\"\"\"If there is whitespace in a field, take it out.\"\"\"\n</code></pre>\n\n<p>Better would be something like</p>\n\n<pre><code>\"\"\"Strip whitespace from the beginning and end of each field.\"\"\"\n</code></pre></li>\n<li><p>This:</p>\n\n<pre><code>titles = [\n 'Mr', 'Mrs', 'Mr.', 'Mrs.', 'mr',\n 'mrs', 'mr.', 'mrs.', 'Miss', 'miss'\n ]\n</code></pre>\n\n<p>could be written as a set comprehension which expresses your intention more directly (that is, for each title you want capitalized and lower-case versions, both with and without a period):</p>\n\n<pre><code>titles = {t for t in 'Miss Mr Mrs Ms'.split()\n for t in [t, t.lower()]\n for t in [t, t + '.']}\n</code></pre></li>\n</ol>\n\n<h3>Answers to your general questions</h3>\n\n<ol>\n<li><p>Once you’ve made the processing row-by-row (see comment #6), then you’ll see that the heuristic functions don’t refer to <code>self</code> any more, and so don’t need to be methods. This suggests that it’s unnecessary to organize the code as a class (and I chose not to, in my revision). But <em>unnecessary</em> is not the same as <em>wrong</em>: there’s room for personal taste here.</p></li>\n<li><p>Not that I noticed.</p></li>\n<li><p>No.</p></li>\n<li><p>This is really a usability quetsion, so I can’t answer this without knowing more about the context in which your program is going to be used. Try it both ways and see which is easier to work with.</p></li>\n<li><p>The <a href=\"http://docs.python.org/library/argparse.html\" rel=\"nofollow\"><code>argparse</code> module</a> (see comment #5) and the <a href=\"http://docs.python.org/library/collections.html#collections.OrderedDict\" rel=\"nofollow\"><code>OrderedDict</code> class</a> (see comment #11).</p></li>\n<li><p>Nested loops are appropriate in some contexts, but in this case, I think the nesting (and especially the repeated boilerplate discussed in comment #7) was a sign that something was wrong with the organization of the code.</p></li>\n</ol>\n\n<h3>Answers to your specific questions</h3>\n\n<ol>\n<li><p>Yes: see comment #6.</p></li>\n<li><p>No: I think the whole “modularity” approach has drawbacks, as discussed in the “Design” section above.</p></li>\n</ol>\n\n<h3>Revised code</h3>\n\n<pre><code>import argparse\nimport collections\nimport csv\nimport sys\n\n# Dispositions for a row.\nCLEAN, DIRTY, DROP = range(3)\n\n# Map from title to canonical version of that title.\nTITLES = {t: title for title in 'Miss Mr Mrs Ms'.split()\n for t in [title, title.lower()]\n for t in [t, t + '.']}\n\ndef clean_row(row):\n \"\"\"\n Return a pair `(disposition, row)` where `disposition` is:\n `CLEAN` if `row` was successfully cleaned up and should be\n output to the clean file;\n `DIRTY` if `row` could not be cleaned up and should be output to\n the dirty file; or\n `DROP` if `row` was empty and should be dropped.\n \"\"\"\n title, names, email = '', collections.OrderedDict(), ''\n for f in (f for field in row for f in field.split()):\n if f in TITLES:\n if title:\n return DIRTY, row\n title = TITLES[f]\n elif '@' in f:\n if email:\n return DIRTY, row\n email = f\n elif f:\n names[f.capitalize()] = None\n\n names = names.keys()\n if len(names) == 3 and email:\n return CLEAN, [title] + names + [email]\n elif len(names) == 2 and email:\n return CLEAN, [title, names[0], '', names[1], email]\n elif names or email:\n return DIRTY, row\n else:\n return DROP, row\n\ndef clean_csv(input, clean, dirty):\n \"\"\"\n Read rows from the CSV file INPUT and attempt to clean them up\n to fit the format (title, first name, middle name, last name, and\n e-mail address). Rows that can be cleaned up are written to the\n output CSV file CLEAN, and rows that cannot be cleaned up are\n written to the output CSV file DIRTY.\n \"\"\"\n clean_writer = csv.writer(clean)\n dirty_writer = csv.writer(dirty)\n headings = 'Title First Middle Last Email'.split()\n for w in clean_writer, dirty_writer:\n w.writerow(headings)\n for row in csv.reader(input):\n disposition, row = clean_row(row)\n if disposition == CLEAN:\n clean_writer.writerow(row)\n elif disposition == DIRTY:\n dirty_writer.writerow(row)\n else:\n assert(disposition == DROP)\n\nif __name__ == '__main__':\n p = argparse.ArgumentParser(description = clean_csv.__doc__)\n p.add_argument('INPUT', type = argparse.FileType('r'),\n help = 'Input CSV file.')\n p.add_argument('CLEAN', type = argparse.FileType('w'),\n help = 'Output CSV file for rows that can be cleaned.')\n p.add_argument('DIRTY', type = argparse.FileType('w'),\n help = 'Output CSV file for rows that need manual repair.')\n args = p.parse_args()\n clean_csv(args.INPUT, args.CLEAN, args.DIRTY)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T23:52:26.780", "Id": "26499", "Score": "0", "body": "Gareth: \"So, although it’s probably not what you were hoping to hear, I think that your code...\" No, I was hoping to hear something like this :-) This is helping me improve, so I'm more than glad to take polite and constructive criticism, which your certainly was. Such a humbling experience to have somebody spend *so much* effort on improving my code! Wow. Thanks a bunch." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T19:37:50.940", "Id": "16309", "ParentId": "16290", "Score": "7" } } ]
{ "AcceptedAnswerId": "16309", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T04:05:44.753", "Id": "16290", "Score": "6", "Tags": [ "python", "optimization", "performance", "csv" ], "Title": "Script that scrubs data from a .csv file" }
16290
<p>This is the way I handle an Ajax response. I am sure it can be improved.</p> <pre><code>success: function (json) { $.each(json, function(index,item){ if (item.field == "article_id") { $("#article_id").val(item.value); } else if (item.field == "naslov") { $("#naslov").val(stripslashes(item.value)); }else if (item.field == "slug_naslov") { $("#slug_naslov").val(item.value); }else if (item.field == "datum") { $("#datum").val(item.value); }else if (item.field == "url") { $("#url").val(item.value); }else if (item.field == "tekst") { $("#tekst").val(stripslashes(item.value)); }else if (item.field == "tag_title") { //handle tags - tokeninput var tagoviArray = item.value; var tagoviInput = $("#txtTags"); $(tagoviInput).tokenInput("clear"); $.each(tagoviArray, function (index, value) { var arr = value.split(','); $.each(arr, function (i, v) { if (!(v=="")) { $(tagoviInput).tokenInput("add", {id: "", name: v}); tag } }); }); }else if (item.field == "love") { $("#love").val(item.value); } }); return false; } </code></pre>
[]
[ { "body": "<p>Maybe something like this?</p>\n\n<pre><code>success: function (json) {\n var decorators = {},\n handlers = {};\n\n // decorators prepare content for insertion\n decorators.naslov = stripslashes;\n decorators.tekst = stripslashes;\n\n // specialized handlers\n handlers.tag_title = function (value) {\n // do the tokenization-stuff here\n };\n\n // Go through the response\n $.each(json, function (index, item) {\n var value = item.value;\n // if the field has its own handler, use that\n if( typeof handlers[item.field] === \"function\" ) {\n handlers[item.field](value);\n } else {\n // Otherwise, send the value through the decorator\n // (if there is one for the given field), and\n // insert the value in the corresponding input\n if( typeof decorators[item.field] === 'function' ) {\n value = decorators[item.field](value);\n }\n $(\"#\" + item.field).val(value);\n }\n });\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T11:42:08.530", "Id": "16299", "ParentId": "16294", "Score": "4" } } ]
{ "AcceptedAnswerId": "16299", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T10:41:08.803", "Id": "16294", "Score": "2", "Tags": [ "javascript", "jquery", "ajax" ], "Title": "jQuery Ajax response" }
16294
<p>I am currently reading <em>The C Programming Language</em> by Dennis Richie and Brian Kernighan, and I came to implement the function <code>squeeze (s1, s2)</code> as an exercise. <code>squeeze()</code> deletes each character in <code>s1</code> that matches any character in the string <code>s2</code>. While coding <code>squeeze()</code>, I thought that I can extend its capability to act like <code>trim()</code> method in Java, and then the my code was already done, and tested. </p> <p>However, even though it is implemented in C, I believe that the code below can be improved and optimized. Please help me do so.</p> <pre><code>char *squeeze (char *str1, char *str2) { int i, j; int str1Len = strlen (str1); int toBeSubtractLen = 0; char chr1 = '\0'; char chr2 = '\0'; for (i = 0; i &lt; str1Len; i++) { chr1 = str1 [i]; for (j = 0; j &lt; strlen (str2); j++) { chr2 = str2 [j]; if (chr1 == chr2) { toBeSubtractLen++; } } } char *finalStr; finalStr = malloc ((str1Len - toBeSubtractLen) + 1); if (finalStr == NULL) { printf ("Unable to allocate memory.\n"); exit (EXIT_FAILURE); } int indx = 0; for (i = 0; i &lt; str1Len; i++) { chr1 = str1 [i]; for (j = 0; j &lt; strlen (str2); j++) { chr2 = str2 [j]; if (chr1 == chr2) { break; } } if (chr1 != chr2) { finalStr[indx] = chr1; indx++; } } return finalStr; } /* end of squeeze() */ </code></pre> <p>Samples:</p> <ol> <li>str1 = ",AaBbCcDdEeFfGgHhIiJjKkLlMmAaAaAaNnOoPpQqRrSsTtUuVvWwXxYyZz"</li> <li>str2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"</li> <li>str3 = "abcdefghijklmnopqrstuvwxyz"</li> <li>name = "ChristopherM.Sawi"</li> <li>birthday = "August14,1988"</li> </ol> <p>Outputs:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>1. squeeze-ing str1 by str2 yields: "&lt;space&gt;,&lt;tab&gt;abcdefghijklmaaanopqrstuvwxyz" 2. squeeze-ing str1 by str3 yields: "&lt;space&gt;m&lt;tab&gt;ABCDEFGHIJKLMAAANOPQRSTUVWXYZ" 3. squeeze-ing str2 by str3 yields: "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 4. squeeze-ing name by str3 yields: "C&lt;space&gt;M.&lt;space&gt;S" 5. squeeze-ing birthday by str1 yields: "141988" </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T13:57:32.127", "Id": "26783", "Score": "0", "body": "Output 2 starts with a ',' not an 'm'" } ]
[ { "body": "<p>It would be better to iterate over both the strings only once. Create a third temporary variable, equal to size of first string, and copy characters one-by-one if no match is found in the second string.</p>\n\n<pre><code>char *squeeze (char *destination, char *source) {\n\n char * result = (char*) malloc (destination_length + 1);\n bool found = FALSE;\n\n int destination_length = strlen (destination);\n int source_length = strlen (source);\n int k = 0;\n\n for (int i = 0; i &lt; destination_length; i++) {\n found = FALSE;\n for (int j = 0; j &lt; source_lenth; j++) {\n if ( source [j] == destination [i] ) {\n found = TRUE;\n break;\n }\n }\n\n if ( FALSE == found ) {\n result [k++] = destination[i];\n }\n }\n\n destination [k] = '\\0';\n return destination;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T05:28:55.320", "Id": "26503", "Score": "0", "body": "I agree with your first sentence, however I think you've actually described more or less the same algorithm @chrismsawl is using. Specifically this \"if no match is found in the second string\" part - implemented naively that would be another traversal of `str2` at each step. Can you share more details of how you'd do it?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T19:07:58.687", "Id": "16307", "ParentId": "16301", "Score": "1" } }, { "body": "<p>Minor improvements:</p>\n\n<ul>\n<li><code>chr1</code> and <code>chr2</code> are initialized to <code>'\\0'</code> before being assigned, but they will always be reassigned before being read. <code>i</code> and <code>j</code> are not being initialized, but, similarly, will be assigned before being read. If you're going for performance optimization, consider leaving <code>chr1</code> and <code>chr2</code> uninitialized. If you're going for good programming practice, consider initializing <code>i</code> and <code>j</code>.</li>\n<li>The loops <code>for (j = 0; j &lt; strlen (str2); j++)</code> call <code>strlen</code> each iteration even though <code>str2</code> doesn't change anywhere in the function. Consider creating a <code>str2len</code> variable like <code>str1len</code> to remove the unnecessary calls.</li>\n</ul>\n\n<p>Major improvement:</p>\n\n<ul>\n<li>The first loop isn't necessary. It's only purpose is to determine the length of <code>finalStr</code>, but we know that a) <code>squeeze</code> never returns a string longer than <code>str1</code>, and b) <code>indx</code> contains the actual length of <code>finalStr</code>. Knowing this, you can <code>malloc</code> <code>finalStr</code> to the size of <code>str1 + 1</code>, then <code>realloc</code> it to <code>indx + 1</code> before returning.</li>\n</ul>\n\n<hr>\n\n<p><em>Edit:</em> <code>finalStr</code> needs to have a trailing <code>\\0</code> assigned to it before returning, also. Consider setting it before returning or by calling <code>memset</code> after <code>malloc</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T19:08:09.897", "Id": "16308", "ParentId": "16301", "Score": "2" } }, { "body": "<p>You want to avoid repeat iteration over the 2nd string, which is O(N). Do this N times and you have an O(N<sup>2</sup>) algorithm.</p>\n\n<p>One trick you could use is to build a lookup table of the chars in <code>str2</code>. This would cost O(N) and some extra memory upfront, but then subsequent lookups in the table could be brought down to O(1).</p>\n\n<p>Here's a simple example. The trade-off is this takes a bit more memory and makes some assumptions about the range of <code>char</code>. It also clobbers the buffer of <code>str1</code>:</p>\n\n<pre><code>#include &lt;limits.h&gt; // for UCHAR_MAX\n\nchar *squeeze (char *str1, char *str2)\n{\n char present[UCHAR_MAX + 1] = {0};\n char *src, *dst;\n\n // Build lookup table of chars in str2\n //\n while (*str2)\n present[(unsigned char)*str2++] = 1;\n\n // Iterate through str1, removing chars along the way.\n //\n src = dst = str1;\n while (*src)\n {\n // Is *src in str2?\n //\n if (present[(unsigned char)*src])\n {\n // Yes, remove this char.. (Advance src but not dst.)\n //\n ++src;\n }\n else\n *dst++ = *src++;\n }\n\n // NUL terminator\n //\n *dst = 0;\n\n return str1;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T04:41:32.367", "Id": "16318", "ParentId": "16301", "Score": "6" } }, { "body": "<p>The solution by @asveikau is more efficient, but here is a small version, for what it is worth. Note that I have used the standard library <code>strchr</code> to look for chars within strings. This is better than rolling your own loop to do the same thing and also avoids nested loops (always a bad sign).</p>\n\n<pre><code>#include &lt;string.h&gt;\nchar *\nsqueeze(char *s, const char *t)\n{\n char *out = s;\n\n for (int i=0; s[i]; ++i) {\n if (!strchr(t, s[i]))\n *out++ = s[i];\n }\n *out = '\\0';\n return s;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T14:00:42.607", "Id": "16470", "ParentId": "16301", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T13:26:50.097", "Id": "16301", "Score": "7", "Tags": [ "optimization", "c", "strings" ], "Title": "Improving and optimizing squeeze() function" }
16301
<p>It's my first window program. It simply searches for a specified file in the whole computer.</p> <p>File Search.h (header file that contains the prototypes of fileSearcher class methods.) </p> <pre><code>#ifndef UNICODE #define UNICODE #endif #include &lt;Windows.h&gt; #include &lt;queue&gt; namespace fileSearch { class fileSearcher { public: fileSearcher(); ~fileSearcher(); //So far, this class doesn't allocate memory on the heap,therefore destructor is empty void getAllPaths(const TCHAR* fileName,std::queue&lt;TCHAR*&gt; &amp;output); /*Returns all matching pathes at the current local system. Format: [A-Z]:\FirstPath\dir1...\fileName [A-Z]:\SecondPath\dir2...\fileName ... [A-Z]:\NPath\dirN...\fileName */ void findFilesRecursivelly(const TCHAR* curDir,const TCHAR* fileName,std::queue&lt;TCHAR*&gt; &amp;output); //Searches for the file in the current and in sub-directories. Sets nothingFound=false if the file has been found. private: static const int MAX_LOCATIONS = 20000; bool nothingFound; void endWithBackslash(TCHAR* string); }; } </code></pre> <p>File Search.cpp ( ... definitions)</p> <pre><code>#ifndef UNICODE #define UNICODE #endif #include "File Search.h" using namespace fileSearch; fileSearcher::fileSearcher() { nothingFound = true; } fileSearcher::~fileSearcher() { } void fileSearcher::getAllPaths(const TCHAR* fileName,std::queue&lt;TCHAR*&gt; &amp;output) { TCHAR localDrives[50]; TCHAR currentDrive; int voluminesChecked=0; TCHAR searchedVolumine[5]; nothingFound = true; if(!wcslen(fileName)) { output.push(TEXT("Invalid search key")); return; } GetLogicalDriveStrings(sizeof(localDrives)/sizeof(TCHAR),localDrives); //For all drives: for(int i=0; i &lt; sizeof(localDrives)/sizeof(TCHAR); i++) { if(localDrives[i] &gt;= 65 &amp;&amp; localDrives[i] &lt;= 90) { currentDrive = localDrives[i]; voluminesChecked++; } else continue; searchedVolumine[0] = currentDrive; searchedVolumine[1] = L':'; searchedVolumine[2] = 0; findFilesRecursivelly(searchedVolumine,fileName,output); } if(nothingFound) output.push(TEXT("FILE NOT FOUND")); } void fileSearcher::findFilesRecursivelly(const TCHAR* curDir,const TCHAR* fileName,std::queue&lt;TCHAR*&gt; &amp;output) { HANDLE hFoundFile; WIN32_FIND_DATA foundFileData; TCHAR* buffer; buffer = new TCHAR[MAX_PATH+_MAX_FNAME]; wcscpy(buffer,curDir); endWithBackslash(buffer); if(!SetCurrentDirectory(buffer)) return; //Fetch inside current directory hFoundFile = FindFirstFileEx(fileName,FINDEX_INFO_LEVELS::FindExInfoBasic,&amp;foundFileData ,FINDEX_SEARCH_OPS::FindExSearchNameMatch,NULL,FIND_FIRST_EX_LARGE_FETCH); if(hFoundFile != INVALID_HANDLE_VALUE) { nothingFound = false; do { buffer = new TCHAR[MAX_PATH+_MAX_FNAME]; wcscpy(buffer,curDir); endWithBackslash(buffer); wcscat(buffer,foundFileData.cFileName); wcscat(buffer,TEXT("\r\n")); output.push(buffer); } while(FindNextFile(hFoundFile,&amp;foundFileData)); } //Go to the subdirs hFoundFile = FindFirstFileEx(TEXT("*"),FINDEX_INFO_LEVELS::FindExInfoBasic,&amp;foundFileData ,FINDEX_SEARCH_OPS::FindExSearchLimitToDirectories ,NULL , NULL); if(hFoundFile != INVALID_HANDLE_VALUE ) { do { if(wcscmp(foundFileData.cFileName,TEXT(".")) &amp;&amp; wcscmp(foundFileData.cFileName,TEXT(".."))) { TCHAR nextDirBuffer[MAX_PATH+_MAX_FNAME]=TEXT(""); wcscpy(nextDirBuffer,curDir); endWithBackslash(nextDirBuffer); //redundant? wcscat(nextDirBuffer,foundFileData.cFileName); findFilesRecursivelly( nextDirBuffer,fileName,output); } } while(FindNextFile(hFoundFile,&amp;foundFileData)); } } void fileSearcher::endWithBackslash(TCHAR* string) { if(string[wcslen(string)-1] != TEXT('\\')) wcscat(string,TEXT("\\")); } </code></pre> <p>main.cpp (simple window interface for the fileSearcher class)</p> <pre><code>#ifndef UNICODE #define UNICODE #endif #include &lt;Windows.h&gt; #include &lt;queue&gt; #include "File Search.h" static HWND textBoxFileName; static HWND searchButton; static HWND textBoxOutput; LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); using namespace fileSearch; int WINAPI wWinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPWSTR cmdLine,int nCmdShow) { TCHAR className[] = L"Main window class"; WNDCLASS wc = {}; wc.lpfnWndProc = WindowProc; wc.hInstance = hInstance; wc.lpszClassName = className; RegisterClass(&amp;wc); HWND hMainWindow = CreateWindowEx(WS_EX_CLIENTEDGE,className,L"Path getter",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,600,300,NULL,NULL,hInstance,NULL); if(hMainWindow == NULL) return 0; textBoxFileName = CreateWindowEx(WS_EX_CLIENTEDGE, L"Edit", NULL,WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL, 10, 10, 300, 21, hMainWindow, NULL, NULL, NULL); searchButton = CreateWindowEx(WS_EX_CLIENTEDGE,L"Button",L"Search",WS_CHILD | WS_VISIBLE | ES_CENTER, 10, 41,75,30,hMainWindow,NULL,NULL,NULL); textBoxOutput = CreateWindowEx(WS_EX_CLIENTEDGE,L"Edit",NULL,WS_CHILD | WS_VISIBLE | WS_VSCROLL | ES_AUTOVSCROLL | ES_MULTILINE | ES_READONLY ,10,81,500,90,hMainWindow,NULL,NULL,NULL); ShowWindow(hMainWindow,nCmdShow); MSG msg = { }; while (GetMessage(&amp;msg, NULL, 0, 0)) { TranslateMessage(&amp;msg); DispatchMessage(&amp;msg); } return 0; } LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_COMMAND: if((HWND)lParam == searchButton) { fileSearcher searcher; TCHAR key[1000]; std::queue&lt;TCHAR*&gt; buffer; SetWindowText(textBoxOutput,NULL); GetWindowText(textBoxFileName,key,1000); searcher.getAllPaths(key,buffer); SendMessage(textBoxOutput,EM_LIMITTEXT,WPARAM(0xFFFFF),NULL); while(!buffer.empty()) { SendMessage(textBoxOutput,EM_SETSEL,GetWindowTextLength(textBoxOutput),GetWindowTextLength(textBoxOutput)); SendMessage(textBoxOutput,EM_REPLACESEL,FALSE, (LPARAM) buffer.front()); delete [] buffer.front(); buffer.pop(); } } return 0; break; case WM_DESTROY: PostQuitMessage(0); return 0; case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hwnd, &amp;ps); HBRUSH pedzel; pedzel = CreateSolidBrush(RGB(249,224,75)); FillRect(hdc, &amp;ps.rcPaint, pedzel); EndPaint(hwnd, &amp;ps); } return 0; } return DefWindowProc(hwnd, uMsg, wParam, lParam); } </code></pre> <p>Shortcomings that I've noticed so far:</p> <p>1) The window freezes during work<br> 2) Only a few queries can be done in a row - a memory after each isn't deallocated from heap (I simply don't know how to fix it).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T21:44:24.373", "Id": "26488", "Score": "0", "body": "Are you against using a Thread pool?" } ]
[ { "body": "<p>A few points:</p>\n\n<ul>\n<li><p>Best Practice: There's no need to define <code>UNICODE</code> in <code>File Search.h</code> since it's defined at the top of those files that include it. Consider creating a configuration header that gets included by the <code>.cpp</code> first and let it handle the defines and other preprocessor logic. That way if you decide to make a non-UNICODE build, you only need to change one definition, not two or three.</p></li>\n<li><p>Best Practice: Class names in C++ generally follow one of two conventions: <code>CamelCaseStyle</code> or <code>underscore_style</code>. Consider using one of these for your class.</p></li>\n<li><p>Potential Build Error / Best Practice: Good use of <code>TCHAR</code> and the <code>TEXT</code> macro to conform to the Windows function definitions. Be sure to use the macro instead of directly using <code>L\"...\"</code> and <code>L'.'</code>, also, so that the code can compile a non-UNICODE build. Same goes for the string-manipulating functions: <code>wcscpy</code> (should be <code>_tcscpy</code>), <code>wcscat</code> (should be <code>_tcscat</code>), and <code>wcscmp</code> (should be <code>_tcscmp</code>). More on strings later, though, since all of this (including the use of <code>TCHAR*</code>) is the hard way to manage strings in C++. </p></li>\n<li><p>Memory Leak: In <code>fileSearcher::fineFilesRecursivelly</code>, <code>buffer</code> is allocated with <code>new</code>, but never <code>delete</code>d. Currently the function can return in two places, so you'll need to have <code>delete [] buffer</code> before those two places (more on strings like <code>buffer</code> next). [<em>edit:</em> <code>buffer</code> is allocated twice in the function. Be sure that it's freed before allocating it again.]</p></li>\n<li><p>Best Practice: You're using C-style strings in your C++ code, which means you need to allocate them yourself (like <code>buffer</code>), deallocate them yourself, and call the various string-managing functions. Instead, consider using C++'s <code>std::basic_string</code>-derived classes to handle the tedious details. I think the related changes you'd need to make are out of scope for a code review because of the heavy use of C-style strings in your code, so check out <a href=\"https://stackoverflow.com/search?q=c-style+std%3A%3Astring\">Stack Overflow's many questions and answers on the topic</a>.</p></li>\n<li><p>Potential Runtime Error / Best Practice: You're using <code>std::queue&lt;TCHAR*&gt;</code> to make a queue of strings, but the strings are not being copied to the queue, only referenced. The string's memory is not guaranteed to be correct once the string variable goes out of scope (I'm a little surprised it works [<em>edit:</em> it's not as broken as I first thought, but I still recommend the change mentioned here] ). You'll want to use <code>std::queue&lt;std::basic_string&lt;TCHAR&gt;&gt;</code> to ensure that copies are created and destroyed. More on strings in the previous note.</p></li>\n</ul>\n\n<p>Shortcomings that you mentioned:</p>\n\n<ol>\n<li><p>The leg-work in your code is being done from <code>WindowProc</code>, so additional messages cannot be processed until the work is finished. You could use a separate thread to do the work, but that topic is beyond the scope of this review.</p></li>\n<li><p>I think the memory leak is <code>buffer</code>, as mentioned above.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T21:18:23.367", "Id": "26487", "Score": "0", "body": "If I had deleted `buffer` inside `fileSearcher::findFilesRecursivelly`, I would have lost the original value to which WindowProc's `queue<TCHAR*> buffer` references. I've tried to delete it after sending message to textBoxOutput, but mysteriously it doesn't work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T02:11:26.047", "Id": "26501", "Score": "0", "body": "@0x6B6F77616C74 I see what you mean, thanks for the explanation. I can't think of a good one-line fix for that. Using `std::queue<std::basic_string<TCHAR>>` (my last bullet point) is probably the cleanest way to let you free up `buffer` by the end of the function without changing all the strings in your code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T18:37:59.620", "Id": "16305", "ParentId": "16303", "Score": "4" } } ]
{ "AcceptedAnswerId": "16305", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T16:09:45.710", "Id": "16303", "Score": "5", "Tags": [ "c++", "windows" ], "Title": "Review my file-searching program" }
16303
<p>I'm teaching myself Python via Zed Shaw's <a href="http://learnpythonthehardway.org/" rel="nofollow">LPTHW</a> and he suggested to me that I try to condense my code so I can call up bits of it within a function. Right now this is boggling my mind and I can't figure out a way to condense it that doesn't result in an error regarding global and local variables in reference to <code>weapons</code>. As it stands, this code works, but as you can see, it's long and gross.</p> <pre><code>### Shop / buy weapons room ############### def buy_weapon(weapons): global gold """big bit of code that allows you to buy a weapons from a weapon list. The function acts a little differently after level zero weapons""" global current_weapon if weapons == level_zero_weapons: sword_price = level_zero_price() blunt_price = level_zero_price() agile_price = level_zero_price() print t.bright_magenta_on_black + """ Please type in the weapon you want to buy. %s, price: %d gold pieces %s, price: %d gold pieces %s, price: %d gold pieces. """ % (weapons[0], sword_price, weapons[1], blunt_price,weapons[2], agile_price) weapon_choice = raw_input(":&gt; ") if weapons[0] in weapon_choice and gold &gt;= sword_price: character_sheet.remove(character_sheet[9]) gold = gold - sword_price character_sheet.insert(9, "You have %s gold pieces." % gold) current_weapon = weapons[0] inventory(weapons[0]) character_sheet.append("Current Weapon: %s" % current_weapon) barracks() elif weapons[1] in weapon_choice and gold &gt;= blunt_price: character_sheet.remove(character_sheet[9]) gold = gold - blunt_price character_sheet.insert(9, "You have %s gold pieces." % gold) current_weapon = weapons[1] inventory(weapons[1]) character_sheet.append("Current Weapon: %s" % current_weapon) barracks() elif weapons[2] in weapon_choice and gold &gt;= agile_price: character_sheet.remove(character_sheet[9]) gold = gold - agile_price character_sheet.insert(9, "You have %s gold pieces." % gold) current_weapon = weapons[2] inventory(weapons[2]) character_sheet.append("Current Weapon: %s" % current_weapon) barracks() else: print "I dont know what %s means" % weapon_choice next() buy_weapon(level_zero_weapons) elif weapons == level_one_weapons: sword_price = level_one_price() blunt_price = level_one_price() agile_price = level_one_price() print""" Type in the weapon you want to buy, type quit to return to the barracks. %s, price: %d gold pieces %s, price: %d gold pieces %s, price: %d gold pieces. """ % (weapons[0], sword_price, weapons[1], blunt_price, weapons[2], agile_price) weapon_choice = raw_input(":&gt; ") if weapons[0] in weapon_choice and gold &gt;= sword_price: character_sheet.remove(character_sheet[9]) gold = gold - sword_price character_sheet.insert(9, "You have %s gold pieces." % gold) current_weapon = weapons[0] inventory(weapons[0]) character_sheet.append("Current Weapon: %s" % current_weapon) barracks() elif weapons[1] in weapon_choice and gold &gt;= blunt_price: character_sheet.remove(character_sheet[9]) gold = gold - blunt_price character_sheet.insert(9, "You have %s gold pieces." % gold) current_weapon = weapons[1] inventory(weapons[1]) character_sheet.append("Current Weapon: %s" % current_weapon) barracks() elif weapons[2] in weapon_choice and gold &gt;= agile_price: character_sheet.remove(character_sheet[9]) gold = gold - agile_price character_sheet.insert(9, "You have %s gold pieces." % gold) current_weapon = weapons[2] inventory(weapons[2]) character_sheet.append("Current Weapon: %s" % current_weapon) barracks() elif "quit" in weapon_choice: barracks() else: print "Either you dont have enough money, or I dont know what %s means" % weapon_choice next() buy_weapon(level_one_weapons) elif weapons == level_two_weapons: sword_price = level_two_price() blunt_price = level_two_price() agile_price = level_two_price() print""" Type in the weapon you want to buy, type quit to return to the barracks. %s, price: %d gold pieces %s, price: %d gold pieces %s, price: %d gold pieces. """ % (weapons[0], sword_price, weapons[1], blunt_price,weapons[2], agile_price) weapon_choice = raw_input(":&gt; ") if weapons[0] in weapon_choice and gold &gt;= sword_price: character_sheet.remove(character_sheet[9]) gold = gold - sword_price character_sheet.insert(9, "You have %s gold pieces." % gold) current_weapon = weapons[0] inventory(weapons[0]) character_sheet.append("Current Weapon: %s" % current_weapon) barracks() elif weapons[1] in weapon_choice and gold &gt;= blunt_price: character_sheet.remove(character_sheet[9]) gold = gold - blunt_price character_sheet.insert(9, "You have %s gold pieces." % gold) current_weapon = weapons[1] inventory(weapons[1]) character_sheet.append("Current Weapon: %s" % current_weapon) barracks() elif weapons[2] in weapon_choice and gold &gt;= agile_price: character_sheet.remove(character_sheet[9]) gold = gold - agile_price character_sheet.insert(9, "You have %s gold pieces." % gold) current_weapon = weapons[2] inventory(weapons[2]) character_sheet.append("Current Weapon: %s" % current_weapon) barracks() elif "quit" in weapon_choice: barracks() else: print "Either you dont have enough money, or I dont know what %s means" % weapon_choice next() buy_weapon(level_two_weapons) elif weapons == level_three_weapons: sword_price = level_three_price() blunt_price = level_three_price() agile_price = level_three_price() print""" Type in the weapon you want to buy, type quit to return to the barracks. %s, price: %d gold pieces %s, price: %d gold pieces %s, price: %d gold pieces. """ % (weapons[0], sword_price, weapons[1], blunt_price,weapons[2], agile_price) weapon_choice = raw_input(":&gt; ") if weapons[0] in weapon_choice and gold &gt;= sword_price: character_sheet.remove(character_sheet[9]) gold = gold - sword_price character_sheet.insert(9, "You have %s gold pieces." % gold) current_weapon = weapons[0] inventory(weapons[0]) character_sheet.append("Current Weapon: %s" % current_weapon) barracks() elif weapons[1] in weapon_choice and gold &gt;= blunt_price: character_sheet.remove(character_sheet[9]) gold = gold - blunt_price character_sheet.insert(9, "You have %s gold pieces." % gold) current_weapon = weapons[1] inventory(weapons[1]) character_sheet.append("Current Weapon: %s" % current_weapon) barracks() elif weapons[2] in weapon_choice and gold &gt;= agile_price: character_sheet.remove(character_sheet[9]) gold = gold - agile_price character_sheet.insert(9, "You have %s gold pieces." % gold) current_weapon = weapons[2] inventory(weapons[2]) character_sheet.append("Current Weapon: %s" % current_weapon) barracks() elif "quit" in weapon_choice: barracks() else: print "Either you dont have enough money, or I dont know what %s means" % weapon_choice next() buy_weapon(level_three_weapons) elif weapons == level_four_weapons: sword_price = level_four_price() blunt_price = level_four_price() agile_price = level_four_price() print""" Type in the weapon you want to buy, type quit to return to the barracks. %s, price: %d gold pieces %s, price: %d gold pieces %s, price: %d gold pieces. """ % (weapons[0], sword_price, weapons[1], blunt_price,weapons[2], agile_price) weapon_choice = raw_input(":&gt; ") if weapons[0] in weapon_choice and gold &gt;= sword_price: character_sheet.remove(character_sheet[9]) gold = gold - sword_price character_sheet.insert(9, "You have %s gold pieces." % gold) current_weapon = weapons[0] inventory(weapons[0]) character_sheet.append("Current Weapon: %s" % current_weapon) barracks() elif weapons[1] in weapon_choice and gold &gt;= blunt_price: character_sheet.remove(character_sheet[9]) gold = gold - blunt_price character_sheet.insert(9, "You have %s gold pieces." % gold) current_weapon = weapons[1] inventory(weapons[1]) character_sheet.append("Current Weapon: %s" % current_weapon) barracks() elif weapons[2] in weapon_choice and gold &gt;= agile_price: character_sheet.remove(character_sheet[9]) gold = gold - agile_price character_sheet.insert(9, "You have %s gold pieces." % gold) current_weapon = weapons[2] inventory(weapons[2]) character_sheet.append("Current Weapon: %s" % current_weapon) barracks() elif "quit" in weapon_choice: barracks() else: print "Either you dont have enough money, or I dont know what %s means" % weapon_choice next() buy_weapon(level_four_weapons) else: print"~~~There is a bug somwhere, forgot to assign (weapons)\n\n\n" raw_input(t.white_on_red(""" Your current weapon is now a %s. Press Enter To Continue """ % current_weapon)) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T18:21:43.790", "Id": "26484", "Score": "2", "body": "You've certainly noticed the amount of duplication in your. Start by looking at similar pieces of code, extracting what is variable and writing functions for those bits with the variable aspects as parameters of the function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T22:28:29.653", "Id": "26490", "Score": "0", "body": "It seems as though the logical variable that would be in a paramater would be weapons but when i try to use that, i got global related errors" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T23:43:44.607", "Id": "26557", "Score": "0", "body": "After implementing the changes proposed in @GlennRogers excellent answer, the next step is getting rid of those `global`s! If you want to keep it simple for now and don't go object oriented, you can use for example a `dict` to save your state, replacing the multiple global variables and pass that around as a function parameter." } ]
[ { "body": "<p>As you've discovered, <code>global</code>s are hard to deal with.</p>\n\n<p>Assuming that you now know what to do with your repeated code, here's one method of dealing with them.</p>\n\n<p>If we start with a function:</p>\n\n<pre><code>INV_GOLD = 9\n\ndef buy_offered_weapon( offered_weapon, price ):\n global gold, current_weapon\n character_sheet.remove( character_sheet[INV_GOLD] )\n gold = gold - price\n character_sheet.insert( INV_GOLD, \"You have %s gold pieces.\" % gold ) \n current_weapon = offered_weapon\n add_to_inventory( offered_weapon )\n character_sheet.append( \"Current Weapon: %s\" % current_weapon )\n back_to_barracks()\n</code></pre>\n\n<p>Remove any global line and mark out which variables are neither local to the function, nor passed in as a parameter (this is obviously easier to do with smallish functions!).</p>\n\n<pre><code>def buy_offered_weapon( offered_weapon, price ):\n GLOBAL_character_sheet.remove( GLOBAL_character_sheet[INV_GOLD] )\n GLOBAL_gold = GLOBAL_gold - price\n GLOBAL_character_sheet.insert( INV_GOLD, \"You have %s gold pieces.\" % GLOBAL_gold ) \n GLOBAL_current_weapon = offered_weapon\n add_to_inventory( offered_weapon )\n GLOBAL_character_sheet.append( \"Current Weapon: %s\" % GLOBAL_current_weapon )\n back_to_barracks()\n</code></pre>\n\n<p>Notice any patterns in the GLOBAL parts, in the same way as you simplified your buy/sell function. Separate these out into \"access functions\" for the globals - in this way, you isolate the globals into a (hopefully) single point, and remove their (direct) use scattered elsewhere in the code.</p>\n\n<p>These access functions should be as small as possible.</p>\n\n<pre><code>def adjust_inventory_gold( gold_change ):\n GLOBAL_character_sheet.remove( GLOBAL_character_sheet[INV_GOLD] )\n GLOBAL_gold = GLOBAL_gold + gold_change\n GLOBAL_character_sheet.insert( INV_GOLD, \"You have %s gold pieces.\" % GLOBAL_gold ) \n\ndef set_current_weapon( weapon ):\n GLOBAL_current_weapon = weapon\n GLOBAL_character_sheet.append( \"Current Weapon: %s\" % GLOBAL_current_weapon )\n</code></pre>\n\n<p>Add back in the <code>global</code> statements as required:</p>\n\n<pre><code>def adjust_inventory_gold( gold_change ):\n global gold, character_sheet\n character_sheet.remove( character_sheet[INV_GOLD] )\n gold = gold + gold_change\n character_sheet.insert( INV_GOLD, \"You have %s gold pieces.\" % gold )\n\ndef set_current_weapon( weapon ):\n global current_weapon, character_sheet\n current_weapon = weapon\n character_sheet.append( \"Current Weapon: %s\" % current_weapon )\n</code></pre>\n\n<p>Note that <code>global character_sheet</code> isn't strictly required (you're not assigning to it), but it's useful making it explicit as documentation.</p>\n\n<pre><code>def buy_offered_weapon( offered_weapon, price ):\n adjust_inventory_gold( -price )\n add_to_inventory( offered_weapon )\n set_current_weapon( offered_weapon )\n back_to_barracks()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T13:50:35.650", "Id": "16321", "ParentId": "16304", "Score": "2" } } ]
{ "AcceptedAnswerId": "16321", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T17:56:08.897", "Id": "16304", "Score": "4", "Tags": [ "python", "console", "adventure-game" ], "Title": "Console weapons shop for adventure game" }
16304
<p>I need to merge two objects in a code path that is going to be heavily used. The code works, but I am concerned it is not optimized enough for speed and I am looking for any suggestions to improve/replace what I have come up with. I originally started working off an example at the end of this issue: <a href="https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically">https://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically</a>. That solution works well for simple objects. However, my needs have a twist to it which is where the performance concerns come in. I need to be able to support arrays such that </p> <ol> <li>an array of simple values will look for values in the new object and add those to the end of the existing object and </li> <li>an array of objects will either merge objects (based off existence of an id property) or push new objects (objects whose id property does not exist) to the end of the existing array.</li> </ol> <p>I do not need functions/method cloning and I don't care about hasOwnProperty since the objects go back to JSON strings after merging.</p> <p>Any suggestions to help me pull every last once of performance from this would be greatly appreciated.</p> <pre><code>var utils = require("util"); function mergeObjs(def, obj) { if (typeof obj == 'undefined') { return def; } else if (typeof def == 'undefined') { return obj; } for (var i in obj) { // if its an object if (obj[i] != null &amp;&amp; obj[i].constructor == Object) { def[i] = mergeObjs(def[i], obj[i]); } // if its an array, simple values need to be joined. Object values need to be remerged. else if(obj[i] != null &amp;&amp; utils.isArray(obj[i]) &amp;&amp; obj[i].length &gt; 0) { // test to see if the first element is an object or not so we know the type of array we're dealing with. if(obj[i][0].constructor == Object) { var newobjs = []; // create an index of all the existing object IDs for quick access. There is no way to know how many items will be in the arrays. var objids = {} for(var x= 0, l= def[i].length ; x &lt; l; x++ ) { objids[def[i][x].id] = x; } // now walk through the objects in the new array // if the ID exists, then merge the objects. // if the ID does not exist, push to the end of the def array for(var x= 0, l= obj[i].length; x &lt; l; x++) { var newobj = obj[i][x]; if(objids[newobj.id] !== undefined) { def[i][x] = mergeObjs(def[i][x],newobj); } else { newobjs.push(newobj); } } for(var x= 0, l = newobjs.length; x&lt;l; x++) { def[i].push(newobjs[x]); } } else { for(var x=0; x &lt; obj[i].length; x++) { var idxObj = obj[i][x]; if(def[i].indexOf(idxObj) === -1) { def[i].push(idxObj); } } } } else { def[i] = obj[i]; } } return def;} </code></pre> <p>The object samples to merge:</p> <pre><code>var obj1 = { "name" : "myname", "status" : 0, "profile": { "sex":"m", "isactive" : true}, "strarr":["one", "three"], "objarray": [ { "id": 1, "email": "a1@me.com", "isactive":true }, { "id": 2, "email": "a2@me.com", "isactive":false } ] }; var obj2 = { "name" : "myname", "status" : 1, "newfield": 1, "profile": { "isactive" : false, "city": "new York"}, "strarr":["two"], "objarray": [ { "id": 1, "isactive":false }, { "id": 2, "email": "a2modified@me.com" }, { "id": 3, "email": "a3new@me.com", "isactive" : true } ] }; </code></pre> <p>Once merged, this console.log(mergeObjs(obj1, obj2)) should produce this:</p> <pre><code>{ name: 'myname', status: 1, profile: { sex: 'm', isactive: false, city: 'new York' }, strarr: [ 'one', 'three', 'two' ], objarray: [ { id: 1, email: 'a1@me.com', isactive: false }, { id: 2, email: 'a2modified@me.com', isactive: false }, { id: 3, email: 'a3new@me.com', isactive: true } ], newfield: 1 } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T15:20:44.957", "Id": "26528", "Score": "0", "body": "Your code would be much easier to read if you used `continue` statements." } ]
[ { "body": "<p>I think the following is doing the same thing, you'll need to check it. It should be pretty fast, it just references objects that don't exist on the target. I changed names from <code>def</code> and <code>obj</code> to <code>target</code> and <code>source</code> because they make more sense to me.</p>\n\n<p>I also included as simple <code>isArray</code> function. Note that I don't like using the constructor property as it's public and you might get an own property rather than the inherited one, so I changed the test for object.</p>\n\n<p>If you test of an object, then for an array, what falls through should be a primitve. There are a lot of assumptions here, I'd implement a bit more checking to make sure I was getting what I expected.</p>\n\n<pre><code>function isArray(o) {\n return Object.prototype.toString.call(o) == \"[object Array]\";\n}\n\n// Assumes that target and source are either objects (Object or Array) or undefined\n// Since will be used to convert to JSON, just reference objects where possible\nfunction mergeObjects(target, source) {\n\n var item, tItem, o, idx;\n\n // If either argument is undefined, return the other.\n // If both are undefined, return undefined.\n if (typeof source == 'undefined') {\n return source;\n } else if (typeof target == 'undefined') {\n return target;\n }\n\n // Assume both are objects and don't care about inherited properties\n for (var prop in source) {\n item = source[prop];\n\n if (typeof item == 'object' &amp;&amp; item !== null) {\n\n if (isArray(item) &amp;&amp; item.length) {\n\n // deal with arrays, will be either array of primitives or array of objects\n // If primitives\n if (typeof item[0] != 'object') {\n\n // if target doesn't have a similar property, just reference it\n tItem = target[prop];\n if (!tItem) {\n target[prop] = item;\n\n // Otherwise, copy only those members that don't exist on target\n } else {\n\n // Create an index of items on target\n o = {};\n for (var i=0, iLen=tItem.length; i&lt;iLen; i++) {\n o[tItem[i]] = true\n }\n\n // Do check, push missing\n for (var j=0, jLen=item.length; j&lt;jLen; j++) {\n\n if ( !(item[j] in o) ) {\n tItem.push(item[j]);\n } \n }\n }\n } else {\n // Deal with array of objects\n // Create index of objects in target object using ID property\n // Assume if target has same named property then it will be similar array\n idx = {};\n tItem = target[prop]\n\n for (var k=0, kLen=tItem.length; k&lt;kLen; k++) {\n idx[tItem[k].id] = tItem[k];\n }\n\n // Do updates\n for (var l=0, ll=item.length; l&lt;ll; l++) {\n // If target doesn't have an equivalent, just add it\n if (!(item[l].id in idx)) {\n tItem.push(item[l]);\n } else {\n mergeObjects(idx[item[l].id], item[l]);\n }\n } \n }\n } else {\n // deal with object\n mergeObjects(target[prop],item);\n }\n\n } else {\n // item is a primitive, just copy it over\n target[prop] = item;\n }\n }\n return target;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T15:20:05.470", "Id": "26527", "Score": "0", "body": "You should use `===` and `!==`. Inverting those ifs inside the for and using `continue` would make the method a lot more readable too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T23:54:20.160", "Id": "26559", "Score": "0", "body": "@ANeves—I only use strict equality where it's actually needed (e.g. `typeof item == 'object' && item !== null`), I think it's better to understand operations rather than follow a rule without thinking \"why do I need that operator here?\". The \"inverted\" if's make more sense to me, e.g. `!(item[j] in o)` would be `item[j] !in o` if there was a `!in` opertator or compound operator (Maybe `NoIn`?). Using `if..continue..else` is long winded while requiring the same logical thought, but wouldn't change one to the other without good reason." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T10:31:28.427", "Id": "26574", "Score": "0", "body": "about the ifs, I meant things like `if (typeof item !== 'object' || item === null) { target[prop] = item; continue; }`. I think it would improve the readability." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T07:02:34.207", "Id": "16319", "ParentId": "16306", "Score": "5" } } ]
{ "AcceptedAnswerId": "16319", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-07T18:53:08.417", "Id": "16306", "Score": "7", "Tags": [ "javascript", "node.js" ], "Title": "How to Optimize Merge of Two Objects That Include Arrays of Objects" }
16306
<p>I've been learning about Monte Carlo simulations on MIT's intro to programming class, and I'm trying to implement one that calculates the probability of flipping a coin heads side up 4 times in a row out of ten flips.</p> <p>Basically, I calculate if the current flip in a 10 flip session is equal to the prior flip, and if it is, I increment a counter. Once that counter has reached 3, I exit the loop even if I haven't done all 10 coin flips since subsequent flips have no bearing on the probability. Then I increment a counter counting the number of flip sessions that successfully had 4 consecutive heads in a row. At the end, I divide the number of successful sessions by the total number of trials. </p> <p>The simulation runs 10,000 trials.</p> <pre><code>def simThrows(numFlips): consecSuccess = 0 ## number of trials where 4 heads were flipped consecutively coin = 0 ## to be assigned to a number between 0 and 1 numTrials = 10000 for i in range(numTrials): consecCount = 0 currentFlip = "" priorFlip = "" while consecCount &lt;= 3: for flip in range(numFlips): coin = random.random() if coin &lt; .5: currentFlip = "Heads" if currentFlip == priorFlip: consecCount += 1 priorFlip = "Heads" else: consecCount = 0 priorFlip = "Heads" elif coin &gt; .5: currentFlip = "Tails" if currentFlip == priorFlip: consecCount = 0 priorFlip = "Tails" else: consecCount = 0 priorFlip = "Tails" break if consecCount &gt;= 3: print("Success!") consecSuccess += 1 print("Probability of getting 4 or more heads in a row: " + str(consecSuccess/numTrials)) simThrows(10) </code></pre> <p>The code seems to work (gives me consistent results each time that seem to line up to the analytic probability), but it's a bit verbose for such a simple task. Does anyone see where my code can get better? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T23:59:44.497", "Id": "26491", "Score": "1", "body": "Why is the priorFlip when you get Tails being set to Heads and why are you incrementing the consecCount? I'm not sure how this is going to give you the right probability?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:05:07.067", "Id": "26492", "Score": "0", "body": "Oops, accidentally pasted my old code -- the updated version has the \"Tails\" fix. As for incrementing consecCount, it's only incremented when priorFlip == consecFlip. It is reset to 0 otherwise. Once it hits 3, it exits the loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:06:07.803", "Id": "26493", "Score": "1", "body": "So your current code will do either 4 Heads in a row or 4 Tails . . . is that intentional?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:08:11.043", "Id": "26494", "Score": "0", "body": "Ooops! Meant to change that to consecCount = 0 for each of the Tails cases. Now does it look okay?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:13:52.237", "Id": "26495", "Score": "0", "body": "You have several code errors . . . I've posted a simplified version, trying to stick to the spirit of your code, and pointed out some of the errors . . ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:30:12.147", "Id": "26496", "Score": "0", "body": "Made a few more optimizations after looking at this a bit more . . ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T15:21:41.967", "Id": "26529", "Score": "0", "body": "I'm being nitpicky (but for the benefit of your code!), but your code doesn't account for a random() == .500--you have less than and greater than. Since random gives you 0-1.0 (non-inclusive 1.0), you can adjust this with >= .50 on your elif or to use an unspecified ELSE instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-23T08:03:53.740", "Id": "96194", "Score": "0", "body": "Why not try out this pattern posted in April this year http://code.activestate.com/recipes/578868-monte-carlo-engine-simple-head-tail-model/" } ]
[ { "body": "<p>So a few errors/simplifications I can see:</p>\n\n<ol>\n<li>You're incrementing <code>consecCount</code> if you have either two heads or two\ntails. </li>\n<li>setting the <code>priorFlip</code> value can be done regardless of what\nthe prior flip was </li>\n<li>Your <code>while</code> loop doesn't do anything as you have a\nfor loop in it, then break right after it, so you'll always make all\n10 tosses. A while loop isn't constantly checking the value inside\nof it; only when it finishes executing the code block. As you <code>break</code> after the <code>for</code> loop, the <code>while</code> condition will never be checked</li>\n<li>There's no reason to track the previous flip, if you always reset the count on a tail</li>\n<li>while the odds are small, you'll be throwing away any toss that is equal to .5</li>\n</ol>\n\n<p>Anyway, here's my first pass at a simplified version:</p>\n\n<pre><code>def simThrows(numFlips):\n consecSuccess = 0 ## number of trials where 4 heads were flipped consecutively\n coin = 0 ## to be assigned to a number between 0 and 1\n numTrials = 10000\n for i in range(numTrials):\n consecCount = 0\n for flip in range(numFlips):\n coin = random.random()\n #since random.random() generates [0.0, 1.0), we'll make the lower bound inclusive\n if coin &lt;= .5:\n #Treat the lower half as heads, so increment the count\n consecCount += 1 \n # No need for an elif here, it wasn't a head, so it must have been a tail\n else:\n # Tails, so we don't care about anything, just reset the count\n consecCount = 0 \n #After each flip, check if we've had 4 consecutive, otherwise keep flipping\n if consecCount &gt;= 3:\n print(\"Success!\")\n consecSuccess += 1\n # we had enough, so break out of the \"for flip\" loop\n # we'll end up in the for i in range loop . . .\n break \n print(\"Probability of getting 4 or more heads in a row: \" + str(consecSuccess/numTrials))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:13:08.540", "Id": "16312", "ParentId": "16310", "Score": "2" } }, { "body": "<p>@Keith Randall showed a short soltion, but verbosity is not necessary a bad thing. Often an important thing is to decomopose the task into separate sub-tasks, which are generic and reusable:</p>\n\n<pre><code>import random\n\ndef montecarlo(experiment, trials):\n r = 0\n for i in range(trials):\n experiment.reset()\n r += 1 if experiment.run() else 0\n return r / float(trials)\n\n\nclass Coinrowflipper():\n def __init__(self, trials, headsinrow):\n self.headsinrow = headsinrow\n self.trials = trials\n self.reset()\n def reset(self):\n self.count = 0\n def run(self):\n for i in range(self.trials):\n if random.random() &lt; 0.5:\n self.count += 1\n if self.count == self.headsinrow:\n return True\n else:\n self.count = 0\n return False\n\nc = Coinrowflipper(10,4)\nprint montecarlo(c, 1000)\n</code></pre>\n\n<p>This way you have a generic monte-carlo experiment, and a generic heads-in a row solution.</p>\n\n<p>Note: using strings (<code>\"Heads\"</code>) to mark internal state is discouraged in any programming language...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:22:53.913", "Id": "16313", "ParentId": "16310", "Score": "4" } }, { "body": "<p>When you're writing code for educational purposes (or sometimes other purposes), <strong>verbose is good</strong> because it helps you understand what's really going on. So making the code shorter or snappier or whatever is not necessarily going to make it better.</p>\n\n<p>With that disclaimer out of the way: one of the most common ways to condense Python code is to use list comprehensions or generators instead of loops. A list comprehension is what you use when you're constructing a list element by element: in its simplest form, instead of this,</p>\n\n<pre><code>the_list = []\nfor something in something_else:\n the_list.append(func(something))\n</code></pre>\n\n<p>you write this:</p>\n\n<pre><code>the_list = [func(something) for something in something_else]\n</code></pre>\n\n<p>If you're doing something else instead of creating a list, you can have Python create an object that generates the elements on demand, rather than actually creating a list out of them. An object of that sort is called a generator and you can create one like this:</p>\n\n<pre><code>the_generator = (func(something) for something in something_else)\n</code></pre>\n\n<p>You can omit the parentheses when the generator is passed to another function as an argument, though.</p>\n\n<pre><code>the_sum = sum(func(something) for something in something_else)\n</code></pre>\n\n<p>would be equivalent to, but better than,</p>\n\n<pre><code>count = 0\nfor something in something_else:\n count += func(something)\n</code></pre>\n\n<p>There are a lot of functions in Python that take iterables (list, generators, etc.) and \"condense\" them into one value using some sort of operation. You can also create your own, corresponding to whatever you would be doing to the result of the loop. You can convert most loops into generator expressions this way.</p>\n\n<p>So let's investigate how you could use a generator to represent the sequences of consecutive throws in each trial. You can create a generator that produces 10 random numbers easily:</p>\n\n<pre><code>(random.random() for i in xrange(10))\n</code></pre>\n\n<p>(this is for Python 2.x; <code>xrange</code> was renamed to <code>range</code> for Python 3). Or you can create a generator that produces 10 random values which are either 0 or 1:</p>\n\n<pre><code>(random.randint(0,1) for i in xrange(10))\n</code></pre>\n\n<p>That saves you from having to check each random number against 0.5. In fact, you could produce a generator that produces 10 randomly chosen words, \"Heads\" or \"Tails\", like so:</p>\n\n<pre><code>(random.choice((\"Heads\",\"Tails\")) for i in xrange(10))\n</code></pre>\n\n<p>but it'll be easier to stick with numbers. (It's usually better to represent things with numbers or objects than with strings.)</p>\n\n<p>But perhaps you're thinking, \"why are you telling me to make 10 numbers when I only have to check until I find a group of four consecutive heads?\" For one thing, if you're just flipping 10 coins each time, it really doesn't matter because you'll make the computer flip at most 6, and on average 3, extra coins in each trial. That doesn't take very long - it'll extend the runtime of this part of your program by 50%, but we're talking 50% of a fraction of a second. It's not worth the effort to figure out how to do it for such a small number of flips. But if each flip had, say, a billion trials, then you would definitely want to stop early. Fortunately, a generator can do this for you! Since generators produce their elements only on demand, you can stop taking elements from it once you get what you want, and not waste much of any computation. I'll address this more later.</p>\n\n<p>Anyway, suppose we have our generator that produces 10 binary values 0 (tails) or 1 (heads). Is there a way to go through this and check to see whether there is a sequence of four or more heads? It turns out that just such a function is provided in <a href=\"http://docs.python.org/py3k/library/itertools.html#itertools.groupby\"><code>itertools.groupby</code></a>, which takes any iterable (list, generator, etc.) and groups consecutive identical elements. An example of its usage is</p>\n\n<pre><code>for k, g in itertools.groupby([1,0,0,1,1,1,1,0,0,0]):\n print k, list(g)\n</code></pre>\n\n<p>and this would print out something like</p>\n\n<pre><code>1 [1]\n0 [0,0]\n1 [1,1,1,1]\n0 [0,0,0]\n</code></pre>\n\n<p>So you can check for four or more consecutive heads by just looking at the length of the group and whether the key is heads or tails.</p>\n\n<pre><code>for k, g in itertools.groupby(random.randint(0,1) for i in xrange(10)):\n if k and len(g) &gt;= 4:\n # got a run of 4 or more consecutive heads!\n # wait, what now?\n</code></pre>\n\n<p>(In Python, 1 is true and 0 is false in a boolean context, so <code>if k</code> is equivalent to <code>if k == 1</code>.) OK, what shall we do with our run of 4 or more consecutive heads? Well, you're trying to find the number of trials in which this occurs. So it probably makes sense to set a <code>success</code> flag if this happens.</p>\n\n<pre><code>success = False\nfor k, g in itertools.groupby(random.randint(0,1) for i in xrange(10)):\n if k and len(g) &gt;= 4:\n success = True\n break # this stops asking the generator for new values\n</code></pre>\n\n<p>But wait! This is starting to look a lot like the kind of loop that can be converted to a generator expression, isn't it? The only catch is that we're not adding anything up or constructing a list. But there is another function, <code>any</code>, that will go through a generator until it finds an element which matches a condition, and that's just what this <code>for</code> loop does. So you could write this as</p>\n\n<pre><code>success = any(k and len(g) &gt;= 4 for k, g in\n itertools.groupby(random.randint(0,1) for i in xrange(10))\n</code></pre>\n\n<p>Now finally, you'll want to count how many times this happens over, say, 10000 trials. So you might write that as something like this:</p>\n\n<pre><code>successes = 0\nfor i in xrange(10000):\n if any(k and len(g) &gt;= 4 for k, g in\n itertools.groupby(random.randint(0,1) for i in xrange(10)):\n successes += 1\n</code></pre>\n\n<p>But of course, we can also convert <em>this</em> to a generator, since you're just adding up numbers:</p>\n\n<pre><code>successes = sum(1 for i in xrange(10000)\n if any(k and len(g) &gt;= 4 for k, g in\n itertools.groupby(random.randint(0,1) for i in xrange(10)))\n</code></pre>\n\n<p>The generator produces a <code>1</code> each time it finds a group of 4 consecutive <code>1</code>s among the 10 random numbers generated.</p>\n\n<p>The last thing you'd want to do is divide by the total number of trials. Well, actually, what you really want to do is calculate the average instead of the sum, and in some places you can find a function <code>mean</code> which is kind of like <code>sum</code> except that it calculates the mean instead of the total. You could use such a function if you had it. But I don't know that one is in the Python standard library, so you can just do the division:</p>\n\n<pre><code>probability = sum(1 for i in xrange(10000)\n if any(k and len(g) &gt;= 4 for k, g in\n itertools.groupby(random.randint(0,1) for i in xrange(10))) / 10000\n</code></pre>\n\n<p>So the task you're trying to accomplish can actually be written in one line of Python. But it's a rather complicated line, and I wouldn't necessarily recommend actually doing this. Sometimes it's good to use a good old fashioned <code>for</code> loop to keep the code clear. More often, though, it's better to split your code up into modular pieces that are more useful than just what you're using them for.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T00:58:39.547", "Id": "16314", "ParentId": "16310", "Score": "9" } }, { "body": "<p>Based on @Karoly Horvath but different enough to be a standalone answer.</p>\n\n<p>A class is very much overkill for this problem, I have achieved the same functionality with a function.</p>\n\n<pre><code>import random\n\ndef montecarlo(experiment, trials):\n positive = 0\n for _ in range(trials):\n positive += 1 if experiment() else 0\n return positive / float(trials)\n\ndef successive_heads(trials,heads_in_a_row):\n count = 0\n for _ in range(trials):\n if random.random() &lt; 0.5:\n count += 1\n if count == heads_in_a_row:\n return True\n else:\n count = 0\n return False\n\nprint(montecarlo(lambda: successive_heads(100,10), 10000))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-13T19:02:22.530", "Id": "84036", "ParentId": "16310", "Score": "1" } } ]
{ "AcceptedAnswerId": "16314", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T23:52:10.790", "Id": "16310", "Score": "5", "Tags": [ "python", "simulation", "statistics" ], "Title": "Monte Carlo coin flip simulation" }
16310
<p>I am trying to append data to a table based on the ajax returned data. </p> <p>My codes work but it seems ugly. I was wondering if anyone here can help me to simplfy it. Thanks a lot!</p> <pre><code> ajax.callback=function(data){ for (var i=0; i&lt;dataObj[0].data.length; i++){ var td=document.createElement('td'); td.innerHTML=dataObj[0].data[i].ID; var td2=document.createElement('td'); td2.innerHTML=dataObj[0].data[i].test; var td3=document.createElement('td'); td3.innerHTML=dataObj[0].data[i].year; var td4=document.createElement('td'); td4.innerHTML=dataObj[0].data[i].code; var td5=document.createElement('td'); td5.innerHTML=dataObj[0].data[i].Label; var td6=document.createElement('td'); td6.innerHTML=dataObj[0].data[i].contents; var td7=document.createElement('td'); td7.innerHTML=dataObj[0].data[i].test; var tr=document.createElement('tr'); tr.appendChild(td); tr.appendChild(td2); tr.appendChild(td3); tr.appendChild(td4); tr.appendChild(td5); tr.appendChild(td6); tr.appendChild(td7); $('#Table').append(tr); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T22:13:00.073", "Id": "26515", "Score": "0", "body": "Store your tr's as one dom fragment and do not append them until after the for loop. Other than that, it's not going to be less ugly without using a templating system or having your server return html." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T15:27:02.307", "Id": "26531", "Score": "0", "body": "Should you be using `data` and not `dataObj`?" } ]
[ { "body": "<p>You could do:</p>\n\n<pre><code>ajax.callback=function(data){\n var elements = [\"ID\", \"test\", \"year\", \"code\", \"Label\", \"contents\", \"test\"];\n\n for (var i=0; i&lt;dataObj[0].data.length; i++){\n var td;\n var tr=document.createElement('tr');\n\n for (var j=0; j &lt; elements.length; ++j){\n td = document.createElement('td');\n td.innerHTML=dataObj[0].data[i][elements[j]];\n tr.appendChild(td);\n }\n\n $('#Table').append(tr);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T22:16:40.243", "Id": "26516", "Score": "0", "body": "`document.createElement` and `innerHtml` is not very jQuery'ish. Why not just `td = $('<td>').html(dataObj[0].data[i][elements[j]);` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T22:23:55.043", "Id": "26517", "Score": "1", "body": "I'm not really familiar enough with jQuery to put stuff like that in. I was just showing him a way he could refactor his js in a js sense. If that's valid jquery, then by all means, make an answer with that instead." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T22:35:20.567", "Id": "26518", "Score": "0", "body": "Thanks so much, your code works except dataObj[0].data[i].elements[j] doesn't equal dataObj[0].data[i].ID\n\ndataObj[0].data[i].elements[j] give me can't read property of 0 errro +1 though" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T22:37:12.713", "Id": "26519", "Score": "0", "body": "@Rouge I made a little mistake in closing the [ bracket, so it may have been unclear. It's not .elements[j], it's [elements[j]]." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T22:13:23.427", "Id": "16323", "ParentId": "16322", "Score": "5" } }, { "body": "<p>One (however not the most performant) of the more readable ways of doing this:</p>\n\n<pre><code>var tr = '&lt;tr&gt;\\\n &lt;td&gt;{id}&lt;/td&gt;\\\n &lt;td&gt;{year}&lt;/td&gt;\\\n ...\n &lt;td&gt;{test}&lt;/td&gt;\\\n&lt;/tr&gt;';\n\ntr = tr.replace(/{id}/, dataObj[0].data[i].ID)\n .replace(/{year}/, dataObj[0].data[i].year)\n .replace(/{test}/, dataObj[0].data[i].test);\n\n$('#Table').append(tr);\n</code></pre>\n\n<p>Or use some templating engine.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T22:14:56.283", "Id": "16324", "ParentId": "16322", "Score": "1" } }, { "body": "<p>You could use</p>\n\n<pre><code>ajax.callback=function(data){\n var keys=[\"ID\",\"test\",\"year\",\"code\",\"Label\",\"contents\",\"test\"],\n tr=document.createElement('tr'),\n td=document.createElement('td');\n for (var i=0, li=dataObj[0].data.length; i&lt;li; i++){\n var newTr=tr.clonenode(false);\n for(var j=0, lj=keys.length; j&lt;lj; j++){\n var newTd=td.cloneNode(false);\n newTd.innerHTML=dataObj[0].data[i][keys[j]];\n newTr.appendChild(newTd);\n }\n document.getElementById('Table').appendChild(newTr);\n }\n}\n</code></pre>\n\n<p>It's pretty much like CrazyCasta's answer, but cloning nodes is faster than creating them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T22:20:18.170", "Id": "16325", "ParentId": "16322", "Score": "0" } } ]
{ "AcceptedAnswerId": "16323", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T22:08:19.153", "Id": "16322", "Score": "0", "Tags": [ "javascript", "jquery", "ajax" ], "Title": "How to append ajax return data to a table" }
16322
<p>Can't seem to find one, so trying to build a very simple but fast implementation. Thought I would post on SO for review/feedback, and so that others can just copy/paste for their own use.</p> <p>I'm using a Dictionary and LinkedList, with a non-granular lock. Basic benchmark included below:</p> <pre><code>public class LRUDictionary&lt;TKey,TValue&gt; : IDictionary&lt;TKey,TValue&gt; { private Dictionary&lt;TKey, LinkedListNode&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;&gt;_dict= new Dictionary&lt;TKey, LinkedListNode&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;&gt;(); private LinkedList&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; _list = new LinkedList&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;(); public int Max_Size { get; set; } public LRUDictionary(int maxsize) { Max_Size = maxsize; } public void Add(TKey key, TValue value) { lock (_dict) { LinkedListNode&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; node; if (_dict.TryGetValue(key, out node)) { _list.Remove(node); _list.AddFirst(node); } else { node = new LinkedListNode&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;( new KeyValuePair&lt;TKey, TValue&gt;(key, value)); _dict.Add(key, node); _list.AddFirst(node); } if (_dict.Count &gt; Max_Size) { var nodetoremove = _list.Last; if (nodetoremove != null) Remove(nodetoremove.Value.Key); } } } public bool Remove(TKey key) { lock (_dict) { LinkedListNode&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; removednode; if (_dict.TryGetValue(key, out removednode)) { _dict.Remove(key); _list.Remove(removednode); return true; } else return false; } } public bool TryGetValue(TKey key, out TValue value) { LinkedListNode&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; node; bool result = false; lock (_dict) result = _dict.TryGetValue(key, out node); if (node != null) value = node.Value.Value; else value = default(TValue); return result; } [rest of IDictionary not implemented yet] } </code></pre> <p>Benchmark:</p> <pre><code>class Program { static Random rand = new Random(); static void Main(string[] args) { var lruspace = 50; var setsize = 100; var iterations = 1000 * 1000; var lrucache = new LRUDictionary&lt;int, int&gt;(lruspace); var watch = new Stopwatch(); watch.Start(); Parallel.For(0, iterations, (i) =&gt; { lrucache.Add(rand.Next(setsize), 0); lrucache.Add(rand.Next(setsize), 0); lrucache.Remove(rand.Next(setsize)); lrucache.Add(rand.Next(setsize), 0); lrucache.Remove(rand.Next(setsize)); lrucache.Remove(rand.Next(setsize)); lrucache.Add(rand.Next(setsize), 0); lrucache.Remove(rand.Next(setsize)); lrucache.Add(rand.Next(setsize), 0); lrucache.Add(rand.Next(setsize), 0); lrucache.Add(rand.Next(setsize), 0); }); Console.WriteLine(watch.ElapsedMilliseconds); Console.ReadLine(); } } </code></pre> <p>Output:</p> <pre><code>2592ms </code></pre> <p>Is this the best way to go? Any obvious improvements?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T16:18:22.663", "Id": "26522", "Score": "0", "body": "your lock sections are too big, also if the thread count goes up, two threads can enter `lock` at the same time. which breaks your correctness." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T16:19:10.213", "Id": "26523", "Score": "0", "body": "before you look at performance, look at correctness. i doubt for several threads you will have correct results" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T16:21:08.410", "Id": "26524", "Score": "0", "body": "I'm starting with big locks to ensure correctness. How can two threads enter the lock?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T16:14:39.423", "Id": "26525", "Score": "0", "body": "You might want to take a look at [C5](http://www.itu.dk/research/c5/Release1.1/c5doc/types/C5.HashedLinkedList_1.htm) which is available on its Github [repo](https://github.com/sestoft/C5/) where you can see its [source](https://github.com/sestoft/C5/blob/master/C5/linkedlists/HashedLinkedList.cs)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T16:39:03.467", "Id": "26526", "Score": "0", "body": "This one from Lucene.Net is pretty neat. http://svn.apache.org/repos/asf/lucene.net/trunk/src/core/Util/Cache/ It is not threadsafe by default, but once you instanciated it, simply call `GetSynchronizedCache()` to get a ThreadSafe wrapper of it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T16:49:10.420", "Id": "37410", "Score": "0", "body": "Is the C5 implementation any good - It's a huge class! Good performance?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T13:34:33.630", "Id": "67854", "Score": "1", "body": "I found three .NET implementations with a quick Googling: - http://stackoverflow.com/questions/754233/is-it-there-any-lru-implementation-of-idictionary\n- http://www.codeproject.com/Articles/23396/A-High-Performance-Multi-Threaded-LRU-Cache\n- http://stackoverflow.com/questions/615648/how-can-i-make-my-simple-net-lru-cache-faster" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-04T23:47:10.223", "Id": "98818", "Score": "0", "body": "@DarthVader two threads can't enter the lock section at the same time -- and I don't see the deadlock issue you mention -- however, I agree with the recommendation to shrink the lock areas to only the absolutely necessary sections." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-04T23:48:55.717", "Id": "98819", "Score": "0", "body": "C5 doesn't have an LRU dictionary, but it does have a double linked hash list (HashedLinkedList) that might be useful in implementing an LRU." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-04T23:57:29.690", "Id": "98821", "Score": "0", "body": "Additionally, @HarryMexican, I would recommend that this class deserves some unit tests (i.e. writing a primitive class like this, with no real external dependencies, is a great way to start teaching yourself TDD. Check out the early chapters of the book 'The Clean Coder' by Robert C. Martin for a good introduction to this philosophy.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-10T02:11:56.090", "Id": "169374", "Score": "0", "body": "LinkedList.Remove is a O(n) operation, i.e. gets slower proportional to the number of items in the list (or, more precise, the number of items it has to iterate over until the item is found)." } ]
[ { "body": "<p>Another implementation is available <a href=\"http://csharptest.net/browse/src/Library/Collections/LurchTable.cs\" rel=\"nofollow\">here</a>.</p>\n\n<p>The benefit to the approach in the <code>LunchTable.cs</code> is that it does not aggregate an existing dictionary implementation, but rather is both the dictionary and linked list rolled into one class. Thread-safe and ready to go, see the <a href=\"http://csharptest.net/1279/introducing-the-lurchtable-as-a-c-version-of-linkedhashmap/\" rel=\"nofollow\">discussion here</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T21:20:51.433", "Id": "40298", "ParentId": "16326", "Score": "1" } }, { "body": "<p>Whilst your code is thread safe, since you have a global lock protecting the dictionary (and the lock is relatively long lived), it will be a serious bottleneck under concurrent load. The principal scalability limit in concurrent applications is the exclusive resource lock.</p>\n<p>The chart below shows throughput with an increasing degree of parallelism on a 16 core VM for concurrent LRU reads and writes. It compares an implementation of LRU that does not have a global lock, to an implementation fundamentally the same as your code (with a global lock).</p>\n<p><a href=\"https://i.stack.imgur.com/1WExx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1WExx.png\" alt=\"enter image description here\" /></a></p>\n<p>In this test I set the concurrent dictionary concurrency level = number of threads. I believe the unusual dip at the beginning is caused by <a href=\"https://en.wikipedia.org/wiki/False_sharing\" rel=\"nofollow noreferrer\">false sharing</a>. It's old now, but <a href=\"http://igoro.com/archive/gallery-of-processor-cache-effects/\" rel=\"nofollow noreferrer\">gallery of processor cache effects</a> has a nice description.</p>\n<p>The implementation with better throughput is a thread safe pseudo LRU designed for concurrent workloads. Latency is very close to ConcurrentDictionary, ~10x faster than MemoryCache and hit rate is better than a conventional LRU algorithm (these are the other two factors that will determine performance). A full analysis provided in the github link below.</p>\n<p>Usage of the ConcurrentLru looks like this:</p>\n<pre><code>int capacity = 666;\nvar lru = new ConcurrentLru&lt;int, SomeItem&gt;(capacity);\n\nvar value = lru.GetOrAdd(1, (k) =&gt; new SomeItem(k));\n</code></pre>\n<p>GitHub: <a href=\"https://github.com/bitfaster/BitFaster.Caching\" rel=\"nofollow noreferrer\">https://github.com/bitfaster/BitFaster.Caching</a></p>\n<pre><code>Install-Package BitFaster.Caching\n</code></pre>\n<p>Below is the complete source code for the ClassicLRU tested above. It has shorter span locks and uses ConcurrentDictionary. It's not intended for production use (it may have bugs) - it's just to illustrate that even when taking narrow locks throughput is still bad under concurrent load.</p>\n<pre><code>public sealed class ClassicLru&lt;K, V&gt; : ICache&lt;K, V&gt;\n{\n private readonly int capacity;\n private readonly ConcurrentDictionary&lt;K, LinkedListNode&lt;LruItem&gt;&gt; dictionary;\n private readonly LinkedList&lt;LruItem&gt; linkedList = new LinkedList&lt;LruItem&gt;();\n\n private long requestHitCount;\n private long requestTotalCount;\n\n public ClassicLru(int capacity)\n : this(Defaults.ConcurrencyLevel, capacity, EqualityComparer&lt;K&gt;.Default)\n { \n }\n\n public ClassicLru(int concurrencyLevel, int capacity, IEqualityComparer&lt;K&gt; comparer)\n {\n if (capacity &lt; 3)\n {\n throw new ArgumentOutOfRangeException(&quot;Capacity must be greater than or equal to 3.&quot;);\n }\n\n if (comparer == null)\n {\n throw new ArgumentNullException(nameof(comparer));\n }\n\n this.capacity = capacity;\n this.dictionary = new ConcurrentDictionary&lt;K, LinkedListNode&lt;LruItem&gt;&gt;(concurrencyLevel, this.capacity + 1, comparer);\n }\n\n public int Count =&gt; this.linkedList.Count;\n\n public double HitRatio =&gt; (double)requestHitCount / (double)requestTotalCount;\n\n ///&lt;inheritdoc/&gt;\n public bool TryGet(K key, out V value)\n {\n Interlocked.Increment(ref requestTotalCount);\n\n LinkedListNode&lt;LruItem&gt; node;\n if (dictionary.TryGetValue(key, out node))\n {\n LockAndMoveToEnd(node);\n Interlocked.Increment(ref requestHitCount);\n value = node.Value.Value;\n return true;\n }\n\n value = default(V);\n return false;\n }\n\n public V GetOrAdd(K key, Func&lt;K, V&gt; valueFactory)\n {\n if (this.TryGet(key, out var value))\n {\n return value;\n }\n\n var node = new LinkedListNode&lt;LruItem&gt;(new LruItem(key, valueFactory(key)));\n\n if (this.dictionary.TryAdd(key, node))\n {\n LinkedListNode&lt;LruItem&gt; first = null;\n\n lock (this.linkedList)\n {\n if (linkedList.Count &gt;= capacity)\n {\n first = linkedList.First;\n linkedList.RemoveFirst();\n }\n\n linkedList.AddLast(node);\n }\n\n // Remove from the dictionary outside the lock. This means that the dictionary at this moment\n // contains an item that is not in the linked list. If another thread fetches this item, \n // LockAndMoveToEnd will ignore it, since it is detached. This means we potentially 'lose' an \n // item just as it was about to move to the back of the LRU list and be preserved. The next request\n // for the same key will be a miss. Dictionary and list are eventually consistent.\n // However, all operations inside the lock are extremely fast, so contention is minimized.\n if (first != null)\n {\n dictionary.TryRemove(first.Value.Key, out var removed);\n\n if (removed.Value.Value is IDisposable d)\n {\n d.Dispose();\n }\n }\n\n return node.Value.Value;\n }\n\n return this.GetOrAdd(key, valueFactory);\n }\n\n public bool TryRemove(K key)\n {\n if (dictionary.TryRemove(key, out var node))\n {\n // If the node has already been removed from the list, ignore.\n // E.g. thread A reads x from the dictionary. Thread B adds a new item, removes x from \n // the List &amp; Dictionary. Now thread A will try to move x to the end of the list.\n if (node.List != null)\n {\n lock (this.linkedList)\n {\n if (node.List != null)\n {\n linkedList.Remove(node);\n }\n }\n }\n\n if (node.Value.Value is IDisposable d)\n {\n d.Dispose();\n }\n\n return true;\n }\n\n return false;\n }\n\n // Thead A reads x from the dictionary. Thread B adds a new item. Thread A moves x to the end. Thread B now removes the new first Node (removal is atomic on both data structures).\n private void LockAndMoveToEnd(LinkedListNode&lt;LruItem&gt; node)\n {\n // If the node has already been removed from the list, ignore.\n // E.g. thread A reads x from the dictionary. Thread B adds a new item, removes x from \n // the List &amp; Dictionary. Now thread A will try to move x to the end of the list.\n if (node.List == null)\n {\n return;\n }\n\n lock (this.linkedList)\n {\n if (node.List == null)\n {\n return;\n }\n\n linkedList.Remove(node);\n linkedList.AddLast(node);\n }\n }\n\n private class LruItem\n {\n public LruItem(K k, V v)\n {\n Key = k;\n Value = v;\n }\n\n public K Key { get; }\n\n public V Value { get; }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-05T02:21:09.923", "Id": "245020", "ParentId": "16326", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-06T15:58:15.317", "Id": "16326", "Score": "9", "Tags": [ "c#", ".net", "collections", "hash-map" ], "Title": "Thread-safe LRU Dictionary in C#" }
16326
<p>Problem: Given a set of n distinct numbers, find the length of the longest monotone increasing subsequence. For example, let's take this array <code>[1,2,9,4,7,3,11,8,14,6]</code> The longest monotone increasing subsequence of this array is <code>[1,2,4,7,11,14]</code>. So the desired result is, the length of the array which is 6.</p> <p>Algorithm (taken from R.G. Dromey's How to Solve it by computer):</p> <ol> <li>Establish the data set a[1...n] of n elements.</li> <li>Set two loops, one to find out out each terminating point and the inner loop to find it's increasing subsequence.</li> <li>start the first loop at index 2 so that it will initially have a sequence.</li> <li>in the inner loop, if current element is less than maximum of previous sequence, then, identify the subsequence and if the length of subsequence is larger than the length of previous longest subsequence then update the length, position of maximum and maximum value.</li> </ol> <p>else, update the length, position of maximum and maximum value so far.</p> <pre><code>import java.util.*; public class Monotone { public static int maxMonotonicSequenceLength(int[] elements) { int maxValue = 0; int positionOfMax = 0; int length = 2; for (int i = 2; i &lt; elements.length; ++i) { if (elements[i] &lt; maxValue) { int count = 1; int previousMaxElement = 0; for (int j = 1; j &lt;= i-1; ++j) { if ((elements[j] &lt; elements[i]) &amp;&amp; previousMaxElement &lt; elements[j]) { previousMaxElement = elements[j]; count = count + 1; if (length &lt; count) { length = count; positionOfMax = j; maxValue = elements[j]; } } } } else { positionOfMax = i; maxValue = elements[i]; length = length + 1; } } return length + 1; } public static void main(String args[]) { int[] list = new int[10]; list[0] = 1; list[1] = 2; list[2] = 9; list[3] = 4; list[4] = 7; list[5] = 3; list[6] = 11; list[7] = 8; list[8] = 14; list[9] = 6; System.out.println("lenght of subsequence: " + maxMonotonicSequenceLength(list)); } } </code></pre>
[]
[ { "body": "<p>Coding details</p>\n\n<ul>\n<li>You can initialize <code>list</code> like this : <code>int[] list = {1,2,9,4,7,3,11,8,14,6};</code> </li>\n<li><code>for (int j = 1, n = i-1; j &lt;= n; ++j) {</code> // do not loop on limit calculation</li>\n<li>l<code>ength++;</code> // for <code>length = length + 1;</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T09:31:57.200", "Id": "16345", "ParentId": "16327", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T17:47:29.300", "Id": "16327", "Score": "5", "Tags": [ "java", "algorithm" ], "Title": "Java implementation of the longest monotone increasing subsequence" }
16327
<p>Current best practice for using a <code>lock_guard</code> looks like this:</p> <pre><code>// introduce scope to take the lock { lock_guard lock(sync); // sync is an accessible mutex object do_protected_stuff(); // may throw, but the mutex is released regardless } // no exception, mutex is released in normal flow </code></pre> <p>I don't like the scope being introduce without a statement. I think it detracts from readability, and I think it's ugly. It occurred to me that what I wanted was the equivalent of modern Python's <a href="http://www.python.org/dev/peps/pep-0343/"><code>with</code> statement</a>:</p> <pre><code>with Lock() as lock: # corresponds to lock+mutex in C++ do_protected_stuff() </code></pre> <p>I thought about it for a while and designed a syntax hack that's gotten me partway there:</p> <pre><code>#include &lt;iostream&gt; #include &lt;boost/thread.hpp&gt; #include &lt;boost/date_time/posix_time/posix_time.hpp&gt; using std::cout; using std::endl; //============================================= // This is the "novel" part // See main() for usage //============================================= // a utility class class with_lock_ { public: with_lock_(boost::mutex &amp;mtx_) : lock(mtx_), new_lock(true) {} operator bool() { bool ret = new_lock; new_lock = false; return ret; } private: boost::lock_guard&lt;boost::mutex&gt; lock; bool new_lock; }; // a macro to hide the gory details #define with_lock_guard(SYNC) for (with_lock_ lk_(SYNC); lk_; ) //============================================== // some global stuff for multi-thread action // a mutex boost::mutex sync; // a value protected by the mutex float zz = 0.0f; // a thread function that will change the value and crow about it void get_it_yourself() { boost::lock_guard&lt;boost::mutex&gt; lock(sync); zz = 99999.99999f; cout &lt;&lt; endl &lt;&lt; " --- MINE!!" &lt;&lt; endl; } //============================================== int main() { boost::thread runit; //============================================= // This is the intended use... // a little syntactic hack, inspired by Python //============================================= with_lock_guard (sync) { runit = boost::thread(get_it_yourself); cout &lt;&lt; "Starting... "; boost::this_thread::sleep(boost::posix_time::millisec(500)); cout &lt;&lt; "OK! Z = " &lt;&lt; zz &lt;&lt; endl; } // wait for that thread to complete runit.join(); return 0; } </code></pre> <p>Accept, for this discussion, that having a keyword to introduce the scope is preferable to introducing scope with just a brace. This hack lets you pretend you have a real <code>with</code>-like statement: you can follow it with a single or compound statement.</p> <p>I do have a concern regarding the scope of the <code>with_lock_</code> object. As I read things, at some level (persisting even into C++11?) the scope of a variable introduced within a <code>for</code> statement is the block enclosing the <code>for</code>. In practice, it's working OK for me with MSVS 2008; there is a compiler option regarding this, which defaults to the behavior I need in this situation.</p> <p>Even without backing off from the basic idea, I see room for improvement. For one thing, a true <code>with</code> statement in C++ would be able to accept other types of RAII-based objects, as Python does. But so far in practice, I've only really the undesirable syntax with <code>lock_guard</code>.</p> <p>What I'm looking for is a way to generalize this feature such that, at least, any mutex type, from any namespace, can be used. Better, if any lock type can be used. A cleaner implementation than abusing <code>for</code> or the <code>operator bool()</code> would be of interest. </p> <p>Also: I'm not concerned if it breaks older compilers, but it would good to know if this works or doesn't in platforms/compilers other than Windows/MSVS2008+. Comments decrying the whole abomination are fine.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T19:35:04.683", "Id": "26540", "Score": "0", "body": "Microsoft has a paragraph [at the bottom of their `for loop` page](http://msdn.microsoft.com/en-us/library/b80153d8%28v=vs.71%29.aspx) describing how the compiler determines the scope according to the flags it's given (default is the C++ standard: the variable is scoped to the loop body). This is for MSVC'03; the newer versions appear to have the same options available." } ]
[ { "body": "<h3>Comments on Design</h3>\n<p>I like the idea in general but usually when I introduce a lock in a scope, the scope is usually the whole method so it does not look that ugly:</p>\n<pre><code>void MyClass::myMethod()\n{\n lock_guard lock(sync); // sync is an accessible mutex object\n do_protected_stuff(); // may throw, but the mutex is released regardless\n}\n</code></pre>\n<p>But lets assume that you have situations that make your style worth while in using:<br />\nNow my problem is that you have situations where things are not as they seem:</p>\n<pre><code>with_lock_guard (sync)\n runit = boost::thread(get_it_yourself);\n cout &lt;&lt; &quot;Starting... &quot;;\n boost::this_thread::sleep(boost::posix_time::millisec(500));\n cout &lt;&lt; &quot;OK! Z = &quot; &lt;&lt; zz &lt;&lt; endl;\n</code></pre>\n<p>Only the first statement is inside the lock. Yet I get no compiler error (yes I know silly error but the idea is that you should design your class so that it is really hard to abuse even accidentally):</p>\n<p>I would change the design slightly so that it used a lambda:</p>\n<pre><code>with_lock_guard(sync, []()\n{\n runit = boost::thread(get_it_yourself);\n cout &lt;&lt; &quot;Starting... &quot;;\n boost::this_thread::sleep(boost::posix_time::millisec(500));\n cout &lt;&lt; &quot;OK! Z = &quot; &lt;&lt; zz &lt;&lt; endl;\n});\n</code></pre>\n<p>This way it will be harder to abuse accidentally.</p>\n<h3>Comments on code:</h3>\n<p>If you are going to have <code>operator bool()</code> conversion method then at least make it <code>explicit</code> so it can not accidentally be abused. But since you are calling this from your own macro I would have a method that you explicitly call. This makes the code easier to understand.</p>\n<p><a href=\"https://stackoverflow.com/questions/6242768/is-the-safe-bool-idiom-obsolete-in-c11\">https://stackoverflow.com/questions/6242768/is-the-safe-bool-idiom-obsolete-in-c11</a></p>\n<pre><code>// Prefer to use explicit on bool to prevent accidental usage:\nexplict operator bool() { bool ret = new_lock; new_lock = false; return ret; }\n</code></pre>\n<p>But I would do this:</p>\n<pre><code>#define with_lock_guard(SYNC) for (with_lock_ lk_(SYNC); lk_.MakeSureWeRunOnceOnly(); )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T22:32:13.040", "Id": "26544", "Score": "0", "body": "The issue of misusing the block also applies to a `for` or `while` or... I don't consider that to be a deficiency. The lambda approach is certainly reasonable, but MSVS2008 does not implement C++11. Due to weird political fu at work, it's not clear to me if C++03 codebases will be updated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T22:34:14.160", "Id": "26545", "Score": "0", "body": "I'm aware of the `explicit` option but I don't expect any users of the class except for that macro. For self-documenting clarity, I do like the MakeSure... method you've devised." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T16:16:48.803", "Id": "26616", "Score": "1", "body": "@MikeC: The issue of a missing block is a **really big problem**. The reason is that you are trying to move people from the concept of the lock applying to everything after the lock to a concept where the lock only applies to the next statement. Look at the use case scenario: people that had working code before and switch naively from `lock_guard lock(sync)` to `with_lock_guard (sync)` now have broken code if there code is more than one statement long. The comparison with `for`, `while` is not justified as (they are only used as an implementation detail that should never be seen)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T16:20:19.517", "Id": "26617", "Score": "0", "body": "I am a beliver that well written C++ can not be abused (if it can then the author has a design problem). Unfortunately this code is way to easy to use incorrectly. Also the fact the under normal situations is likely to be used incorrectly when updating existing code make it a real problem." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T20:57:56.920", "Id": "16330", "ParentId": "16328", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T18:29:39.727", "Id": "16328", "Score": "7", "Tags": [ "c++", "multithreading" ], "Title": "Improve my little syntactic hack" }
16328
<p>I have the following class which is a tool for retrieving MD5 hashes of files that are input into it. They can potentially be very large files and I require cancellation and progress report, hence why i rolled my own solution rather than just passing in a filestream to <code>HashAlgorithm</code>.</p> <p>I have a producer - consumer set up so that I can be reading in file blocks at the same time as calculating the MD5 hasher. I find the best performance is using 16mb blocks, which I allow a max pre-read of 3 blocks. Considering I have up to 5 of these running in parallel (5 drives) then memory usage can max out at 240mb assuming that the GC collects immediately. Obviously this doesn't happen so i see memory usage jump to approx 700mb or more in some instances.</p> <p>How can I reduce this erratic memory behaviour?</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Security.Cryptography; using System.IO; using System.Threading; using System.Threading.Tasks; using System.Collections.Concurrent; namespace MD5Library { public class FileBlock { public byte[] Data; public int Length; public FileBlock(int inBufferSize) { Data = new byte[inBufferSize]; } } public class MD5Hasher { protected int bufferSize = 1024 * 1024 * 16; //16mb at a time public void MD5Hasher() { } public void MD5Hasher(int _bufferSize) { bufferSize = _bufferSize; } public Task&lt;string&gt; Go(string inFile, CancellationToken ct, IProgress&lt;ProgressReport&gt; prg) { FileInfo fi = new FileInfo(inFile); // Queue with capacity 3x the buffer BlockingCollection&lt;FileBlock&gt; BigBuffer = new BlockingCollection&lt;FileBlock&gt;(3); Task readFileTask = new Task(() =&gt; readFiles(fi, ct, BigBuffer)); Task&lt;string&gt; computeHashTask = new Task&lt;string&gt;(() =&gt; calcHash(fi, BigBuffer, ct, prg)); readFileTask.Start(); computeHashTask.Start(); return computeHashTask; } private async void readFiles(FileInfo fi, CancellationToken ct, BlockingCollection&lt;FileBlock&gt; BigBuffer) { int bytesRead; using (FileStream stream = new FileStream(fi.FullName, FileMode.Open)) { do { FileBlock fileBlock = new FileBlock(bufferSize); fileBlock.Length = await stream.ReadAsync(fileBlock.Data, 0, bufferSize, ct); bytesRead = fileBlock.Length; //Infinite timeout BigBuffer.TryAdd(fileBlock, -1, ct); } while (bytesRead != 0); BigBuffer.CompleteAdding(); } } private string calcHash(FileInfo fi, BlockingCollection&lt;FileBlock&gt; BigBuffer, CancellationToken ct, IProgress&lt;ProgressReport&gt; prg) { long _fileSize = fi.Length; long _bytesProcessed = 0; using (HashAlgorithm hashAlgorithm = MD5.Create()) { foreach (var b in BigBuffer.GetConsumingEnumerable(ct)) { hashAlgorithm.TransformBlock(b.Data, 0, b.Length, b.Data, 0); _bytesProcessed += b.Length; // Report progress ProgressReport p = new ProgressReport(); p.setProgress(_bytesProcessed, _fileSize); prg.Report(p); } hashAlgorithm.TransformFinalBlock(new byte[0], 0, 0); return HashToString(hashAlgorithm.Hash); } } public int BufferSize { get { return bufferSize; } } public string HashToString(byte[] inHash) { string hex = ""; foreach (byte b in inHash) { hex += b.ToString("x2"); } return hex; } } public class ProgressReport { public int PercentDone { get; set; } public string InfoText { get; set; } public void setProgress(long _progress, long _total) { PercentDone = Convert.ToInt32((_progress * 100) / _total); InfoText = PercentDone + "% complete."; ; } } //Borrowed from Stephen Cleary: http://nitoprograms.blogspot.co.uk/2012/02/reporting-progress-from-async-tasks.html public class PropertyProgress&lt;T&gt; : IProgress&lt;T&gt;, INotifyPropertyChanged { private readonly SynchronizationContext context; private T progress; public PropertyProgress(T initialProgress = default(T)) { this.context = SynchronizationContext.Current ?? new SynchronizationContext(); this.progress = initialProgress; } public T Progress { get { return this.progress; } private set { this.progress = value; if (this.PropertyChanged != null) { this.PropertyChanged(this, new PropertyChangedEventArgs("Progress")); } } } void IProgress&lt;T&gt;.Report(T value) { this.context.Post(_ =&gt; { this.Progress = value; }, null); } public event PropertyChangedEventHandler PropertyChanged; } } </code></pre> <p>Usage:</p> <pre><code> string source = @"c:\largefile.dat"; MD5Hasher md5async = new MD5Hasher(); PropertyProgress&lt;ProgressReport&gt; p = new PropertyProgress&lt;ProgressReport&gt;(); CancellationTokenSource cts = new CancellationTokenSource(); Console.Writeline(await md5async.Go(source, cts.Token, p)); </code></pre>
[]
[ { "body": "<ol>\n<li><p>Before I address your specific issue directly, I'd like to suggest that you review <a href=\"http://msdn.microsoft.com/en-us/library/ms229002(v=vs.100).aspx\" rel=\"nofollow noreferrer\">MSDN's guidelines for C# naming conventions</a>, specifically with <a href=\"http://msdn.microsoft.com/en-us/library/ms229043(v=vs.100).aspx\" rel=\"nofollow noreferrer\">respect to capitalization</a>. The erratic name formatting makes your code unnecessarily difficult to follow. You will undoubtedly increase the consistency of your code when it becomes more readable, and you will be able to gain much more when interacting with other programmers (such as on CodeReview).</p></li>\n<li><p>I am not 100% certain about the culprit here, but I have a suspicion that your performance issue is being caused by the way you are creating the string in your <code>HashToString</code> method. Your code is concatenating the strings together using the <code>+</code> operator. There are known performance issues with this approach, and the performance degradation increases proportionally to the number of strings. <strong>As a general rule, you should use a <code>StringBuilder</code> if you are concatenating more than four strings.</strong> An informative article about this guideline is available at: <a href=\"http://www.dotnetperls.com/string-concat\" rel=\"nofollow noreferrer\">dotnetperls - C# string.Concat</a>. If you are concatenating strings in a loop, you should always use a <code>StringBuilder</code>. You can also read an article with benchmarks and explanation of the relative performance between concatenation and <code>StringBuilder</code> at <a href=\"http://www.dotnetperls.com/stringbuilder-performance\" rel=\"nofollow noreferrer\">dotnetperls - C# StringBuilder Performance</a>. After reading these articles, it should be clear that converting any large array to a string using your approach will result in terrible performance. I found <a href=\"http://www.heikniemi.net/hardcoded/2004/08/net-string-vs-stringbuilder-concatenation-performance/\" rel=\"nofollow noreferrer\">another article</a>, which cites performance tests that indicate <strong>using a <code>StringBuilder</code> is 550% faster than using a plus sign</strong>. </p></li>\n</ol>\n\n<p>Now, let's start with your code and see if we can find a better way to handle that issue...</p>\n\n<h2>Original <code>string.Concat</code>* Version:</h2>\n\n<p>**The <code>+</code> operator calls String.Concat under the hood.*</p>\n\n<pre><code>public string HashToString(byte[] inHash)\n{\n string hex = \"\";\n foreach (byte b in inHash)\n {\n hex += b.ToString(\"x2\");\n } \n return hex;\n}\n</code></pre>\n\n<p>Now, since the concatenation is happening in a loop, we know it's better to use the <code>StringBuilder</code> than the <code>+</code> operator. This is what the code looks like if we make this change:</p>\n\n<h2>Better <code>StringBuilder</code> Version:</h2>\n\n<pre><code>public string HashToString2(byte[] inHash)\n{\n StringBuilder hexBuilder = new StringBuilder(); \n foreach (byte b in inHash)\n {\n hexBuilder.AppendFormat(\"{0:x2}\", b);\n } \n return hexBuilder.ToString();\n}\n</code></pre>\n\n<p>Now, if you read the dotnerperls articles, you'd realize we can do a minor tweak to get this to give use even better performance. The performance tweak involves <a href=\"http://www.dotnetperls.com/stringbuilder-capacity\" rel=\"nofollow noreferrer\">explicitly assigning the <code>StringBuilder</code>'s <code>capacity</code> when you create the instance</a>. Since we have an array and we know each element in the array will result in 2 characters, we can determine the capacity of the <code>StringBuilder</code> and eliminate the cost of constant resizing. </p>\n\n<h2>Even Better <code>StringBuilder</code> Version:</h2>\n\n<pre><code>public string HashToString3(byte[] inHash)\n{\n StringBuilder hexBuilder = new StringBuilder( inHash.Length * 2 ); \n foreach (byte b in inHash)\n {\n hexBuilder.AppendFormat(\"{0:x2}\", b);\n } \n return hexBuilder.ToString();\n}\n</code></pre>\n\n<p>At this point, you should be able to run tests and notice better performance. Since we know that at least one of your issues was caused by the <code>HashToString</code> method, it's worth stepping back and see if we are converting a hash to a string in the most optimal way. Now, the hash is just a byte array in a specific context, so we really just need to know <strong>how to get the best performance when converting a byte array to a hexadecimal string in C#</strong>. I googled this, and found out that this issue has been discussed and tested exhaustively. The resources I found include:</p>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa-in-c\">\"How do you convert a byte array to a hexadecimal string and vice versa in C#?\"</a> on StackOverflow. The issue gets beaten to death here, with the selected answer getting close to 200 votes.</p></li>\n<li><p>An open source repository for a project called <a href=\"https://bitbucket.org/patridge/convertbytearraytohexstringperftest\" rel=\"nofollow noreferrer\">\"Convert Byte Array to Hex String Performance Test\"</a>, which was inspired by the previously noted StackOverflow question. It tested 9 candidate methods, (the <code>StringBuilder</code> implementation analogous to our previous result being the <strong>slowest</strong>). </p></li>\n</ul>\n\n<p>The fastest result from the performance test used byte manipulation and looks like:</p>\n\n<h2>Ridiculously Optimized Byte Manipulation Version:</h2>\n\n<pre><code>public string HashToString4(byte[] bytes) {\n char[] c = new char[bytes.Length * 2];\n byte b;\n for (int i = 0; i &lt; bytes.Length; i++) \n {\n b = ((byte)(bytes[i] &gt;&gt; 4));\n c[i * 2] = (char)(b &gt; 9 ? b + 0x37 : b + 0x30);\n b = ((byte)(bytes[i] &amp; 0xF));\n c[i * 2 + 1] = (char)(b &gt; 9 ? b + 0x37 : b + 0x30);\n }\n return new string(c);\n}\n</code></pre>\n\n<p>My only criticism of this is that the byte manipulation technique is very difficult for human beings to read. The second best option was about half as fast as the byte manipulation, but is very readable and leverages a built in .NET function for converting byte arrays to hexadecimal strings. It looks like:</p>\n\n<h2>2nd Best, Highly-Readable Version:</h2>\n\n<pre><code>public string HashToString5(byte[] bytes) {\n return BitConverter.ToString(bytes).Replace(\"-\", \"\");\n}\n</code></pre>\n\n<p>Now, I said at the beginning that I wasn't certain this is your only culprit. However, I know for a fact that making this change will increase your performance in general. Try the suggested refactoring, and let us know how your situation changes.</p>\n\n<h2>Update re: <code>BlockingCollection</code></h2>\n\n<p>It looks like <code>BlockingCollection</code> is also worth exploring for performance issues. I'm personally not very familiar with this class, but <a href=\"https://stackoverflow.com/users/65358/reed-copsey\">Reed Copsey</a> indicates that certain versions of it have scaling issues. Here are a couple StackOverflow posts that are probably worth reading if the <code>HashToString</code> overhaul doesn't completely solve your issue: </p>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/3039724/blockingcollectiont-performance\"><code>BlockingCollection&lt;T&gt;</code> performance`</a></p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/5001003/fast-and-best-producer-consumer-queue-technique-blockingcollection-vs-concurrent\">Fast and Best Producer/Consumer Queue Technique - <code>BlockingCollection&lt;T&gt;</code> vs <code>ConcurrentQueue&lt;T&gt;</code></a></p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T14:03:12.330", "Id": "26596", "Score": "0", "body": "I'm pretty sure string concatenation is not the problem here. The MD5 hash has only 16 bytes. And doing one string concatenation of 16 two-character strings per each file of several hundred megabytes will be completely insignificant, even if done very inefficiently. Your advice might be good in general, but it's not relevant in this case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T14:09:30.153", "Id": "26599", "Score": "0", "body": "@svick, (1) I asked the user to test for validation. (2) It has been demonstrated that string concatenation performance decreases drastically after four strings (this would be 16). (3) I also pointed out some possibilities w/ the BlockingCollection. I do not know what interactions this could result in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T14:22:29.983", "Id": "26600", "Score": "2", "body": "Yes, concatenating many strings this way has bad performance (because it's O(n^2)). But are you seriously suggesting that concatenating 16 very short strings once in a while will waste hundreds of megabytes of memory? And of the two articles you linked to, the first one talks about a very specific version of `BlockingCollection`, which isn't used here. And the second one doesn't mention any performance problems at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T15:12:02.430", "Id": "26604", "Score": "0", "body": "I'd use LINQ in `HashToString`: `return inHash.Aggregate(string.Empty, (current, b) => current + b.ToString(\"x2\"));`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T17:06:03.033", "Id": "26620", "Score": "0", "body": "@JesseC.Slicer, that was one of the ones that got tested. Check out the project, it's got results if you wanna compare them" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T11:53:38.633", "Id": "16351", "ParentId": "16331", "Score": "5" } }, { "body": "<p>Here's how I would go about it (mostly from a readability standpoint rather than a performance one - though the use of immutable data may help contribute to well-measurable performance and memory usage metrics):</p>\n\n<pre><code>namespace MD5Library\n{\n using System;\n using System.Collections.Concurrent;\n using System.Collections.Generic;\n using System.ComponentModel;\n using System.IO;\n using System.Linq;\n using System.Security.Cryptography;\n using System.Threading;\n using System.Threading.Tasks;\n\n public interface IFileBlock\n {\n byte[] Data\n {\n get;\n }\n\n int Length\n {\n get;\n\n set;\n }\n }\n\n public sealed class FileBlock : IFileBlock\n {\n private readonly byte[] data;\n\n public FileBlock(int inBufferSize)\n {\n this.data = new byte[inBufferSize];\n }\n\n public byte[] Data\n {\n get\n {\n return this.data;\n }\n }\n\n public int Length\n {\n get;\n\n set;\n }\n }\n\n public class MD5Hasher\n {\n private readonly int bufferSize = 1024 * 1024 * 16; // 16mb at a time.\n\n public MD5Hasher()\n {\n }\n\n public MD5Hasher(int bufferSize)\n {\n this.bufferSize = bufferSize;\n }\n\n protected int BufferSize\n {\n get\n {\n return this.bufferSize;\n }\n }\n\n public Task&lt;string&gt; Go(string inFile, CancellationToken ct, IProgress&lt;IProgressReport&gt; prg)\n {\n // Queue with capacity 3x the buffer.\n var fi = new FileInfo(inFile);\n var bigBuffer = new BlockingCollection&lt;IFileBlock&gt;(3);\n var readFileTask = new Task(() =&gt; this.ReadFiles(fi, ct, bigBuffer));\n var computeHashTask = new Task&lt;string&gt;(() =&gt; CalcHash(fi, bigBuffer, ct, prg));\n\n readFileTask.Start();\n computeHashTask.Start();\n return computeHashTask;\n }\n\n private static string HashToString(IEnumerable&lt;byte&gt; inHash)\n {\n return inHash.Aggregate(string.Empty, (current, b) =&gt; current + b.ToString(\"x2\"));\n }\n\n private async void ReadFiles(FileInfo fi, CancellationToken ct, BlockingCollection&lt;IFileBlock&gt; bigBuffer)\n {\n using (var stream = File.OpenRead(fi.FullName))\n {\n int bytesRead;\n\n do\n {\n var fileBlock = new FileBlock(this.bufferSize);\n\n fileBlock.Length = await stream.ReadAsync(fileBlock.Data, 0, this.bufferSize);\n bytesRead = fileBlock.Length;\n\n // Infinite timeout.\n bigBuffer.TryAdd(fileBlock, -1, ct);\n }\n while (bytesRead != 0);\n\n bigBuffer.CompleteAdding();\n }\n }\n\n private static string CalcHash(FileInfo fi, BlockingCollection&lt;IFileBlock&gt; bigBuffer, CancellationToken ct, IProgress&lt;IProgressReport&gt; prg)\n {\n var fileSize = fi.Length;\n var bytesProcessed = 0L;\n\n using (HashAlgorithm hashAlgorithm = MD5.Create())\n {\n foreach (var b in bigBuffer.GetConsumingEnumerable(ct))\n {\n hashAlgorithm.TransformBlock(b.Data, 0, b.Length, b.Data, 0);\n bytesProcessed += b.Length;\n\n // Report progress.\n prg.Report(new ProgressReport(bytesProcessed, fileSize));\n }\n\n hashAlgorithm.TransformFinalBlock(new byte[0], 0, 0);\n return HashToString(hashAlgorithm.Hash);\n }\n }\n }\n\n public interface IProgressReport\n {\n int PercentDone\n {\n get;\n }\n\n string InfoText\n {\n get;\n }\n }\n\n public sealed class ProgressReport : IProgressReport\n {\n private const string PercentComplete = \"% complete.\";\n\n private readonly int percentDone;\n\n private readonly string infoText;\n\n public ProgressReport(long progress, long total)\n {\n this.percentDone = Convert.ToInt32((100 * progress) / total);\n this.infoText = this.PercentDone + PercentComplete;\n }\n\n public int PercentDone\n {\n get\n {\n return this.percentDone;\n }\n }\n\n public string InfoText\n {\n get\n {\n return this.infoText;\n }\n }\n }\n\n // Borrowed from Stephen Cleary: http://nitoprograms.blogspot.co.uk/2012/02/reporting-progress-from-async-tasks.html\n public class PropertyProgress&lt;T&gt; : IProgress&lt;T&gt;, INotifyPropertyChanged\n {\n private readonly SynchronizationContext context;\n\n private T progress;\n\n public PropertyProgress(T initialProgress = default(T))\n {\n this.context = SynchronizationContext.Current ?? new SynchronizationContext();\n this.progress = initialProgress;\n }\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n public T Progress\n {\n get\n {\n return this.progress;\n }\n\n private set\n {\n this.progress = value;\n if (this.PropertyChanged != null)\n {\n this.PropertyChanged(this, new PropertyChangedEventArgs(\"Progress\"));\n }\n }\n }\n\n void IProgress&lt;T&gt;.Report(T value)\n {\n this.context.Post(_ =&gt; { this.Progress = value; }, null);\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T15:48:14.833", "Id": "16360", "ParentId": "16331", "Score": "0" } }, { "body": "<p>First, make sure that this is actually a problem for you. Large number in the “used memory” column might look scary, but it's not a problem if the memory wouldn't be used for anything anyway.</p>\n\n<p>The reason why your program seems to be using too much memory is most likely because the garbage collector doesn't run often enough. .Net tries to not run GC too often, so it doesn't affect performance too much. But, as a side effect, this means your application will consume more memory than what you might expect.</p>\n\n<p>The quick and dirty solution to this is to make sure the GC runs more often, by calling <a href=\"http://msdn.microsoft.com/en-us/library/xe0c2357.aspx\" rel=\"nofollow\"><code>GC.Collect()</code></a>. An appropriate place to do that would be right before you allocate your big array in the constructor of <code>FileBlock</code>. But, depending on how many objects are there in your application, this could significantly affect performance.</p>\n\n<p>A better solution might be to create a <a href=\"http://en.wikipedia.org/wiki/Object_pool_pattern\" rel=\"nofollow\">pool</a> of blocks. When you need a new block, you would first look in the pool and take it from there is there was one. When you're done with a block, you wouldn't just rely on the GC, but you would put it back into the pool. This way, blocks wouldn't be GCed and then reallocated again and again, which should lead to less wasted memory.</p>\n\n<p>One question is how to decide that the pool is too big, so you can remove unused blocks from it and let it be GCed. You'll have to try that by yourself, but one possibility is to base this decision on time: if a block is in the pool for, say, one minute, you can discard it.</p>\n\n<p>Another option would be to have a fixed total number of blocks. In this case, if a block is requested when the pool is empty, you would block until some block is returned to the pool. This would ensure that your memory usage doesn't go over some limit, but it could also affect performance, because a thread that could be reading from the disk can't do that, because there are no blocks available.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T16:25:47.513", "Id": "16365", "ParentId": "16331", "Score": "1" } }, { "body": "<p>You are seeing memory climb because the garbage collector is not running at the same rate that data is allocated. It is important to note that FileBlock.Data is allocating in the large object heap. Conceptually, large object heap objects belong the generation 2 because they are collected at the same time generation 2 is collected. <a href=\"http://msdn.microsoft.com/en-us/magazine/cc534993.aspx#id0070017\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/magazine/cc534993.aspx#id0070017</a> has some good pointers on the LOH.</p>\n\n<p>You could consider pre-allocating a pool of 16MB blocks. There would also be an extra speed advantage since the memory manager wouldn't need to keep zeroing 16MB arrays for each allocation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-16T08:55:08.450", "Id": "18696", "ParentId": "16331", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T21:06:01.027", "Id": "16331", "Score": "8", "Tags": [ "c#", "multithreading", "memory-management", "asynchronous" ], "Title": "Code works but memory usage is erratic" }
16331
<p>This is my first time working with classes and it's still unclear to me. I was wondering if someone can tell me if I did this right.</p> <blockquote> <p>Define a new class, Track, that has an artist (a string), a title (also a string), and an album (see below).</p> <ol> <li>Has a method <code>__init__</code>(self, artist, title, album=None). The arguments artist and and title are strings and album is an Album object (see below)</li> <li>Has a method <code>__str__</code>(self) that returns a reasonable string representation of this track</li> <li>Has a method set_album(self, album) that sets this track's album to album</li> </ol> </blockquote> <pre><code>class Track: def __init__(self, artist, title, album=None): self.artist = str(artist) self.title = str(title) self.album = album def __str__(self): return self.artist + " " + self.title + " " + self.album def set_album(self, album): self.album = album Track = Track("Andy", "Me", "Self named") </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T00:54:32.897", "Id": "26563", "Score": "3", "body": "The `set_album` method is redundant and _unpythonic_: simply assign to the attribute directly in your code. If at any point in the future you need some more complicated behaviour when setting the attribute, look into using a [property](http://docs.python.org/library/functions.html#property) then." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T21:43:39.027", "Id": "26805", "Score": "0", "body": "@PedroRomano - agreed, but it seems as though the homework question (I assume it's homework?) is explicitly asking for the method `set_album`." } ]
[ { "body": "<p>In general, looks great! A few things:</p>\n\n<ol>\n<li>This relates to 'new-style' classes in Python - make sure that they inherit from <code>object</code>. It sounds like you are learning about classes now, so I will spare an explanation of what inheritance is since you'll eventually get to it.</li>\n<li>I could be misguided in saying this, but generally I've seen/done type conversion (where you call <code>str()</code>) outside of the constructor (i.e. the <code>__init__()</code> function). The instructions says it expects a string, and you are already passing a string in the <code>Track =</code> line, so removing the <code>str()</code> parts will still result in the correct answer.</li>\n<li>The instructions say that <code>album</code> is an \"Album object\", which means that <code>Album</code> will be a class as well. I'm assuming you're just getting this started so it hasn't been created yet, but when you do, you can just pass the <code>Album</code> object into your <code>Track</code> constructor.</li>\n<li>Naming - in general, avoid naming your instances the same thing as the class (in your case, <code>Track</code> is the class). This leads to confusion, especially when you need to create a second instance (because <code>Track</code> will then an instance of Track, instead of the <code>Track</code> class.</li>\n</ol>\n\n<p>Here is your same code with a few of those adjustments. In general though, looking good!</p>\n\n<pre><code>class Track(object):\n def __init__(self, artist, title, album=None):\n self.artist = artist\n self.title = title\n self.album = album\n\n def __str__(self):\n # This is called 'string formatting' and lets you create a template string\n # and then plug in variables, like so\n return \"%s - %s (%s)\" % (self.artist, self.title, self.album)\n\n def set_album(self, album):\n self.album = album\n\nmy_track = Track(\"Andy\", \"Me\", \"Self named\")\n\n# This will show you what __str__ does\nprint my_track\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T21:44:32.037", "Id": "26806", "Score": "0", "body": "Regarding point 1: you don't need to inherit from `object` in Python 3.x. I can't tell what version he's using. Also, the `%` formatting operator [has been superseded by `string.format()`](http://www.python.org/dev/peps/pep-3101/) (though of course the old style is still hugely common)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T22:09:00.343", "Id": "26810", "Score": "2", "body": "@poorsod Agreed - I actually don't ever use the % operator :) Figured it would be the easier one to explain, but am looking forward to a `.format()`-only future! As to inheriting from `object`, I blindly assumed that he was using 2.x - I need to get with the future I guess :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T00:47:07.380", "Id": "16337", "ParentId": "16332", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T22:21:33.600", "Id": "16332", "Score": "5", "Tags": [ "python" ], "Title": "Music track class" }
16332
<p>I'm new to Python and would like some advice or guidance moving forward. I'm trying to parse Wikipedia data into something uniform that I can put into a database. I've looked at wiki parsers but from what I can see they are large and complex and don't get me much as I don't need 99% of their functionality (I'm not editing, or the ilk). What I am doing is reading some information from template variables and trying to clean them up into useable information. I've already created a simple function to read a wiki template and return a dictionary of key/values. These key/values are what I'm reading and trying to parse into useful data.</p> <p>For example, I'm trying to parse the <code>Infobox settlement</code> template to create the following information:</p> <pre><code>{'CITY': u'Portland', 'COUNTRY': u'United States of America', 'ESTABLISHED_DATE': u'', 'LATITUDE': 40.43388888888889, 'LONGITUDE': -84.98, 'REGION': u'Indiana', 'WIKI': u'Portland, Indiana'} </code></pre> <p>The only item not directly from the template is the <code>WIKI</code> entry, this is the wiki page title the template if from. The raw template that the above is produced from is:</p> <pre><code>{{Infobox settlement |official_name = Portland, Indiana |native_name = |settlement_type = [[City]] |nickname = |motto = |image_skyline = BlueBridge.jpg |imagesize = 250px |image_caption = Meridian (arch) Bridge in the fog |image_flag = |image_seal = |image_map = Jay_County_Indiana_Incorporated_and_Unincorporated_areas_Portland_Highlighted.svg |mapsize = 250px |map_caption = Location in the state of [[Indiana]] |image_map1 = |mapsize1 = |map_caption1 = |coordinates_display = inline,title |coordinates_region = US-IN |subdivision_type = [[List of countries|Country]] |subdivision_name = [[United States]] |subdivision_type1 = [[Political divisions of the United States|State]] |subdivision_name1 = [[Indiana]] |subdivision_type2 = [[List of counties in Indiana|County]] |subdivision_name2 = [[Jay County, Indiana|Jay]] |government_type = |leader_title = [[Mayor]] |leader_name = Randy Geesaman ([[Democratic Party (United States)|D]]) |leader_title1 = &lt;!-- for places with, say, both a mayor and a city manager --&gt; |leader_name1 = |leader_title2 = |leader_name2 = |leader_title3 = |leader_name3 = |established_title = &lt;!-- Settled --&gt; |established_date = |established_title2 = &lt;!-- Incorporated (town) --&gt; |established_date2 = |established_title3 = &lt;!-- Incorporated (city) --&gt; |established_date3 = |area_magnitude = 1 E7 |area_total_sq_mi = 4.65 |area_land_sq_mi = 4.65 |area_water_sq_mi = 0.00 |area_water_percent = 0 |area_urban_sq_mi = |area_metro_sq_mi = |population_as_of = 2010 |population_note = |population_total = 6223 |population_density_km2 = 604.7 |population_density_sq_mi = 1566.8 |population_metro = |population_density_metro_km2 = |population_density_metro_sq_mi = |population_urban = |timezone = [[North American Eastern Time Zone|EST]] |utc_offset = -5 |timezone_DST = [[North American Eastern Time Zone|EDT]] |utc_offset_DST = -4 |latd = 40 |latm = 26 |lats = 2 |latNS = N |longd = 84 |longm = 58 |longs = 48 |longEW = W |elevation_m = 277 |elevation_ft = 909 |postal_code_type = [[ZIP code]] |postal_code = 47371 |website = http://www.thecityofportland.net |area_code = [[Area code 260|260]] |blank_name = [[Federal Information Processing Standard|FIPS code]] |blank_info = 18-61236{{GR|2}} |blank1_name = [[Geographic Names Information System|GNIS]] feature ID |blank1_info = 0441471{{GR|3}} |footnotes = }} </code></pre> <p>To get the results, I first get the template information into a dictionary with this function. Its sole job is to find a template and to return a dictionary of key/value information for me to use:</p> <pre><code>"""Find a template""" def __getTemplate(self, name, input=""): if (input == ""): input = self.rawPage startIndex = input.lower().find("{{" + name.lower()) + 2 + len(name) length = len(input) braces = 0 result = "" for i in range(startIndex, length): c = input[i] if (c == "{"): braces += 1 elif (c == "}" and braces &gt; 0): braces -= 1 elif (c == "["): braces += 1 elif (c == "]" and braces &gt; 0): braces -= 1 elif (c == "&lt;" and input[i+1] == "!"): braces += 1 elif (c == "&gt;" and braces &gt; 0 and input[i-1] == "-"): braces -= 1 elif (c == "}" and braces == 0): result = result.strip() parts = result.split("|") dict = {} counter = 0 for part in parts: part = part.strip() kv = part.split("=") key = kv[0].strip() if (len(key) &gt; 0): val = "" if (len(kv) &gt; 1): val = kv[1].strip().replace("%!%!%", "|").replace("%@%@%", "=") else: val = key; key = counter counter += 1 dict[key] = val return dict elif (c == "|" and braces &gt; 0): c = "%!%!%" elif (c == "=" and braces &gt; 0): c = "%@%@%" result += c </code></pre> <p>It seems to work well enough - it's returning what I'm expecting. Any suggestions are welcome, like I said I'm new to Python and I'm sure there are better ways to do what I'm doing.</p> <p>The results from this function is a dictionary that represents the template, the values are still a mess of free form text. I pass the dictionary to the next function. This is the one I would like most of the advice on - it's a mess and needs cleaned up. The <code>if</code>s and the <code>replace</code>s are all over the place. Before I go and clean that up I was hoping to get any advice or suggestions on other more Python ways of doing things.</p> <pre><code>"""Parse the Infobox settlement template""" def __parseInfoboxSettlement(self): values = self.__getTemplate("Infobox settlement") settlement = {} settlement['WIKI'] = self.title if values == None: return settlement # Get the settlement established date if 'established_date' in values: if 'established_date2' not in values: settlement['ESTABLISHED_DATE'] = self.__parseDate(values['established_date']) else: if len(values['established_date']) &gt; len(values['established_date2']): settlement['ESTABLISHED_DATE'] = self.__parseDate(values['established_date']) else: settlement['ESTABLISHED_DATE'] = self.__parseDate(values['established_date2']) if len(settlement['ESTABLISHED_DATE']) == 4: settlement['ESTABLISHED_YEAR'] = settlement['ESTABLISHED_DATE'] settlement['ESTABLISHED_DATE'] = u"" else: settlement['ESTABLISHED_YEAR'] = settlement['ESTABLISHED_DATE'].split("-")[0] # Get the settlement latitude try: deg = 0.0 min = 0.0 sec = 0.0 if 'latd' in values: match = re.findall("([0-9]*)", values['latd'])[0] if len(match) &gt; 0: deg = float(match) if 'lat_d' in values: match = re.findall("([0-9]*)", values['lat_d'])[0] if len(match) &gt; 0: deg = float(match) if 'latm' in values: match = re.findall("([0-9]*)", values['latm'])[0] if len(match) &gt; 0: min = float(match) if 'lat_m' in values: match = re.findall("([0-9]*)", values['lat_m'])[0] if len(match) &gt; 0: min = float(match) if 'lats' in values: match = re.findall("([0-9]*)", values['lats'])[0] if len(match) &gt; 0: sec = float(match) if 'lat_s' in values: match = re.findall("([0-9]*)", values['lat_s'])[0] if len(match) &gt; 0: sec = float(match) lat = deg + min/60 + sec/3600 if 'latNS' in values: if values['latNS'].lower() == "s": lat = 0 - lat if 'lat_NS' in values: if values['lat_NS'].lower() == "s": lat = 0 - lat settlement['LATITUDE'] = lat except: pass # get the settlement longitude try: deg = 0.0 min = 0.0 sec = 0.0 if 'longd' in values: match = re.findall("([0-9]*)", values['longd'])[0] if len(match) &gt; 0: deg = float(match) if 'long_d' in values: match = re.findall("([0-9]*)", values['long_d'])[0] if len(match) &gt; 0: deg = float(match) if 'longm' in values: match = re.findall("([0-9]*)", values['longm'])[0] if len(match) &gt; 0: min = float(match) if 'long_m' in values: match = re.findall("([0-9]*)", values['long_m'])[0] if len(match) &gt; 0: min = float(match) if 'longs' in values: match = re.findall("([0-9]*)", values['longs'])[0] if len(match) &gt; 0: sec = float(match) if 'long_s' in values: match = re.findall("([0-9]*)", values['long_s'])[0] if len(match) &gt; 0: sec = float(match) long = deg + min/60 + sec/3600 if 'longEW' in values: if values['longEW'].lower() == "w": long = 0 - long if 'long_EW' in values: if values['long_EW'].lower() == "w": long = 0 - long settlement['LONGITUDE'] = long except: pass # Figure out the country and region settlement['COUNTRY'] = u"" settlement['REGION'] = u"" count = 0 num = u"" while True: name = u"" type = u"" if 'subdivision_name' + num in values: name = values['subdivision_name' + num].replace("[[", "").replace("]]","") name = name.replace("{{flag|","").replace("{{","").replace("}}","").strip() name = name.replace(u"flagicon",u"").strip() if 'subdivision_type' + num in values: type = values['subdivision_type' + num].strip().lower() # Catch most issues if u"|" in name: parts = name.split("|") first = True for part in parts: if len(part) &gt; 0 and u"name=" not in part and not first: name = part first = False # Nead with name= things the above missed if u"|" in name: parts = name.split("|") for part in parts: if len(part) &gt; 0 and u"name=" not in part: name = part # Double name parts = name.split(" ") if len(parts) == 2: if parts[0].lower() == parts[1].lower(): name = parts[0] if u"country" in type and u"historic" not in type: if u"united states" in name.lower() or name.lower() == u"usa": settlement['COUNTRY'] = u"United States of America" elif name.lower() == u"can": settlement['COUNTRY'] = u"Canada" else: settlement['COUNTRY'] = name elif (u"state" in type and u"counties" not in type and u"county" not in type and u"|region" not in type) or u"federal district" in type: # US State settlement['REGION'] = name.replace("(region)","").replace("(state)","").strip() elif (u"canada|province" in type): # Canada settlement['REGION'] = name.replace("(region)","").replace("(state)","").strip() settlement['REGION'] = settlement['REGION'].replace(u"QC", u"Québec") elif (u"|region" in type and settlement['REGION'] == u""): settlement['REGION'] = name.replace("(region)","").replace("(state)","").strip() elif type != u"": self.__log("XXX subdivision_type: " + type) count += 1 num = str(count) if type == u"": break # Cleanup the city name settlement['CITY'] = u"" name = u"" if 'official_name' in values: name = values['official_name'].replace(u"[[", u"").replace(u"]]",u"").replace(u"{{flag|",u"").replace(u"}}",u"").strip() if 'name' in values and name == u"": name = values['name'].replace(u"[[", u"").replace(u"]]",u"").replace(u"{{flag|",u"").replace(u"}}",u"").strip() if name != u"": name = name.replace(u"The City of ",u"").replace(u"City of ",u"").replace(u"Town of ",u"").replace(u"Ville de ", u"").replace(u" Township", "") if u"{{flagicon" in name: parts = name.split("}}") name = parts[1].strip() if u"&lt;ref&gt;" in name: parts = name.split("&lt;ref&gt;") if len(parts) &gt; 0: name = parts[0].strip() if u"&lt;br /&gt;" in name: parts = name.split("&lt;br /&gt;") for part in parts: if u"img" not in part and len(part) &gt; 1: name = part if u"," in name: parts = name.split(","); if len(parts) &gt; 1: if parts[1].strip().lower() in settlement['REGION'].lower(): if parts[0].strip() not in settlement['REGION'].lower(): settlement['CITY'] = parts[0].strip() elif parts[1].strip() not in settlement['REGION'].lower(): settlement['CITY'] = parts[1].strip() elif name.lower() not in settlement['REGION'].lower(): settlement['CITY'] = name else: self.__log("XXX settlement_type: " + type) # Set the results self.locationData.append(settlement) </code></pre> <p>I know this code is a mess, and there are several blocks of code marked by a comment line explaining what they do. The rest is based on trial and error looking over 30-40 pages in the wiki. This works 99% of the time from what I have tried so far. I'm going through a list of 100-200 locations and just haven't hit many of the international locations yet.</p> <p>Besides this code being a mess, is there anything I should be doing more Python-esque that I'm not? Besides cleaning things up, are there any other suggestions you have on how to go about doing what I'm doing?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T22:37:31.833", "Id": "26548", "Score": "1", "body": "Just saying, a wiki parser is too complex, but a 200 line mega-function isn't? Sounds like you are reinventing the wheel here. Besides that, this would be more suited to Code Review, as there is no specific question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T22:40:32.947", "Id": "26549", "Score": "0", "body": "@Lattyware - The wiki parse wouldn't do what this function is doing anyway. All it would do is give me a dictionary key/values that my fist function gives me. It may save me some [[ and ]] replaces but I dont think thats worth moving to a wiki parser. Maybe I'm wrong. Also most wikiparsers I've found haven't been maintained in a long time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T23:20:30.220", "Id": "26552", "Score": "1", "body": "You might be better off using an HTML/DOM parser, and parsing the generated HTML rather than trying to parse the wikitext" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T23:38:37.827", "Id": "26555", "Score": "0", "body": "@ernie - wikipeida doesn't like you doing that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T23:41:39.393", "Id": "26556", "Score": "0", "body": "They don't like you parsing their html, but they're okay with you parsing the wikitext? I'd imaging they don't like any scraping at all?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T23:48:07.093", "Id": "26558", "Score": "0", "body": "I don't think Wikipedia care what format you consume their API in. If you want rendered HTML, just use the render option: http://en.wikipedia.org/w/index.php?action=render&title=Main_Page" } ]
[ { "body": "<p>Wikipedia pages have this great comment line-- <code>&lt;!-- Infobox begins --&gt;</code> to tell you where infoboxes start and end. Use that to find the information in the infobox.</p>\n\n<p>You end up with a string, lets call it <code>infobox</code>. </p>\n\n<pre><code># List Comprehension over infobox to return values\ninfo = [j.split(\"=\") for j in [i for i in infobox.split('|')]][1:]\n\n# And, here's your dict:\nwikidict = {}\nfor i in info:\n try:\n # stripping here is best\n wikidict[i[0].strip()] = i[1].strip()\n except IndexError:\n pass # if there's no data, there's no i[1], and an IndexError is thrown\n</code></pre>\n\n<p>That said, the template values are just that-- template values. If you want the latitude, you dont need to code anything complex-- the dictionary keys are already there.</p>\n\n<pre><code> latkeys = \"latd latm lats latNS\".split()\n lat_info = [wikidict[i] for i in latkeys]\n</code></pre>\n\n<p>You could easily do a quick transformation over the lat_info to get things into the format you want. </p>\n\n<p>You should also probably write a separate function that strips the <code>[[x|y]]</code> from certain elements, and provides a return as a tuple if you're interested in manipulating those. As it stands, your code is nearly impossible to read. You dont need to push strings through complex logic gates like the ones you have; keep the logic to a bare minimum. You know, the <a href=\"http://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow\">Keep It Simple, Stupid</a> rule. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T23:37:11.027", "Id": "26553", "Score": "0", "body": "The problem I'm running into is that latd may or maynot contain a number. It might be in lat_d for that matter. so once I find the d m and s (depending on which exist or not) I do the math to get a latitude. Its just hard as there is no rhyme or reason to some fields." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T23:38:06.517", "Id": "26554", "Score": "0", "body": "`info = [j.split(\"=\") for j in [i for i in infobox.split('|')]][1:]` looks a lot simpler than what I have to read a dictionary but how does is handle a = or a | being in the value of a key? I started off with KISS but each time I saw and issue, another if or replace went in to fix it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T00:12:41.607", "Id": "26561", "Score": "0", "body": "Here's the beauty of this solution. You don't actually need the stuff behind the `|` in the value. For example, if you see `|subdivision_type2 = [[List of counties in Indiana|County]]`, the next line is `|subdivision_name2 = [[Jay County, Indiana|Jay]]`, and you throw away the first data piece, and you return `'[[Jay County, Indiana'` for `wikidict['subdivision_name2']`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T00:19:45.843", "Id": "26562", "Score": "0", "body": "@Justin808 and in either case, the lats have `lat` at the beginning of the name, right? `latkeys = [i for i in wikidict.keys() if all(('lat' in i, 'population' not in i))]` (population has 'lat' in it)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T23:16:26.120", "Id": "16336", "ParentId": "16335", "Score": "2" } } ]
{ "AcceptedAnswerId": "16336", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-08T22:30:26.147", "Id": "16335", "Score": "5", "Tags": [ "python", "parsing", "wikipedia" ], "Title": "Parsing Wikipedia data in Python" }
16335
<p>Very simple I want to edit a virtual host files and replace the tags I made with some actual data:</p> <pre><code>import os, re with open('virt_host', 'r+') as virtual file = virtual.read() file = re.sub('{{dir}}', '/home/richard', file) file = re.sub('{{user}}', 'richard', file) file = re.sub('{{domain_name}}', 'richard.com', file) with open('new_virt', 'w+') as new_file new_file.write(file) new_file.close() </code></pre> <p>Is this the best way?</p>
[]
[ { "body": "<pre><code>import os, re\n</code></pre>\n\n<p>Here, make sure you put a colon after <code>virtual</code></p>\n\n<pre><code>with open('virt_host', 'r+') as virtual:\n</code></pre>\n\n<p>Avoid using built-in Python keywords as variables (such as <code>file</code> here)</p>\n\n<pre><code> f = virtual.read()\n</code></pre>\n\n<p>This part is explicit, which is a good thing. Depending on whether or not you have control over how your variables are defined, you could use <a href=\"http://docs.python.org/library/string.html#format-string-syntax\" rel=\"nofollow\">string formatting</a> to pass a dictionary containing your values into the read file, which would save a few function calls.</p>\n\n<pre><code> f = re.sub('{{dir}}', '/home/richard', f)\n f = re.sub('{{user}}', 'richard', f)\n f = re.sub('{{domain_name}}', 'richard.com', f)\n</code></pre>\n\n<p>Same as above regarding the colon</p>\n\n<pre><code>with open('new_virt', 'w+') as new_file:\n new_file.write(f)\n</code></pre>\n\n<p>One of the main benefits of using a context manager (such as <code>with</code>) is that it handles things such as closing by itself. Therefore, you can remove the <code>new_file.close()</code> line.</p>\n\n<p>Here is the full code with the adjustments noted. Hope it helps!</p>\n\n<pre><code>import os, re\n\nwith open('virt_host', 'r+') as virtual:\n f = virtual.read()\n f = re.sub('{{dir}}', '/home/richard', f)\n f = re.sub('{{user}}', 'richard', f)\n f = re.sub('{{domain_name}}', 'richard.com', f)\n\nwith open('new_virt', 'w+') as new_file:\n new_file.write(f)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T15:32:04.370", "Id": "26612", "Score": "0", "body": "@Jason No prob man!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T08:38:28.600", "Id": "16344", "ParentId": "16341", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T07:53:45.790", "Id": "16341", "Score": "3", "Tags": [ "python" ], "Title": "How to improve method of opening file in python then writing to another?" }
16341
<p>I've been studying hard and asking a lot of questions - I finally came a cross an exercise in LYAH that looked like it was easy enough but a perfect candidate for practicing.</p> <p>The below program has a bunch of helper funcs in there, but the one of interest is <code>neighbors/3</code>. It takes a <code>Pair</code> type and <code>Edge</code> number, and a <code>BiMorph</code> type. It then determines all of the children within that edge and returns it as a list of tuple pairs.</p> <p>I would like a more experienced Haskeller to come in and tear it apart or to give me constructive criticism.</p> <pre><code>import Control.Monad import Control.Applicative data Pair a = Pair a a deriving (Show, Eq) data BiMorph a = BiMorph Func Func type Neighbors = [(Int, Int)] type Matrix = [[Int]] type Func = (Int -&gt; Int -&gt; Int) instance Functor Pair where fmap f (Pair a b) = Pair (f a) (f b) instance Applicative Pair where pure a = Pair a a (Pair fa fb) &lt;*&gt; (Pair a b) = Pair (fa a) (fb b) matrix :: Int -&gt; Int -&gt; Matrix matrix xl yl = replicate yl $ [1..xl] cartesianPairs :: Func -&gt; Pair Int -&gt; [Pair Int] cartesianPairs f p = [(f &lt;$&gt; (Pair x y) &lt;*&gt; p) | x &lt;- [1,0], y &lt;- [0,1], (x,y) /= (0,0)] cartesianDoubles :: Func -&gt; Func -&gt; Pair Int -&gt; [Pair Int] cartesianDoubles f g (Pair x y) = [Pair (f x 1) (g y 1), Pair (g x 1) (f y 1)] dropP :: Pair Int -&gt; (Int, Int) dropP (Pair x y) = (abs x, abs y) liftP :: (Int, Int) -&gt; Pair Int liftP (x, y) = Pair x y neighbors :: Pair Int -&gt; Int -&gt; BiMorph Int -&gt; Neighbors neighbors p e (BiMorph f g) = map dropP $ concat [(cartesianPairs f p), (cartesianPairs g p), (cartesianDoubles f g p)] &gt;&gt;= (\(Pair x' y') -&gt; guard (x' &lt;= e &amp;&amp; y' &lt;= e) &gt;&gt; return (Pair x' y')) </code></pre>
[]
[ { "body": "<p>Run <code>hlint</code> tool on your source to help you with getting rid of redundant brackets, <code>$</code> and other minor suggestions.</p>\n\n<p>In <code>neighbors</code> your using of <code>guard</code> in list monad can be changed to <code>filter</code> function:</p>\n\n<pre><code>neighbors :: Pair Int -&gt; Int -&gt; BiMorph Int -&gt; Neighbors\nneighbors p e (BiMorph f g) = map dropP $ filter ff $ concat [cartesianPairs f p, cartesianPairs g p, cartesianDoubles f g p] where\n ff (Pair x' y') = x' &lt;= e &amp;&amp; y' &lt;= e\n</code></pre>\n\n<p>You can also hardcode the list into <code>cartesianPairs</code> as it's short:</p>\n\n<pre><code>cartesianPairs :: Func -&gt; Pair Int -&gt; [Pair Int]\ncartesianPairs f p =\n [f &lt;$&gt; Pair x y &lt;*&gt; p | (x, y) &lt;- [(1,0), (0,1), (1,1)]]\n</code></pre>\n\n<p>You can even use pairs directly:</p>\n\n<pre><code>cartesianPairs :: Func -&gt; Pair Int -&gt; [Pair Int]\ncartesianPairs f p =\n [f &lt;$&gt; pair &lt;*&gt; p | pair &lt;- [Pair 1 0, Pair 0 1, Pair 1 1]] \n</code></pre>\n\n<p>I also have an impression that <code>cartesianPairs</code> can be further simplified but I couldn't find anything that has clear meaning. Here are two attempts:</p>\n\n<pre><code>cartesianPairs f p =\n (&lt;*&gt; p) &lt;$&gt; (fmap . fmap) f [Pair 1 0, Pair 0 1, Pair 1 1]\n\ncartesianPairs f p =\n (&lt;*&gt; p) . fmap f &lt;$&gt; [Pair 1 0, Pair 0 1, Pair 1 1]\n</code></pre>\n\n<p><code>cartesianDoubles</code> can be shrinked the same way if you want:</p>\n\n<pre><code>cartesianDoubles f g (Pair x y) = [Pair (ff x) (gg y), Pair (gg x) (ff y)] where\n ff x = f x 1\n gg x = g x 1\n\ncartesianDoubles f g p = [Pair ff gg &lt;*&gt; p, Pair gg ff &lt;*&gt; p] where\n ff x = f x 1\n gg x = g x 1\n\ncartesianDoubles f g p = (&lt;*&gt; p) &lt;$&gt; [Pair ff gg, Pair gg ff] where\n ff x = f x 1\n gg x = g x 1\n</code></pre>\n\n<p>Yet another improvement. You can notice that there are versions of <code>cartesianDoubles</code> and <code>cartesianPairs</code> sharing the same <code>(&lt;*&gt; p) &lt;$&gt;</code> part:</p>\n\n<pre><code>cartesianPairs f p =\n (&lt;*&gt; p) &lt;$&gt; (fmap . fmap) f [Pair 1 0, Pair 0 1, Pair 1 1]\n\ncartesianDoubles f g p = (&lt;*&gt; p) &lt;$&gt; [Pair ff gg, Pair gg ff] where\n ff x = f x 1\n gg x = g x 1\n</code></pre>\n\n<p>Then notice that <code>&lt;$&gt;</code> in <code>(&lt;*&gt; p) &lt;$&gt;</code> is for <code>Functor []</code> instance, so it's just plain <code>map</code>, and <code>map has a property of commuting with</code>concat<code>:</code>map f . concat == concat . map f`.</p>\n\n<p>So you can move the common fragment out:</p>\n\n<pre><code>cartesianPairs f p =\n (fmap . fmap) f [Pair 1 0, Pair 0 1, Pair 1 1]\n\ncartesianDoubles f g p = [Pair ff gg, Pair gg ff] where\n ff x = f x 1\n gg x = g x 1\n\nneighbors :: Pair Int -&gt; Int -&gt; BiMorph Int -&gt; Neighbors\nneighbors p e (BiMorph f g) = map dropP $ filter ff $ map (&lt;*&gt; p) $ concat [cartesianPairs f p, cartesianPairs g p, cartesianDoubles f g p] where\n ff (Pair x' y') = x' &lt;= e &amp;&amp; y' &lt;= e\n</code></pre>\n\n<p>Now <code>p</code> argument is not used:</p>\n\n<pre><code>cartesianPairs f =\n (fmap . fmap) f [Pair 1 0, Pair 0 1, Pair 1 1]\n\ncartesianDoubles f g = [Pair ff gg, Pair gg ff] where\n ff x = f x 1\n gg x = g x 1\n\nneighbors :: Pair Int -&gt; Int -&gt; BiMorph Int -&gt; Neighbors\nneighbors p e (BiMorph f g) = map dropP $ filter ff $ map (&lt;*&gt; p) $ concat [cartesianPairs f, cartesianPairs g, cartesianDoubles f g] where\n ff (Pair x' y') = x' &lt;= e &amp;&amp; y' &lt;= e\n</code></pre>\n\n<p>If you want, you can convert <code>neighbors</code> to use list comprehensions:</p>\n\n<pre><code>neighbors :: Pair Int -&gt; Int -&gt; BiMorph Int -&gt; Neighbors\nneighbors p e (BiMorph f g) = \n [ dropP xx \n | x &lt;- concat [cartesianPairs f, cartesianPairs g, cartesianDoubles f g]\n , let xx @ (Pair x' y') = x &lt;*&gt; p\n , x' &lt;= e &amp;&amp; y' &lt;= e ] \n</code></pre>\n\n<p>Or even</p>\n\n<pre><code>neighbors :: Pair Int -&gt; Int -&gt; BiMorph Int -&gt; Neighbors\nneighbors p e (BiMorph f g) = \n [ dropP xx \n | xx @ (Pair x' y') &lt;- (&lt;*&gt; p) &lt;$&gt; \n concat [cartesianPairs f, cartesianPairs g, cartesianDoubles f g] \n , x' &lt;= e &amp;&amp; y' &lt;= e ] \n</code></pre>\n\n<p>But I find it less clear.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T02:01:02.377", "Id": "26813", "Score": "0", "body": "I spent some time going through this - thank you for taking the time again to go through my program. Is this generally how you program in Haskell yourself? Do you write out the general idea (as I did) then iteratively improve the functions till you find some common patterns, then generalize it? Or is this a process that happens somewhat...intuitively...for you and this was just an externalized version of what you do in your head now?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T11:17:34.993", "Id": "26830", "Score": "0", "body": "For old code it's like simplifying expressions in high school algebra. I still even don't know what your program is about. For new code the initial idea becomes better over time. At first I barely could write code without type errors, then I learned to refactor recursion into folds, then I learned to recognize folds before I write recursion, then recognision of `.` and monadic compositions became intuitive." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T20:14:34.923", "Id": "16370", "ParentId": "16342", "Score": "4" } } ]
{ "AcceptedAnswerId": "16370", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T08:13:49.190", "Id": "16342", "Score": "5", "Tags": [ "haskell" ], "Title": "Determine children within edge and return a list of tuple pairs" }
16342
<p><a href="http://en.wikipedia.org/wiki/Entity%E2%80%93relationship_model" rel="nofollow">Wikipedia Page for <strong>Entity-Relationship Model</strong></a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T10:22:28.827", "Id": "16346", "Score": "0", "Tags": null, "Title": null }
16346
An ERM (Entity–Relationship Model) is an abstract model of a relational database. Diagrams created with ERM syntax are called entity-relationship diagrams.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T10:22:28.827", "Id": "16347", "Score": "0", "Tags": null, "Title": null }
16347
<p>At the moment I am using this to check a boolean property in sharepoint 2007 using C# and .Net Framework 3.5</p> <pre><code>if (bool.Parse(listItem.Properties["Boolean Property"].ToString()) == false) </code></pre> <p>is there any better way of doing it ?</p> <p><strong>Edit</strong></p> <p>when my code try to convert property into string it gives me exception even when am validating if property is empty or not.</p> <p><strong>This Worked For me</strong> </p> <p>using method "Contains Key" instead of "Properties.Containsfield"</p> <pre><code>object abc = "bool property"; foreach (SPListItem item in list.Items) { if (item.Properties.ContainsKey(abc) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T13:02:30.740", "Id": "26582", "Score": "0", "body": "I explained some of the errors that your approach is likely to generate in my answer. My guess is it's either a `NullReferenceException` or a `FormatException`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T16:44:35.570", "Id": "26618", "Score": "0", "body": "Unrelated, but note that use of boolean literals in comparisons is something that I’d flag in every code review. Boolean literals have one use, and one use only: to initialise a boolean value." } ]
[ { "body": "<p>The <code>.Parse</code> methods will throw exceptions if the value is null, in a bad format, etc.</p>\n\n<p>I suggest always using the <code>.TryParse</code> methods instead:</p>\n\n<pre><code>bool val;\nif(!bool.TryParse(listItem.Properties[\"Boolean Property\"].ToString(), out foo)) {\n val = false;\n}\n</code></pre>\n\n<p>Or perhaps one of the <a href=\"http://msdn.microsoft.com/en-us/library/system.convert.toboolean%28v=vs.100%29.aspx\" rel=\"nofollow\"><code>Convert.ToBoolean()</code></a> methods.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T12:42:10.073", "Id": "16353", "ParentId": "16349", "Score": "4" } }, { "body": "<p>I am making some assumptions about your code, specifically that <code>listItem</code> is of type <a href=\"http://msdn.microsoft.com/en-us/library/ms415089.aspx\"><code>SPListItem</code></a> and that <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem_properties.aspx\"><code>listItem.Properties</code></a> is a <a href=\"http://msdn.microsoft.com/EN-US/library/aahzb21x\"><code>HashTable</code></a>. This is mainly to provide context for my explanation, but even if I am mistaken, most of my comments will still hold. For the sake of context, let's assume your actual method looks like:</p>\n\n<pre><code> void HandleBooleanListItemProperty( SPListItem listItem ){ \n if (bool.Parse(listItem.Properties[\"Boolean Property\"].ToString()) == false){ \n // do something if the Boolean ListItem property is false\n } \n else\n { \n // do something if the Boolean ListItem property is true\n }\n} \n</code></pre>\n\n<ol>\n<li><p>Validate that the object exists before you call <code>ToString()</code>. The way your method is currently written, you will get a <code>NullReferenceException</code> if the key \"Boolean Property\" is missing or the hashed value that corresponds to the \"Boolean Property\" key is <code>null</code>. This refactoring will make the method look like:</p>\n\n<pre><code>void HandleBooleanListItemProperty2( SPListItem listItem ){ \n object booleanPropertyValue = listItem.Properties[\"Boolean Property\"];\n if ( ReferenceEquals( booleanPropertyValue, null ) ) {\n // do something if the Boolean ListItem property is missing\n } \n else if (bool.Parse(booleanPropertyValue.ToString()) == false){ \n // do something if the Boolean ListItem property is false\n } \n else { \n // do something if the Boolean ListItem property is true\n }\n } \n</code></pre></li>\n<li><p>Use <code>bool.TryParse</code> instead of <code>bool.Parse</code>. If the <code>ToString()</code> value of the hashed value corresponding to the key \"Boolean Property\" is anything other than \"true\" or \"false\" (case-insensitive), a <code>FormatException</code> will be thrown. This refactoring will make the method look like:</p>\n\n<pre><code> void HandleBooleanListItemProperty3( SPListItem listItem ){ \n object booleanPropertyValue = listItem.Properties[\"Boolean Property\"];\n bool parsedBooleanPropertyValue;\n if ( ReferenceEquals( booleanPropertyValue, null ) ) { \n // do something if the Boolean ListItem property is missing\n }\n else if (bool.TryParse(booleanPropertyValue.ToString(), out parsedBooleanPropertyValue) ) \n {\n if(parsedBooleanPropertyValue == false){ \n // do something if the Boolean ListItem property is false\n }\n else { \n // do something if the Boolean ListItem property is true\n }\n } \n else { \n // do something if the Boolean ListItem property's ToString() value was something other than \"true\" or \"false\"\n }\n } \n</code></pre></li>\n<li><p>If the hashed value that corresponds to the \"Boolean Property\" key is really a <code>bool</code>, then cast it before comparing. Calling <code>ToString()</code> just throws away .NET's type-safety. This refactoring will make the method look like:</p>\n\n<pre><code> void HandleBooleanListItemProperty4( SPListItem listItem ){ \n object booleanPropertyValue = listItem.Properties[\"Boolean Property\"];\n if (booleanPropertyValue is bool) \n {\n bool castBooleanPropertyValue = (bool) booleanPropertyValue;\n if( castBooleanPropertyValue == false ){ \n // do something if the Boolean ListItem property is false\n }\n else { \n // do something if the Boolean ListItem property is true\n }\n } \n else { \n // do something if the Boolean ListItem property is not a bool \n if ( ReferenceEquals( booleanPropertyValue, null ) ) { \n // do something if the Boolean ListItem property is missing\n }\n else {\n // do something if the Boolean ListItem property is something other than a bool\n }\n }\n } \n</code></pre></li>\n<li><p>Eliminate magic strings from your value accessor. This requires removing the inline <code>\"Boolean Property\"</code> and declaring with that value, and then using the constant in order to access the value in every usage. This decreases the possibility that a typos will cause bugs. An article on magic strings is available at: <a href=\"http://codebetter.com/matthewpodwysocki/2009/03/19/functional-net-lose-the-magic-strings/\">http://codebetter.com/matthewpodwysocki/2009/03/19/functional-net-lose-the-magic-strings/</a> . The resulting refactoring would look like:</p>\n\n<pre><code> const string BooleanPropertyKey = \"Boolean Property\";\n\n void HandleBooleanListItemProperty5( SPListItem listItem ){ \n object booleanPropertyValue = listItem.Properties[BooleanPropertyKey];\n if (booleanPropertyValue is bool) \n {\n bool castBooleanPropertyValue = (bool) booleanPropertyValue;\n if( castBooleanPropertyValue == false ){ \n // do something if the Boolean ListItem property is false\n }\n else { \n // do something if the Boolean ListItem property is true\n }\n } \n else { \n // do something if the Boolean ListItem property is not a bool \n if ( ReferenceEquals( booleanPropertyValue, null ) ) { \n // do something if the Boolean ListItem property is missing\n }\n else {\n // do something if the Boolean ListItem property is something other than a bool\n }\n }\n } \n</code></pre></li>\n<li><p>Use the negation operator (<code>!</code>) instead of comparing to false. This is much more readable and will save you time in the long run. This final refactoring looks like:</p>\n\n<pre><code> const string BooleanPropertyKey = \"Boolean Property\";\n\n void HandleBooleanListItemProperty6( SPListItem listItem ){ \n object booleanPropertyValue = listItem.Properties[BooleanPropertyKey];\n if (booleanPropertyValue is bool) \n {\n bool castBooleanPropertyValue = (bool) booleanPropertyValue;\n if( !castBooleanPropertyValue ){ \n // do something if the Boolean ListItem property is false\n }\n else { \n // do something if the Boolean ListItem property is true\n }\n } \n else { \n // do something if the Boolean ListItem property is not a bool \n if ( ReferenceEquals( booleanPropertyValue, null ) ) { \n // do something if the Boolean ListItem property is missing\n }\n else {\n // do something if the Boolean ListItem property is something other than a bool\n }\n }\n } \n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T13:24:12.457", "Id": "26585", "Score": "0", "body": "thanks for explaining it in details and I did tried number 5, but when property is there it isn't going to first if statement but going to else statement and I just debugged and looked at what property is returned as and its returned as \"1\" for that particular item and code thinks its not boolean" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T13:31:09.000", "Id": "26586", "Score": "1", "body": "@TimeToThine, I guess you are used to working with JavaScript, huh? In C#, `1` is not a `Boolean`. It is an integer. You can use the same approach with `int` instead of `bool`, and then check `if( ((int)listItem.Properties[BooleanPropertyKey]) == 1 )`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T13:36:14.407", "Id": "26587", "Score": "0", "body": "sorry am bit confused now, I looked at XML returned by SharePoint in my solution while its attached to list and in XML it got \"1\" as value for that property but when I tried to get values of all items using console app, its giving me as true, however for one item I am getting \"object not set to reference\" for which I think has been already added before custom property wasn't added to list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T13:39:40.113", "Id": "26588", "Score": "0", "body": "XML stores a boolean value as a `1`. This is different than the C# literal `1`. If you are deserializing the XML document to a `HashTable`, it should be converted to a `Boolean`. Your problem is that there is no value in the `HashTable` with the key \"Boolean Property\", so when you ask the `HashTable` for it, it gives you `null`. When you ask `null` for `ToString()`, it gives you a `NullReferenceException` (\"Object not set to a reference\")" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T13:43:51.200", "Id": "26589", "Score": "0", "body": "thats true, I think I want to catch this this null exception in a way that I can do something with it without throwing any exception, just like you explained it in code above, but number 5 isn't working like it should be :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T13:49:04.640", "Id": "26590", "Score": "0", "body": "@TimeToThine, I guarantee you the code will \"work like it should\". Maybe you are not realizing that a null reference will not be seen as a `bool`. So, for example, if there is no \"Boolean Property\" attribute in the XML element, then there will be no reference in the `HashTable`, and so it will throw an error." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T13:01:18.770", "Id": "16354", "ParentId": "16349", "Score": "8" } } ]
{ "AcceptedAnswerId": "16354", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T11:16:53.843", "Id": "16349", "Score": "3", "Tags": [ "c#", "sharepoint" ], "Title": "Better way of parsing string to boolean" }
16349
<p>I've had some help designing my field boxes and I was hoping to get feedback on the code. The fields will increase in complexity which is why I thought to structure it this way (image upload fields, textbox with WYSIWYG controls etc.</p> <p>CSS</p> <pre><code>.error { height: 27px; background-color: red; margin-bottom: 4px;} .lft { float: left; } ul, li { list-style-type: none; vertical-align:middle; } .ts3 { font-size: 15px; } .dc3 { background-color: #808080; } .tc5 { color: #333333;} .p4 { padding: 4px; } .r2 { border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; } .r6 { border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; } .field { line-height:27px; font-family:arial, sans-serif; border-color: #d9d9d9; border-top:solid 1px #c0c0c0; } input.field{width:100%} .fieldwrapper{ padding: 0 5px 0 0; overflow: hidden;} label{width:200px; display:inline-block; float:left}​ </code></pre> <p>HTML</p> <pre><code>&lt;ul&gt; &lt;li &gt; &lt;div class="r6 dc3 ts2 p4"&gt; &lt;div class="error r6"&gt;Error!&lt;/div&gt; &lt;label field_id="None" for="sender"&gt;Sender email address&lt;/label&gt; &lt;div class="fieldwrapper"&gt; &lt;input class="field r2" placeholder="Email" type="text" value=""&gt; &lt;p&gt;This is just me explaining how to use this particular field. It is very interesting, don't you know...&lt;/p&gt; &lt;/div&gt;&lt;/div&gt; &lt;/li&gt;&lt;/ul&gt; </code></pre> <p>​ JSfiddle link <a href="http://jsfiddle.net/cskQ8/64/" rel="nofollow">LNIK</a></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T12:48:43.187", "Id": "26580", "Score": "0", "body": "You should use [`<input type=\"email\" ...`](http://developers.whatwg.org/states-of-the-type-attribute.html#e-mail-state-%28type=email%29)." } ]
[ { "body": "<ol>\n<li><p>If the input with the <code>placeholder=\"Email\"</code> is actually an email address, then the <code>type</code> attribute should be set to <code>email</code>, not <code>text</code>. (Reference: <a href=\"http://www.w3.org/TR/html-markup/input.email.html\" rel=\"nofollow\">http://www.w3.org/TR/html-markup/input.email.html</a>)</p></li>\n<li><p>Declare an <code>id</code> attribute and a <code>name</code> attribute on the email field. This will be necessary if you want to access the elements or their posted values explicitly. (Reference: <a href=\"http://reference.sitepoint.com/html/input/name\" rel=\"nofollow\">http://reference.sitepoint.com/html/input/name</a> , <a href=\"http://reference.sitepoint.com/html/core-attributes/id\" rel=\"nofollow\">http://reference.sitepoint.com/html/core-attributes/id</a>)</p></li>\n<li><p>Once you have declared an <code>id</code> on the input, set the <code>for</code> attribute on the label equal to that id. This will enable a behavior such that clicking on the label will focus on the input for the corresponding field. (Reference: <a href=\"http://reference.sitepoint.com/html/label\" rel=\"nofollow\">http://reference.sitepoint.com/html/label</a>) </p></li>\n<li><p>Use descriptive, semantic class names. Good class names should indicate the nature of the content, not the format of the layout. Instead of <code>fieldwrapper</code> try <code>sender-email</code>. (Reference : <a href=\"http://www.w3.org/QA/Tips/goodclassnames\" rel=\"nofollow\">http://www.w3.org/QA/Tips/goodclassnames</a> )</p></li>\n<li><p>This depends on what HTML version you are using, but the HTML5 spec says that form elements should be wrapped in <code>p</code> tags, not <code>div</code>s. (Reference: <a href=\"http://dev.w3.org/html5/spec/forms.html#writing-a-form\" rel=\"nofollow\">http://dev.w3.org/html5/spec/forms.html#writing-a-form</a>'s-user-interface)</p></li>\n</ol>\n\n<p>The code that would correspond to my comments might look like : </p>\n\n<pre><code>&lt;p class=\"email-input\"&gt;\n &lt;label for=\"sender\"&gt;Sender email address:&lt;/label&gt;\n &lt;input id=\"sender\" name=\"sender\" type=\"email\" placeholder=\"Email\" class=\"r2\"&gt;\n&lt;/p&gt;\n&lt;p&gt;This is just me explaining how to use this particular field. It is very interesting, don't you know...&lt;/p&gt;\n</code></pre>\n\n<p>One thing you'll notice is that there are less CSS classes. I have replaced the <code>field-wrapper</code> with <code>email-input</code> and completely removed the <code>field</code> class. You can migrate the <code>.field-wrapper</code> CSS to the <code>.email-input</code> selector, and the <code>field</code> CSS to the <code>.email-input &gt; input</code> selector.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T17:04:57.137", "Id": "26619", "Score": "0", "body": "@JamesWillson no problem, good luck!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T13:28:33.653", "Id": "16355", "ParentId": "16350", "Score": "1" } } ]
{ "AcceptedAnswerId": "16355", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T11:50:12.307", "Id": "16350", "Score": "1", "Tags": [ "html", "css" ], "Title": "HTML CSS Field Layout" }
16350
<p>I wrote my own exception class, deriving from <code>std::runtime_error</code> to have Error-IDs, timestamps and inner exceptions. It seems to work, but are there any drawbacks?</p> <p>The only thing I see is the deep-copy in the copy-constructor, which is not efficient, when there are many nested exceptions. But exceptions should be rare and not be nested too much, so I think it's a downside I can cope with.</p> <pre><code>#pragma once #include &lt;stdexcept&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;time.h&gt; #include &lt;memory&gt; class MyException : public std::runtime_error { public: MyException(const MyException&amp; exception) : std::runtime_error(exception.what()), exceptionId(exception.id()), ts(exception.timestamp()), innerException(NULL) { if (exception.inner() != NULL) { innerException = new MyException(*exception.inner()); } else { innerException = NULL; } } MyException(const std::string&amp; _Message) : std::runtime_error(_Message), exceptionId(0), innerException(NULL) { time(&amp;ts); } MyException(const std::string&amp; _Message, unsigned int id) : std::runtime_error(_Message), exceptionId(id), innerException(NULL) { time(&amp;ts); } MyException(const std::string&amp; _Message, unsigned int id, MyException* innerException) : std::runtime_error(_Message), exceptionId(id), innerException(new MyException(*innerException)) { time(&amp;ts); } virtual ~MyException() { delete innerException; } unsigned int id() const { return exceptionId; } time_t timestamp() const { return ts; } const MyException* inner() const { return innerException; } private: unsigned int exceptionId; time_t ts; const MyException* innerException; }; </code></pre> <p>This is how I would use it:</p> <pre><code>void handleException(MyException *ex) { cout &lt;&lt; "exception " &lt;&lt; ex-&gt;id() &lt;&lt; " - " &lt;&lt; ex-&gt;what() &lt;&lt; endl; const MyException* innerException = ex-&gt;inner(); int t = 1; while (innerException != NULL) { for (int i=0; i&lt;t; ++i) { cout &lt;&lt; "\t"; } ++t; cout &lt;&lt; "inner exception " &lt;&lt; innerException-&gt;id() &lt;&lt; " - " &lt;&lt; innerException-&gt;what() &lt;&lt; endl; innerException = innerException-&gt;inner(); } } void throwRecursive(int temp) { if (temp == 0) { throw runtime_error("std::runtime_error"); } try { throwRecursive(--temp); } catch (MyException &amp;ex) { throw MyException("MyException", (temp+1), &amp;ex); } catch (exception &amp;ex) { throw MyException(ex.what(), (temp+1)); } } void myExceptionTest() { try { throwRecursive(3); } catch (MyException &amp;ex) { handleException(&amp;ex); } } </code></pre> <p>And the output:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>exception 3 - MyException inner exception 2 - MyException inner exception 1 - std::runtime_error </code></pre> </blockquote> <p>I already found out <a href="https://stackoverflow.com/questions/12801194/is-there-anything-wrong-with-my-self-implemented-exception-class#comment17310405_12801194">here</a> that I'm violating the <a href="http://en.wikipedia.org/wiki/Rule_of_three_%28C++_programming%29" rel="nofollow noreferrer">rule of three</a>, having forgotten the copy assignment operator.</p> <p>Other issues mentioned: cloning, reserved names and throw specifications.</p> <p>Can anyone tell me more about that?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T14:47:30.697", "Id": "26602", "Score": "0", "body": "First glance: `innerException == NULL;` could be quite a nasty typo." } ]
[ { "body": "<p>Not all compilers support <code>#pragma once</code></p>\n\n<pre><code>#pragma once\n</code></pre>\n\n<p>There are C++ equivalent of most C libraries that put the appropriate interface into the standard namespace.</p>\n\n<pre><code>#include &lt;time.h&gt;\n\n// Prefer\n\n#include &lt;ctime&gt;\n</code></pre>\n\n<p>My pet peeve (OK second after <code>using namespace std;</code>); because everybody thinks they know the rules but get it wrong all the time:</p>\n\n<pre><code>_Message\n</code></pre>\n\n<p><strong>DO NOT USE IDENTIFIERS WITH A LEADING UNDERSCORE</strong>. Even if you know the rules most people get it wrong (such as this case) as a result it leads to maintenance problems. <a href=\"https://stackoverflow.com/a/228797/14065\">https://stackoverflow.com/a/228797/14065</a> An identifier with a leading underscore and a capital letter is <em>reserved</em> in all scopes (i.e. the implementation is potentially going to use a macro with that name and Message seems like a prime candidate).</p>\n\n<p>Your three versions of the constructor can be written as a single constructor:</p>\n\n<pre><code> MyException( const std::string&amp; _Message\n , unsigned int id = 0 // Use default values\n , MyException* innerException = NULL) // That way you do not have\n : std::runtime_error(_Message) // three versions of the\n , exceptionId(id) // same constructor\n , innerException(innerException)\n {\n time(&amp;ts);\n }\n</code></pre>\n\n<p>A class is its own friend.<br>\nSo you don't need to call getter methods to access members of the object you are copying in the copy constructor; you can just get the values. When constructing the base class (std::runtime_error) why not take advantage of its copy constructor (it may have optimizations that you are failing to take use of by using the non standard version).</p>\n\n<pre><code>MyException(const MyException&amp; exception)\n : std::runtime_error(exception)\n , exceptionId(exception.exceptionId)\n , ts(exception.ts)\n , innerException(NULL)\n</code></pre>\n\n<p>The inner exception is passed around as a pointer. So we have no ownership semantics associated with it. You attempt to take ownership but fail (because you do not implement the rule of 3 (5 in C++11)).</p>\n\n<pre><code>{\n if (exception.inner != NULL)\n {\n // Slicing problem if exception.inner is derived from MyException\n innerException = new MyException(exception.inner);\n }\n else\n {\n // Already set in the initializer list no need to set again.\n innerException = NULL;\n }\n}\n</code></pre>\n\n<p>Also because of the way you implement it you can not subclass <code>MyException</code> because the copy constructor will slice your object on copy. You should probably use a smart pointer to handle ownership of the exception. Since sharing the same exception would solve most of your problems the easy way out is to use <code>shared_ptr&lt;X&gt;</code>. Personally I would make <code>X</code> a std::runtime_error<code>not</code>MyException` thus allowing you to chain on standard exceptions (or anything derived from them).</p>\n\n<p>In the handler:</p>\n\n<pre><code>void handleException(MyException *ex)\n</code></pre>\n\n<p>Why pass a pointer to the exception. Now you have to check for NULL. Pass it as a reference.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T17:09:18.187", "Id": "26621", "Score": "0", "body": "Wow! Thank you for this detailed answer. I'm new to this site. Can I simply edit my question by replacing my code by an improved version for a next revision step?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T18:30:02.883", "Id": "26626", "Score": "0", "body": "@Ben: Rather than replace your answer Add a new section below with a title called `###edit 1`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T09:13:32.410", "Id": "26664", "Score": "0", "body": "I edited my question. Please have a look at it!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T16:00:38.403", "Id": "16362", "ParentId": "16357", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T14:11:42.100", "Id": "16357", "Score": "6", "Tags": [ "c++", "exception" ], "Title": "Self-implemented C++ exception class" }
16357
<p>I'm trying to get my head around object oriented programming, and I'm starting in JavaScript. I have put a working demo of my code on JSFiddle (<a href="http://jsfiddle.net/Grezzo/bhuac/" rel="nofollow">here</a>), but the class is below.</p> <p>My main concerns are that as soon as the object is called with a constructor, all the properties are populated straight away (there are no methods). Should I have put some of the contructor code into methods?</p> <pre><code>function XEString(encryptedString) { if (!XEString.test(encryptedString)) { //Throw exception if invalid XEcrypt string throw new Error("Invalid XECrypt string"); } else { this.encryptedString = encryptedString; //Save encrypted string to object //Remove first "." char and put numbs into array, then convert numbs from strs to ints this.encryptedNumbers = this.encryptedString.substring(1).split("."); for (var i = 0; i &lt; this.encryptedNumbers.length; i++) { this.encryptedNumbers[i] = parseInt(this.encryptedNumbers[i], 10); } //Each char is calced from a group of 3 numbs this.stringLength = this.encryptedNumbers.length / 3; //Create array for encrypted chars, and obj to map encrypted char freq this.encryptedChars = []; this.encryptedCharFreq = {}; //Loop for each letter for (var i = 0; i &lt; this.stringLength; i++) { //Add together each group of 3 numbs var thisChar = 0; for (var j = 0; j &lt; 3; j++) { thisChar += this.encryptedNumbers[3 * i + j]; } this.encryptedChars[i] = thisChar; //Store encrypted char code in array //Keep a record of how many times each encrypted char occurred if (this.encryptedCharFreq[thisChar] == null) { //If this char has not been seen before this.encryptedCharFreq[thisChar] = 1; //Set the occurrence in the obj map to 1 } else { //Otherwise this.encryptedCharFreq[thisChar]++; //Increment the occurrence in the obj map } } //Get highest char freq (mode) this.highestFreq = 0; for (var i in this.encryptedCharFreq) { if (this.encryptedCharFreq[i] &gt; this.highestFreq) { this.highestFreq = this.encryptedCharFreq[i]; } } //Get all highest freq chars (modes) and add objs containing key, decrypted string and numb of unprintable chars this.decryptedStrings = []; for (var i in this.encryptedCharFreq) { if (this.encryptedCharFreq[i] == this.highestFreq) { var key = i - 32; //Space char is ASCII code 32 var decryptedString = ""; var unprintableChars = 0; for (var j = 0; j &lt; this.stringLength; j++) { //for every char add the decoded ascii char and check for unprintable char var decryptedChar = this.encryptedChars[j] - key; decryptedString += String.fromCharCode(decryptedChar); if (decryptedChar &lt; 32 || decryptedChar &gt; 126) { //Printable ASCII char codes range from 32-126 unprintableChars++; } } this.decryptedStrings.push({ 'key': key, 'decryptedString': decryptedString, 'unprintablechars': unprintableChars }); } } //Get least unprintable chars this.leastUnprintableChars = Infinity; for (i in this.decryptedStrings) { if (this.decryptedStrings[i]['unprintablechars'] &lt; this.leastUnprintableChars) { this.leastUnprintableChars = this.decryptedStrings[i]['unprintablechars']; } } //Get best decrypted string(s) this.bestDecryptedStrings = []; for (i in this.decryptedStrings) { if (this.decryptedStrings[i]['unprintablechars'] == this.leastUnprintableChars) { this.bestDecryptedStrings.push(this.decryptedStrings[i]); } } } } //Function for testing valid XEcrypted string. returns true or false XEString.test = function(encryptedString) { return /^((\.-?\d+){3})+$/.test(encryptedString); }​ </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T16:05:39.087", "Id": "26614", "Score": "0", "body": "Could you include code in the question, please? \"This site is for code reviews, which are hard to do when the code is behind a link somewhere out there on the internet. If you want a code review, you must post the relevant snippets of code in your question. It is fine to post a \"see more\" link (though, do be careful — very few reviewers will be willing to click through and read thousands of lines of your code), but the most important parts of the code must be placed directly in the question.\" (from the FAQ)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T16:15:06.153", "Id": "26615", "Score": "0", "body": "@palacsint Fair enough (I'm familiar with stackoverflow where some people are happy to debug a live copy of the code), but I understand why it might differ here (I'm new here). I'm not sure how to condense the code for a code review without losing code that I want reviewed, so it is quite long." } ]
[ { "body": "<p>It's a tricky one, since your class* doesn't really need any methods. Since its purpose is to decrypt a string, it makes sense to do that decryption straight away. Not much need to call any methods on the instantiated object afterwards.</p>\n\n<p>Besides, I don't see much that would make sense to expose as methods. The decryption steps really only make sense in their current context. </p>\n\n<p>So the way you've done it right now seems appropriate enough, I think.</p>\n\n<p>I guess you could simply skip instantiation, and simply have a decrypt function that returns an object literal (aka map, hash, etc.) with the properties. No need for a constructor and instantiation, just a <code>parseXEString</code> function. That's probably what I'd do.</p>\n\n<p>But if you do want to instantiate you own object, you could keep the code pretty much the same, but add property accessor (reader) methods, and keep the properties themselves \"private\". This would make the object's properties immutable (whereas now, anyone can say <code>xeObj.decryptedStrings = ...</code> and overwrite the calculated properties.) This can be accomplished like so:</p>\n\n<pre><code>function Demo() {\n var x = 42; // local var\n\n // make a read accessor for x\n this.getX = function () {\n return x;\n };\n}\n\nvar d = new Demo;\nd.getX() // =&gt; 42\nd.x; // =&gt; undefined\n</code></pre>\n\n<p>However, all your code would still need to be inside the constructor in order to be able to access the local variables. I.e. the methods can't be on the prototype.</p>\n\n<p>(And depending on where your code is intended to be used it would be better to use ECMA5's <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty\" rel=\"nofollow\"><code>Object.definePropety</code></a> which let's you add accessors. Of course, older JS runtimes do not support this.)</p>\n\n<p>*) <em>Technically, it's a \"constructor\" in JS terms, not a class, but that's not terribly important here</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T08:21:14.133", "Id": "26767", "Score": "0", "body": "Thanks, I think there is some more reading for me to do before I fully understand what you are saying." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T08:46:49.783", "Id": "26771", "Score": "0", "body": "@Grezzo Let me know if you have questions, and I'll try my best to answer them (as soon as I have the chance to, anyway)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T17:16:21.980", "Id": "16366", "ParentId": "16361", "Score": "1" } } ]
{ "AcceptedAnswerId": "16366", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T15:55:24.743", "Id": "16361", "Score": "2", "Tags": [ "javascript", "object-oriented", "classes" ], "Title": "Is this a good JavaScript class?" }
16361
<p>I have based my code off several tutorials which has culminated what I think is quite a complicated CSS layout. It has a docked footer. The sidebars are turned on dynamically in my template depending if there is content. The site is designed to work in the following scenarios:</p> <h2>1 Column</h2> <ul> <li>No div class lft </li> <li>No div class rgt</li> <li>Content in div class col-main</li> </ul> <p><a href="http://jsfiddle.net/HMsKa/" rel="nofollow">http://jsfiddle.net/HMsKa/</a></p> <h2>2 Columns</h2> <ul> <li>Content in either div class lft or div class rgt</li> <li>Content in div class col-main</li> </ul> <p><a href="http://jsfiddle.net/HMsKa/2/" rel="nofollow">http://jsfiddle.net/HMsKa/2/</a></p> <h2>3 Columns</h2> <ul> <li>Content in div class lft </li> <li>Content in div class rgt</li> <li>Content in col-main div</li> </ul> <p><strong>Here is the HTML</strong></p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html lang="en-US"&gt; &lt;head&gt; &lt;title&gt;Title&lt;/title&gt; &lt;link href="/static/css/main.css" rel="stylesheet" type="text/css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="container-wrap"&gt; &lt;div id="header-wrap" class="full_width"&gt; &lt;div id="header-container" class="dc1"&gt; &lt;div id="header" class="thin_width rel"&gt; &lt;a href="/"&gt;&lt;img src="/static/img/header.jpg" id="logo" alt="coming soon" title="coming soon"&gt;&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="/posts/list/"&gt;Link1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/posts/create/"&gt;Link 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/about"&gt;Link 3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="container" class="thin_width"&gt; &lt;div class="full_width" style="height:auto;"&gt; &lt;div class="lft"&gt;Test&lt;/div&gt; &lt;div class="rgt"&gt;Test&lt;/div&gt; &lt;div id="col-main"&gt; &lt;h1&gt;Sed ut perspiciatis unde&lt;/h1&gt; &lt;div id="fullwidth"&gt; &lt;form id="searchForm" action="/search"&gt; &lt;input type="text" name="kw" class="field r2 lft dc1 tc5 b1 ts3" id="field_regular" placeholder="Keyword"&gt; &lt;input type="text" name="loc" class="field r2 lft dc1 tc5 b1 ts3" id="field_regular" placeholder="Location"&gt; &lt;input type="submit" class="button r2 b1 ts3" id="button_search" value="Search"&gt; &lt;/form&gt; &lt;/div&gt; &lt;p&gt;Sed ut perspiciatne voluptatem sequi nesciunt.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="footer-wrap" class="thin_width"&gt; &lt;div id="footer-container" class="full_width abs dc1"&gt; &lt;div id="footer" class="thin_width rel"&gt; &amp;#169; 2012 Company, Inc. &lt;ul&gt; &lt;li&gt;&lt;a href="/contact"&gt;Contact&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/faq"&gt;FAQ&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/terms"&gt;Terms&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/privacy"&gt;Privacy&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;​ </code></pre> <p><strong>Here is the CSS:</strong></p> <pre><code>/* GENERAL */ html { height:100%; } body { height:100%; font-family: Arial, Helvetica, sans-serif; font-weight:normal; font-style:normal; font-size:100%; } p { font size: 13px; margin: 10px 0; padding: 0; } h1 { font-size: 22px; } h2 { font-size: 17px; } h3 { font-size: 14px; } blockquote { font-style: italic; } /*POSITIONING */ .lft { float: left; } .rgt { float: right; } .rel { position: relative; } .abs { position: absolute; } /* TEXT COLOURS */ .tc6 { color: #4C4C4C; } .tc5 { color: #333333; } .tc4 { color: #999999; } .tc3 { color: #808080; } .tc2 { color: #F5F5F5; } .tc1 { color: #FFFFFF; } /* TEXT STYLING */ .bold { font-weight: bold; } .italic { font-style:italic; } /* TEXT SIZES */ .ts5 { font-size: 21px; } .ts4 { font-size: 18px; } .ts3 { font-size: 15px; } .ts2 { font-size: 13px; } .ts1 { font-size: 11px; } /* DIV COLOURS */ .dc6 { background-color: #4C4C4C; } .dc5 { background-color: #333333; } .dc4 { background-color: #999999; } .dc3 { background-color: #808080; } .dc2 { background-color: #F5F5F5; } .dc1 { background-color: #FFFFFF; } /* WIDTHS */ .full_width { width: 100%; } .thin_width { width: 940px; } /* BORDERS */ .b1 { border: 1px solid; } /* RADIUS */ .r6 { border-radius: 6px; -moz-border-radius: 6px; -webkit-border-radius: 6px; } .r2 { border-radius: 2px; -moz-border-radius: 2px; -webkit-border-radius: 2px; } /* FIELD */ .field { line-height:27px; font-family:arial, sans-serif; border-color: #d9d9d9; border-top:solid 1px #c0c0c0; padding-left:5px; margin-right: 15px; width:250px; } /* BUTTON */ .button { cursor:pointer; font-family: arial, sans-serif; min-width: 70px; padding-left: 20px; padding-right: 20px; padding-top: 10px; padding-bottom: 10px; color: white; } .button:hover { border: 1px solid #2F5BB7; } .button:active { -moz-box-shadow: 0 0 2px #888; -webkit-box-shadow: 0 0 2px #888; box-shadow: 0 0 2px #888; } /* BUTTONS */ #button_search { height: 34px; background: url(http://www.divology.com/wp-content/themes/divology/tutorials/google-search/ico-search.png) no-repeat #4d90fe center; border: 1px solid #3079ED; text-indent:-999px; color: transparent; line-height:0; font-size:0; } #button_primary { border-color: #3079ED; background-color: #55A4F2; } #button_secondary { border-color: gray; } #field_regular { height:27px; } /* FIELDS */ #field_large { height:300px; } /* HEADER */ #header-wrap { top: 0; left: 0; } #header-container { line-height: 60px; height: 60px; border-bottom: 1px solid #E5E5E5; } #header { margin: 0 auto; position: relative; } #header h1 { color: #beffbf; text-align: left; width: 290px; margin: 0; position: absolute; left: 0; top: 20px; } #header h1 em { color: #90b874; font-size: small; display: block; } #header ul { top:0; margin: 0; padding: 0; list-style: none; position: absolute; right: 0; } #header ul li { float: left; margin-right: 5px; } #header ul li a{ color: #90b874; font-weight: bold; font-size: 1.4em; margin-right: 5px; text-decoration: none; } #header ul li a:hover { color: #beffbf; } /* CONTAINER */ #container { margin: 0 auto; font-size: 1.4em; overflow: auto; padding: 31px 0 80px 0px; } #container-wrap { min-height:100%; position:relative; min-width: 940px; } #logo { height:20px; } /* FOOTER */ #footer-wrap { bottom: 0; left: 0; } #footer-container { line-height: 60px; height: 60px; bottom: 0; border-top: 1px solid #E5E5E5; } #footer { margin: 0 auto; position: relative; } #footer ul { margin: 0; padding: 0; list-style: none; position: absolute; top: 0; right: 0; } #footer ul li { float: left; margin-right: 5px; } #footer ul li a { color: #90b874; font-size: 12px; padding-left: 10px; padding-right: 10px; text-decoration: none; } #footer ul li a:hover { color: #beffbf; } #faq EM { display:none; } #faq LI STRONG { font-weight:normal; color:#246; text-decoration:underline; cursor:pointer; } .hidden { display:none; } #content{ background: orange; height: auto; } #col-main { overflow:hidden; } </code></pre> <p>I am new to CSS coding, and I have had to make a lot of decisions without really knowing my stuff. I would love to get feedback to see if I can improve this code, especially with regards to making it cleaner, short code or more compatible.</p>
[]
[ { "body": "<h2>Drop HTML4 in favor of XHTML or HTML5</h2>\n\n<p>There is no reason to stay with HTML4 any longer. Go with HTML5 or XHTML.</p>\n\n<h2>Class and ID names</h2>\n\n<p>Are your class and ID abbreviations really necessary? <code>.tc1</code> doesn't say anything about what text color the class applies. Consider using something like <code>.white-color</code> or <code>.white-text-color</code>. The same goes for all your class and ID names. Name them so you know what they do. Your css file should not be a lookup table.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T18:22:09.183", "Id": "18509", "ParentId": "16364", "Score": "2" } } ]
{ "AcceptedAnswerId": "18509", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T16:10:02.697", "Id": "16364", "Score": "3", "Tags": [ "html", "css" ], "Title": "Complex CSS layout - Docked Footer and Elastic Content" }
16364
<p>I am still learning OOP and I need a little help, I don't really know how to properly make this not look so terrible.</p> <p>Any thoughts?</p> <pre><code>&lt;?php class Noti { public static $app; public static $user; public static $url; public static $result; public static $data; public static $title; public static $text; public static function status($title = null, $text = null) { // Error check if(empty($title)) return false; if(empty($text)) return false; // Set self::$title = $title; self::$text = $text; // Get the NOTI config self::$app = Config::get('noti.app_id'); self::$user = Config::get('noti.user_token'); self::$url = Config::get('noti.url'); // Format self::$data = self::format(); // Url $ch = curl_init(self::$url.'add'); // Append add to url for status update curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, self::$data); self::$result = curl_exec($ch); // Close curl_close($ch); return self::$result; } private static function format() { $data = array( 'app' =&gt; self::$app, 'user' =&gt; self::$user, 'notification[title]' =&gt; self::$title, 'notification[text]' =&gt; self::$text ); return http_build_query($data); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T18:26:54.330", "Id": "26624", "Score": "2", "body": "A couple of words on what the code is supposed to do would be appreciated. Otherwise it's pretty hard to say tell if the code's good or not. It's obviously something to do with notifications, but what's the context?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T18:29:54.987", "Id": "26625", "Score": "0", "body": "Pretty much I call `Noti::status(title,text);` and it does a cURL post to a url with that data. It's really not anything major :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T18:35:18.100", "Id": "26627", "Score": "0", "body": "Ok, but I see you've made a static class (you could put `abstract` in there too), yet there's also some `user_token` stuff. So is this for a single-user system or are there several users to notify (in which case a non-static class might make more sense)?. I understand how you call this code and what it does, but I still don't know much about the context" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T18:40:38.973", "Id": "26628", "Score": "0", "body": "I think your thinking about it a bit too much. It's literally a single file and it gets called with `Noti::status('test', 'testing');` there is not going to be several users, there is a single user and a single app id, and a single url to notify. I could have made this a function, but the way my framework works is that classes are easier to work with as they are autoloaded." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T18:45:45.187", "Id": "26629", "Score": "0", "body": "Fair enough, but that's already more information than was in your original question - which is why I asked. Without a little bit context, others on this site are basically playing the role of a PHP interpreter, trying to run the code in their heads to figure out what's going on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T18:47:11.150", "Id": "26631", "Score": "0", "body": "Fair enough, I didn't really know what people request as this is my first time on this codereview part." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-12T05:32:21.373", "Id": "304129", "Score": "0", "body": "@Steven where is the behaviour associated with your data structure? your current class simply looks like an assortment of different types of data heaped together in one class." } ]
[ { "body": "<p>Not sure why the properties are marked <code>public</code>, since they're overwritten each time <code>Noti::status()</code> is called. There's no real point in having external code access <code>Noti::$user</code>, for instance (external code can just call <code>Config::get()</code> if it wants the values). So <code>protected</code> or <code>private</code> would be better.</p>\n\n<p>But actually, there's little point in having those static properties at all. For instacne, the <code>format</code> method could be rewritten as</p>\n\n<pre><code>private static function format($title, $text) {\n return http_build_query(array(\n 'app' =&gt; Config::get('noti.app_id'),\n 'user' =&gt; Config::get('noti.user_token'),\n 'notification[title]' =&gt; $title,\n 'notification[text]' =&gt; $text\n ));\n}\n</code></pre>\n\n<p>... and it wouldn't need to have access to any class properties at all (I'd probably call it <code>build_query</code> or <code>build_request</code> while I'm at it, since <code>format</code> isn't terribly descriptive).</p>\n\n<p>But of course, you can skip the <code>format</code> method entirely. It's private, and there's only one other method in the class, so there's only one place it'll be called. (If there were two or more places it could be called from, then a separate method would definitely make sense, of course.)</p>\n\n<p>You also don't need to store anything going on in <code>status()</code> in static properties. <code>$data = ...</code> accomplishes the same as <code>self::$data = ...</code> (without having to type <code>self::</code>). Same for <code>self::$result</code>.</p>\n\n<p>In the end, this should do the same thing</p>\n\n<pre><code>abstract class Noti {\n public static function status($title = null, $text = null) {\n if(empty($title) || empty($text)) return false;\n\n $data = http_build_query(array(\n 'app' =&gt; Config::get('noti.app_id'),\n 'user' =&gt; Config::get('noti.user_token'),\n 'notification[title]' =&gt; $title,\n 'notification[text]' =&gt; $text\n ));\n\n $url = Config::get('noti.url') . \"add\";\n\n $ch = curl_init($url);\n curl_setopt($ch, CURLOPT_POST, 1);\n curl_setopt($ch, CURLOPT_POSTFIELDS, $data);\n $result = curl_exec($ch);\n curl_close($ch);\n\n return $result;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T18:58:15.020", "Id": "16368", "ParentId": "16367", "Score": "1" } }, { "body": "<p>As Flambino said, why are you using static properties and methods? Static really contradicts the whole purpose of OOP and so it should really only be used in special cases. In fact, those special cases aren't likely to present themselves until you are much more familiar with the concept of OOP, therefore, if you ever find yourself using static elements you can stop yourself immediately and ask, \"Why?\". More than likely there is a better way to do what you are attempting without them.</p>\n\n<p>That being said, the way you are currently listing your properties is fine, but just in case you didn't already know, you only have to declare <code>public</code> once. You can separate each additional property with a comma. And since PHP doesn't care about whitespace, you can make this more legible by adding a newline after each property. This also works for properties that have default values, as demonstrated below. <strong>As Corbin pointed out in the comments, this is a preference, you can do either one.</strong></p>\n\n<pre><code>public\n $app,\n $user = 'default user',\n //etc...\n $text\n;\n</code></pre>\n\n<p>PHP's <code>empty()</code> function is really only useful on arrays, and objects. When using strings it is better to use <code>is_null()</code> or just treat the parameter/variable as a boolean directly. Note: Doing the later will have unexpected results if the parameter's value is ever a false value (0, '', \"false\", etc...). By the way, PHP inherently requires braces. Otherwise, when you add additional lines to a statement, you wouldn't have to then also add braces. As such, you should really use braces all the time, even on single line statements. People might argue this, but I feel that if PHP does not allow completely braceless code it shouldn't allow it at all, otherwise it is only going to cause issues. Additionally, you can combine those two if statements into one using the OR short circuiting operator. This follows the \"Don't Repeat Yourself\" (DRY) Principle, which, along with the Single Responsibility Principle, are important concepts when trying to learn OOP.</p>\n\n<pre><code>if( is_null( $title ) || is_null( $text ) ) {\n return FALSE;\n}\n//OR\nif( ! $title || ! $text ) {\n return FALSE;\n}\n</code></pre>\n\n<p>Speaking of Single Responsibility Principle, you are doing too much in your status method. The method should only do as much as is required to accomplish its purpose. In this case return the status. It can call as many methods as it needs to accomplish this, but it shouldn't be directly responsible for doing anything else. This ensures completely reusable code, which, as mentioned above, is a key concept of OOP. However, in this context, I don't believe the <code>status()</code> method should really have to call any other methods.</p>\n\n<p>Last, but not least, try to cut back on internal comments. If you follow the Single Responsibility Principle then your code should naturally fall into a \"self-documenting\" style, and then the only comments you will need are doccomments for recording more abstract functionality.</p>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T22:51:53.787", "Id": "26643", "Score": "0", "body": "+1, however: \"in case you didn't already know, you only have to declare public once. You can separate each additional property with a comma.\" That syntax makes me sad (separate declarations are *much* more legible in my opinion). As far as I'm aware, very few people ever use that syntax. Also, the is_null and boolean casts of the `$title`/`$text` might not do what he wants. For example, an object is considered non-null. And an array is considered non-null... So on. (I suppose it's way out of scope to completely explain the oddities of the type system in PHP :p.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T00:34:09.287", "Id": "26648", "Score": "0", "body": "To each their own. I find mine much more readable, but I imagine those with a background in Java, C, etc... would find the list a little more familiar. I did try to stress that the current implementation was fine, just trying to point out another way. As to the other, I was going by context and assuming they were strings. I did mention that arrays were more appropriate for `empty()`, perhaps I should add that about objects too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T02:28:30.580", "Id": "26654", "Score": "0", "body": "I just realized looking back at the code that a solution is for him to not provide default parameters. If he wants the function to return false when called with non-non-empty strings, he shouldn't allow a default invocation of it that defaults to the error input he checks for. That makes no sense. Also, for what it's worth, I would do: `if (!is_string($x) || $x === \"\") { ... }`. A white list approach seems more direct than a blacklist. Anyway, I'm done rambling now. Hopefully I haven't been too annoying :)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T21:14:11.130", "Id": "16374", "ParentId": "16367", "Score": "2" } }, { "body": "<p><strong>This is not OOP.</strong></p>\n\n<p>Just using <code>class</code> does not make your code object oriented. Writing OO code is about encapsulating the state and behavior into objects.</p>\n\n<p>See <a href=\"https://codereview.stackexchange.com/a/11006/7585\">this answer</a> which explains why public properties and static are bad.</p>\n\n<h2>Static is Already Hurting You</h2>\n\n<p>Your code relies on <code>Config::get</code>. Anyone who wants to reuse this class will need to have a class named <code>Config</code> with a method named <code>get</code>. This is what your class depends on. If you try to unit test this class you will find it difficult to test it as a unit. It is already hard-coded to rely on the Config class.</p>\n\n<h2>Dependency Injection / Inversion Of Control</h2>\n\n<p>To remove the tight coupling to your Config object you should pass in the dependencies to the constructor of the object:</p>\n\n<pre><code>class Noti\n{\n protected $app;\n protected $config;\n\n public function __construct(Config $config)\n {\n $this-&gt;config = $config;\n }\n\n public function getStatus()\n {\n $this-&gt;app = $this-&gt;config-&gt;get('noti.app_id');\n // etc.\n }\n}\n</code></pre>\n\n<p>Note: I would use docblock comments above to explain all of the methods and properties.</p>\n\n<p>The tight coupling to the Config class's get method has been modified. From above we see that any Config object or derived class (We type-hinted for Config in the constructor) can be passed into the Noti class. This could be further decoupled by Type-Hinting for an interface that specifies the contract for the Config object implementation.</p>\n\n<p>The testing is now simple as a mock object can be passed into the constructor and there are no hard-coded dependencies left in the code.</p>\n\n<h2>Method Names</h2>\n\n<p>Method names should be descriptive. Consider using verb+noun to describe your methods:</p>\n\n<pre><code>getStatus // instead of status\ngetQuery // instead of format\n</code></pre>\n\n<p>Now we know that we are returning the status, and formatting a URL. Note: As mseancole points out you are doing too much in your status method.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T03:29:41.853", "Id": "16384", "ParentId": "16367", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T18:20:00.567", "Id": "16367", "Score": "2", "Tags": [ "php", "object-oriented", "php5" ], "Title": "PHP Simple OOP Class" }
16367
<p>What should I use to cache the result so that it takes less time to search? It currently takes a large number of minutes to complete 10000 test cases with range 1-99999999999999 (18 times 9 - the worst case), even though the search values have been hard-coded for testing purposes (1600, 1501).</p> <pre><code>Set&lt;Integer&gt; set = new TreeSet&lt;Integer&gt;(); //some logic to populate 1600 numbers for (int cases = 0; cases &lt; totalCases; cases++) { String[] str = br.readLine().split(" "); long startRange = Long.parseLong(str[0]); long endRange = Long.parseLong(str[1]); int luckyCount = 0; for (long num = startRange; num &lt;= endRange; num++) { int[] longArray = { 1600, 1501 }; if (set.contains(longArray[0]) &amp;&amp; set.contains(longArray[1])) { luckyCount++; } } System.out.println(luckyCount); } </code></pre> <p>It actually is a problem to find a lucky number - those numbers whose sum of digits and sum of square of digits are prime. I have implemented the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow noreferrer">Sieve of Eratosthenes</a> for this. To optimize it further, I commented my <code>getDigitSum</code> method, and I thought was heavy, so I replaced it with two hard-coded values, but it still takes minutes to solve one test case. <a href="https://codereview.stackexchange.com/questions/8319/puzzle-sum-of-the-digits-is-prime-or-not">Here is a reference to actual problem asked</a>.</p> <pre><code>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Set; import java.util.TreeSet; public class Solution { private static int[] getDigitSum(long num) { long sum = 0; long squareSum = 0; for (long tempNum = num; tempNum &gt; 0; tempNum = tempNum / 10) { if (tempNum &lt; 0) { sum = sum + tempNum; squareSum = squareSum + (tempNum * tempNum); } else { long temp = tempNum % 10; sum = sum + temp; squareSum = squareSum + (temp * temp); } } int[] twosums = new int[2]; twosums[0] = Integer.parseInt(sum+""); twosums[1] = Integer.parseInt(squareSum+""); // System.out.println("sum Of digits: " + twoDoubles[0]); // System.out.println("squareSum Of digits: " + twoDoubles[1]); return twosums; } public static Set&lt;Integer&gt; getPrimeSet(int maxValue) { boolean[] primeArray = new boolean[maxValue + 1]; for (int i = 2; i &lt; primeArray.length; i++) { primeArray[i] = true; } Set&lt;Integer&gt; primeSet = new TreeSet&lt;Integer&gt;(); for (int i = 2; i &lt; maxValue; i++) { if (primeArray[i]) { primeSet.add(i); markMutiplesAsComposite(primeArray, i); } } return primeSet; } public static void markMutiplesAsComposite(boolean[] primeArray, int value) { for (int i = 2; i*value &lt; primeArray.length; i++) { primeArray[i * value] = false; } } public static void main(String args[]) throws NumberFormatException, IOException { // getDigitSum(80001001000l); //System.out.println(getPrimeSet(1600)); Set set = getPrimeSet(1600); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int totalCases = Integer.parseInt(br.readLine()); for (int cases = 0; cases &lt; totalCases; cases++) { String[] str = br.readLine().split(" "); long startRange = Long.parseLong(str[0]); long endRange = Long.parseLong(str[1]); int luckyCount = 0; for (long num = startRange; num &lt;= endRange; num++) { int[] longArray = getDigitSum(num); if(set.contains(longArray[0]) &amp;&amp; set.contains(longArray[1])){ luckyCount++; } } System.out.println(luckyCount); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T19:54:20.983", "Id": "26632", "Score": "1", "body": "What's the purpose of `startRange` and `endRange`? Is that how you would normally pick numbers to search for in `set`, or are they for something else?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T14:36:00.780", "Id": "28537", "Score": "0", "body": "You can write `squareSum += tempNum * tempNum;`, `tempNum /= 10;` and so on" } ]
[ { "body": "<p>If I'm right the following is the same:</p>\n\n<pre><code>final Set&lt;Integer&gt; set = new TreeSet&lt;Integer&gt;();\n//some logic to populate 1600 numbers\nfor (int cases = 0; cases &lt; totalCases; cases++) {\n final String[] str = br.readLine().split(\" \");\n final long startRange = Long.parseLong(str[0]);\n final long endRange = Long.parseLong(str[1]);\n int luckyCount = 0;\n final int[] longArray = { 1600, 1501 };\n if (set.contains(longArray[0]) &amp;&amp; set.contains(longArray[1])) {\n luckyCount += (endRange - startRange + 1);\n }\n System.out.println(luckyCount);\n}\n</code></pre>\n\n<p>It eliminates an unnecessary loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T21:57:12.057", "Id": "26639", "Score": "0", "body": "no they aren't same ..please check my edited pst" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T20:51:50.310", "Id": "16372", "ParentId": "16369", "Score": "0" } }, { "body": "<p>You claim the lookup in the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html\" rel=\"nofollow\" title=\"log(n) time\">TreeSet</a> takes a long time, why don't you use a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html\" rel=\"nofollow\" title=\"constant time\">HashSet</a> which guarantees constant time instead of the <code>log(n)</code> time of <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html\" rel=\"nofollow\" title=\"log(n) time\">TreeSet</a>.</p>\n\n<p>Also did you profile your code to verify that it is the lookup that is taking so much time? And that it isn't something else?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T20:41:30.773", "Id": "27976", "Score": "0", "body": "@Daniel Fischer has given good explaination here ...And yes I was wrong, m not good at algorithms , trying same .. check this http://stackoverflow.com/questions/12809177/treeset-search-taking-long-time-puzzle-to-find-lucky-numbers" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T09:41:37.517", "Id": "17550", "ParentId": "16369", "Score": "3" } }, { "body": "<p>There are few places in this implementation that can be improved. In order to to start attacking the issues i made few changes first to get an idea of the main problems:\nmade the total start cases be the value 1 and set the range to be a billion (1,000,000,000) to have a large amount of iterations. also I use the method \"getDigitSum\" but commented out the code that actually makes the sum of digits to see how the rest runs: following are the methods that were modified for an initial test run:</p>\n\n<pre><code>private static int[] getDigitSum(long num) {\n\n long sum = 0;\n long squareSum = 0;\n// for (long tempNum = num; tempNum &gt; 0; tempNum = tempNum / 10) {\n// if (tempNum &lt; 0) {\n// sum = sum + tempNum;\n// squareSum = squareSum + (tempNum * tempNum);\n// } else {\n// long temp = tempNum % 10;\n// sum = sum + temp;\n// squareSum = squareSum + (temp * temp);\n//\n// }\n// }\n int[] twosums = new int[2];\n twosums[0] = Integer.parseInt(sum+\"\");\n twosums[1] = Integer.parseInt(squareSum+\"\");\n // System.out.println(\"sum Of digits: \" + twoDoubles[0]);\n // System.out.println(\"squareSum Of digits: \" + twoDoubles[1]);\n return twosums;\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public static void main(String args[]) throws NumberFormatException,\n IOException {\n // getDigitSum(80001001000l);\n //System.out.println(getPrimeSet(1600));\n Set set = getPrimeSet(1600);\n //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int totalCases = 1;\n for (int cases = 0; cases &lt; totalCases; cases++) {\n //String[] str = br.readLine().split(\" \");\n long startRange = Long.parseLong(\"1\");\n long endRange = Long.parseLong(\"1000000000\");\n int luckyCount = 0;\n for (long num = startRange; num &lt;= endRange; num++) {\n int[] longArray = getDigitSum(num); //this method was commented for testing purpose and was replaced with any two hardcoded values\n if(set.contains(longArray[0]) &amp;&amp; set.contains(longArray[1])){\n luckyCount++;\n }\n\n\n }\n System.out.println(luckyCount);\n }\n\n} \n</code></pre>\n\n<p><strong>Running the code takes 5 minutes 8 seconds.</strong>\nnow we can start optimizing it step by step. I will now mention the various points in the implementation that can be optimized.</p>\n\n<p><em><strong>1- in the method getDigitSum(long num)</em></strong></p>\n\n<pre><code>int[] twosums = new int[2];\ntwosums[0] = Integer.parseInt(sum+\"\");\ntwosums[1] = Integer.parseInt(squareSum+\"\");\n</code></pre>\n\n<p>the above is not good. on every call to this method, two String objects are created , e.g. (sum+\"\") , before they are parsed into an int. considering the method is called billion times in my test, that produces two billion String object creation operations. since you know that the value is an int (according to the math in there and based on the links you provided), it would be enough to use casting:</p>\n\n<pre><code>twosums[0] = (int)sum;\ntwosums[1] = (int)squareSum;\n</code></pre>\n\n<p><strong>2- In the \"Main\" method, you have the following</strong> </p>\n\n<pre><code>for (long num = startRange; num &lt;= endRange; num++) {\n int[] longArray = getDigitSum(num); \\\\this method was commented for testing purpose and was replaced with any two hardcoded values\n if(set.contains(longArray[0]) &amp;&amp; set.contains(longArray[1])){\n luckyCount++;\n }\n }\n</code></pre>\n\n<p>here there are few issues:</p>\n\n<p><strong>a- set.contains(longArray[0])</strong> will create an Integer object (with autoboxing) because contains method requires an object. this is a big waste and is not necessary. in our example, billion Integer objects will be created. Also, usage of set, whether it is a treeset or hash set is not the best for our case. </p>\n\n<p>what you are trying to do is to get a set that contains the prime numbers in the range 1 .. 1600. this way, to check if a number in the range is prime, you check if it is contained in the set. This is not good as there are billions of calls to the set contains method. instead, your boolean array that you made when filling the set can be used: to find if the number 1500 is prime, simply access the index 1500 in the array. this is much faster solution. since its only 1600 elements (1600 is greater than max sum of sqaures of digits of your worst case), the wasted memory for the false locations is not an issue compared to the gain in speed. </p>\n\n<p><strong>b- int[] longArray = getDigitSum(num);</strong>\n an int array is being allocated and returned. that will happen billion times. in our case, we can define it once outside the loop and send it to the method where it gets filled. on billion iterations, this saved 7 seconds, not a big change by itslef. but if the test cases are repeated 1000 times as you plan, that is 7000 second. </p>\n\n<p>therefore, after modifying the code to implement all of the above, here is what you will have:</p>\n\n<pre><code>import java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.util.Set;\nimport java.util.TreeSet;\n\npublic class Solution {\n\nprivate static void getDigitSum(long num,int[] arr) {\n\n long sum = 0;\n long squareSum = 0;\n// for (long tempNum = num; tempNum &gt; 0; tempNum = tempNum / 10) {\n// if (tempNum &lt; 0) {\n// sum = sum + tempNum;\n// squareSum = squareSum + (tempNum * tempNum);\n// } else {\n// long temp = tempNum % 10;\n// sum = sum + temp;\n// squareSum = squareSum + (temp * temp);\n//\n// }\n// }\n arr[0] = (int)sum;\n arr[1] = (int)squareSum;\n // System.out.println(\"sum Of digits: \" + twoDoubles[0]);\n // System.out.println(\"squareSum Of digits: \" + twoDoubles[1]);\n\n}\n\npublic static boolean[] getPrimeSet(int maxValue) {\n boolean[] primeArray = new boolean[maxValue + 1];\n for (int i = 2; i &lt; primeArray.length; i++) {\n primeArray[i] = true;\n }\n\n for (int i = 2; i &lt; maxValue; i++) {\n if (primeArray[i]) {\n markMutiplesAsComposite(primeArray, i);\n }\n }\n\n return primeArray;\n}\n\npublic static void markMutiplesAsComposite(boolean[] primeArray, int value) {\n for (int i = 2; i*value &lt; primeArray.length; i++) {\n primeArray[i * value] = false;\n\n }\n}\n\npublic static void main(String args[]) throws NumberFormatException,\n IOException {\n // getDigitSum(80001001000l);\n //System.out.println(getPrimeSet(1600));\n boolean[] primeArray = getPrimeSet(1600);\n //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n int totalCases = 1;\n for (int cases = 0; cases &lt; totalCases; cases++) {\n //String[] str = br.readLine().split(\" \");\n long startRange = Long.parseLong(\"1\");\n long endRange = Long.parseLong(\"1000000000\");\n int luckyCount = 0;\n int[] longArray=new int[2];\n for (long num = startRange; num &lt;= endRange; num++) {\n getDigitSum(num,longArray); //this method was commented for testing purpose and was replaced with any two hardcoded values\n if(primeArray[longArray[0]] &amp;&amp; primeArray[longArray[1]]){\n luckyCount++;\n }\n\n\n }\n System.out.println(luckyCount);\n }\n\n}\n}\n</code></pre>\n\n<p><strong>Running the code takes 4 seconds.</strong> </p>\n\n<p>the billion iterations cost 4 seconds instead of 5 minutes 8 seconds, that is an improvement. the only issue left is the actual calculation of the sum of digits and sum of squares of digits. that code i commented out (as you can see in the code i posted). if you uncomment it, the runtime will take 6-7 minutes. and here, there is nothing to improve except if you find some mathematical way to have incremental calculation based on previous results.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T14:15:42.730", "Id": "28535", "Score": "0", "body": "`long startRange = Long.parseLong(\"1\");\n long endRange = Long.parseLong(\"1000000000\"); `can be changed in `for(long num = 1L; num<=1000000000L;..)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T14:26:45.750", "Id": "28536", "Score": "0", "body": "Thanks @cl-r. that is true. when i made the code i tried to keep the origin for minimal changes as actually they are read from the commented out line : //String[] str = br.readLine().split(\" \"); so they were initialized from Strings so i just replaced the str[0] with the String \"1\" and so with the other one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T14:42:40.117", "Id": "28538", "Score": "0", "body": "I'm just asking me if `num <1000000001L` is a better solution : compile have just to test once `<` and not `< && =`?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T13:44:21.873", "Id": "17920", "ParentId": "16369", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T19:15:19.233", "Id": "16369", "Score": "3", "Tags": [ "java", "optimization", "algorithm" ], "Title": "Caching 1600 integers and searching from treeSet takes a lot of time" }
16369
<p>I have created a simple <code>ArrayList</code> with some methods from the actual <code>ArrayList</code> in Java.</p> <p>I am testing this for mistakes, but I am learning Java and my tests are maybe not comprehensive.</p> <pre><code>public class SJUArrayList&lt;E&gt; { // Data fields private E[] theData; private int size = 0; private int capacity = 0; // Constants private static final int INIT_CAPACITY = 10; // Constructors public SJUArrayList() { this(INIT_CAPACITY); } public SJUArrayList(int initCapacity) { capacity = initCapacity; theData = (E[]) new Object[capacity]; } // Methods public boolean add(E e) { if(e == null) { throw new NullPointerException(); } if(size == capacity) { reallocate(); } theData[size] = e; size++; return true; } // End add(E e) method public void add(int index, E e) { if(index &lt; 0 || index &gt; size) { throw new ArrayIndexOutOfBoundsException(index); } if(e == null) { throw new NullPointerException(); } if(size == capacity) { reallocate(); } for(int i = size; i &gt; index; i--) { theData[i] = theData[i - 1]; } theData[index] = e; size++; } // End add(int index, E e) method public void clear() { theData = (E[]) new Object[capacity]; size = 0; } // End clear() method public boolean equals(Object o) { if(o == null) { return false; } if(getClass() != o.getClass()) { return false; } SJUArrayList&lt;E&gt; otherO = (SJUArrayList&lt;E&gt;) o; if(size != otherO.size) { return false; } for(int i = 0; i &lt; size; i++) { if(!theData[i].equals(otherO.theData[i])) { return false; } } return true; } // End equals(Object o) method public E get(int index) { if(index &lt; 0 || index &gt;= size) { throw new ArrayIndexOutOfBoundsException(index); } return theData[index]; } // End get(int index) method public int indexOf(Object o) { if(o == null) { throw new NullPointerException(); } for(int i = 0; i &lt; size; i++) { if(theData[i].equals(o)) { return i; } } return -1; } // End indexOf(Object o) method public boolean isEmpty() { return size == 0; } // End isEmpty() method public E remove(int index) { if(index &lt; 0 || index &gt;= size) { throw new ArrayIndexOutOfBoundsException(index); } E temp = theData[index]; for(int i = index + 1; i &lt; size; i++) { theData[i - 1] = theData[i]; } size--; return temp; } // End remove(int index) method public boolean remove(Object o) { int indexOfO = indexOf(o); if(indexOfO == -1) { return false; } remove(indexOfO); return true; } // End remove(Object o) method public E set(int index, E e) { if(index &lt; 0 || index &gt;= size) { throw new ArrayIndexOutOfBoundsException(index); } if(e == null) { throw new NullPointerException(); } E temp = theData[index]; theData[index] = e; return temp; } // End set(int index, E e) method public int size() { return size; } // End size() method private void reallocate() { capacity *= 2; E[] newArraylist = (E[]) new Object[capacity]; for(int i = 0; i &lt; size; i++) { newArraylist[i] = theData[i]; } theData = newArraylist; } // End reallocate() method } </code></pre> <p>I also have the following warnings:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Note: SJUArrayList.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. </code></pre> </blockquote> <p>What are they, and how can I eliminate them without using <code>-Xlint</code>?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T21:45:49.150", "Id": "26637", "Score": "0", "body": "[How do I address unchecked cast warnings?](http://stackoverflow.com/a/509115/843804)" } ]
[ { "body": "<ol>\n<li><p>Consider the following test case:</p>\n\n<pre><code>final SJUArrayList&lt;String&gt; list = new SJUArrayList&lt;String&gt;(4);\nlist.add(\"a\");\nlist.add(\"b\");\nlist.add(\"c\"); // theData contains the following: [a, b, c, null]\nlist.remove(\"c\"); // theData contains the following: [a, b, c, null]\n</code></pre>\n\n<p>It's a memory leak since the <code>theData</code> array has a reference to a removed object, therefore the garbage collector could not deallocate the memory of the unused, inaccessible <code>c</code> string object. It could be serious if you have lots of lists or use this list with bigger objects.</p></li>\n<li><p>You should implement a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#hashCode%28%29\">hashCode method</a> too:</p>\n\n<blockquote>\n <p>If two objects are equal according to the <code>equals(Object)</code> method, then calling the <code>hashCode</code> \n method on each of the two objects must produce the same integer result. </p>\n</blockquote>\n\n<p>The following test should pass:</p>\n\n<pre><code>final SJUArrayList&lt;String&gt; listOne = new SJUArrayList&lt;String&gt;(4);\nlistOne.add(\"a\");\n\nfinal SJUArrayList&lt;String&gt; listTwo = new SJUArrayList&lt;String&gt;(4);\nlistTwo.add(\"a\");\n\nassertTrue(\"equals\", listOne.equals(listTwo));\nassertEquals(\"hashCode\", listOne.hashCode(), listTwo.hashCode()); // should pass\n</code></pre></li>\n<li><p><code>-1</code> is used multiple times. It should be a named constant.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-08T18:45:02.273", "Id": "107349", "Score": "0", "body": "I disagree with -1 having to be a named constant. `-1`, `0` and `1` are pretty much exceptions to the whole \"magic numbers\" rule." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T21:43:50.173", "Id": "16375", "ParentId": "16371", "Score": "8" } }, { "body": "<ul>\n<li><p>Would be nice if this implemented an interface to make it easier for others to use. The Iterable interface would be nice to implement so that this could be used in enhanced for loops. Ideally you would implement the List interface though, then it would feel much closer to an ArrayList.</p></li>\n<li><p>The warning is being caused because you create an array of type Object and cast it to type E. Since you can't create generic arrays the only way around this is using a @SuppressWarning(\"unchecked\") annotation. I see it done in the constructor, reallocate, and clear so you may want to create a method that will create the array for you so that you only do it once.</p></li>\n<li><p>If you favor concise code you could also remove the out of bounds checks</p>\n\n<pre><code>if(index &lt; 0 || index &gt;= size) {\n throw new ArrayIndexOutOfBoundsException(index);\n}\n</code></pre>\n\n<p>If the index is out of bounds the array will throw the exception for you, this is duplicating code already in the array type.</p></li>\n<li><p>I personally favor a little extra typing to shortcuts like INIT_CAPACITY, INITIAL_CAPACITY reads so much better and its only 2 extra characters.</p></li>\n<li><p>Your reallocate could be shortened to one line using builtins</p>\n\n<pre><code>theData = Arrays.copyOf(theData, capacity *= 2);\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T13:44:20.050", "Id": "26838", "Score": "1", "body": "Frankly, `SuppressWarnings` makes me kind of nervous. There has to be a better way to deal with this. Perhaps add the proper casts as needed and/or change the type of the array field to `Object[]`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T13:49:25.037", "Id": "26839", "Score": "1", "body": "@luiscubal No, there isn't a better way because that's just the way Java generics are implemented." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-16T10:57:30.747", "Id": "94826", "Score": "0", "body": "Removing the out of bounds check is not always viable. For instance in the `get` method, the array length is probably bigger than the arraylist size. The underlying array would not necessarily throw an exception when the arraylist should." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T12:56:32.903", "Id": "16502", "ParentId": "16371", "Score": "3" } }, { "body": "<h2>Bugs?</h2>\n\n<p>If your intention was to mimic the implementation of the real ArrayList exacly, you should allow <code>add(null)</code>. Right now you're throwing an NPE.</p>\n\n<p>Same story for <code>indexOf(null)</code>. The real ArrayList just returns the proper index or -1 if there is no null element, but you throw a NullPointerException. </p>\n\n<p>Again, maybe you intended this behaviour. But from your question I got the impression you were trying to mimic the real ArrayList as a coding exercise.</p>\n\n<h2>Code duplication</h2>\n\n<p>You have some code duplication. For instance, take a look at the two overloaded <code>add</code> methods. I believe you can just write the first one like this:</p>\n\n<pre><code>public boolean add(E e) {\n add(size, e);\n}\n</code></pre>\n\n<h2>Comments</h2>\n\n<p>You end some of your methods with a comment like this: <code>// End add(E e) method</code>. While this is not strictly bad it does make me think you're in the habit of writing huge methods that are so long that these comments are necessary in order to be able to comprehend what is going on. I'd say you're better off leaving these comments out, if you keep your methods small and properly indent your code, you won't need them. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-16T10:50:35.840", "Id": "54364", "ParentId": "16371", "Score": "1" } } ]
{ "AcceptedAnswerId": "16375", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T20:21:46.533", "Id": "16371", "Score": "5", "Tags": [ "java", "array" ], "Title": "A simple ArrayList class in Java" }
16371
<p>I am making a stats page for my Android game, and I have never really used the Android XML layout stuff, so I'm sure things are a little messy and strange. The layout ends up looking pretty good, and I'm just seeing if I can remove some of the repetitive crap and maybe better understand some of the stuff I did that seemed a little strange.</p> <p><strong>stats</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="*" android:layout_weight="1"&gt; &lt;TableRow android:background="@drawable/red_background"&gt; &lt;TextView android:text="STATS" android:textColor="#FF0000" android:id="@+id/button" android:layout_height="wrap_content" android:layout_width="wrap_content" android:textSize="30dip" android:textStyle="bold" android:gravity="center" android:layout_span="3" /&gt; &lt;/TableRow&gt; &lt;TableRow android:layout_margin="10dp"/&gt; &lt;TableRow android:layout_weight="1"&gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:background="#000000" android:orientation="vertical" android:layout_span="3"&gt; &lt;TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:layout_gravity="center" android:background="@drawable/red_background"&gt; &lt;TableRow android:layout_margin="10dp"/&gt; &lt;TableRow android:gravity="center" android:layout_gravity="center"&gt; &lt;TextView android:text="Score:" android:textColor="#FF0000" android:layout_height="fill_parent" android:layout_width="fill_parent" android:textSize="20dip" android:textStyle="bold" /&gt; &lt;TextView android:layout_height="fill_parent" android:layout_width="fill_parent" android:textColor="#0000FF" android:textSize="20dip" android:textStyle="bold" android:id="@+id/Score" /&gt; &lt;/TableRow&gt; &lt;TableRow android:gravity="center" android:layout_gravity="center"&gt; &lt;TextView android:text="Sliced:" android:textColor="#FF0000" android:layout_height="fill_parent" android:layout_width="fill_parent" android:textSize="20dip" android:textStyle="bold" /&gt; &lt;TextView android:layout_height="fill_parent" android:layout_width="fill_parent" android:textColor="#0000FF" android:textSize="20dip" android:textStyle="bold" android:id="@+id/Sliced" /&gt; &lt;/TableRow&gt; &lt;TableRow android:gravity="center" android:layout_gravity="center"&gt; &lt;TextView android:text="Scorched:" android:textColor="#FF0000" android:layout_height="fill_parent" android:layout_width="fill_parent" android:textSize="20dip" android:textStyle="bold" /&gt; &lt;TextView android:layout_height="fill_parent" android:layout_width="fill_parent" android:textColor="#0000FF" android:textSize="20dip" android:textStyle="bold" android:id="@+id/Scorched" /&gt; &lt;/TableRow&gt; &lt;TableRow android:gravity="center" android:layout_gravity="center"&gt; &lt;TextView android:text="Frozen:" android:textColor="#FF0000" android:layout_height="fill_parent" android:layout_width="fill_parent" android:textSize="20dip" android:textStyle="bold" /&gt; &lt;TextView android:layout_height="fill_parent" android:layout_width="fill_parent" android:textColor="#0000FF" android:textSize="20dip" android:textStyle="bold" android:id="@+id/Frozen" /&gt; &lt;/TableRow&gt; &lt;TableRow android:gravity="center" android:layout_gravity="center"&gt; &lt;TextView android:text="Bowled:" android:textColor="#FF0000" android:layout_height="fill_parent" android:layout_width="fill_parent" android:textSize="20dip" android:textStyle="bold" /&gt; &lt;TextView android:layout_height="fill_parent" android:layout_width="fill_parent" android:textColor="#0000FF" android:textSize="20dip" android:textStyle="bold" android:id="@+id/Bowled" /&gt; &lt;/TableRow&gt; &lt;TableRow android:layout_margin="10dp"/&gt; &lt;/TableLayout&gt; &lt;/LinearLayout&gt; &lt;/TableRow&gt; &lt;TableRow android:layout_margin="10dp"/&gt; &lt;TableRow&gt; &lt;Button android:background="@drawable/blue_background" android:text="Quit" android:id="@+id/quit" android:textSize="30dip" android:textStyle="bold" android:textColor="#0000FF" android:onClick="onClick"/&gt; &lt;Button android:background="@drawable/blue_background" android:text="Play" android:id="@+id/play" android:textSize="30dip" android:textStyle="bold" android:textColor="#0000FF" android:onClick="onClick"/&gt; &lt;Button android:background="@drawable/blue_background" android:text="Post" android:id="@+id/post" android:textSize="30dip" android:textStyle="bold" android:textColor="#0000FF" android:onClick="onClick"/&gt; &lt;/TableRow&gt; &lt;/TableLayout&gt; </code></pre> <p><strong>blue_background</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;layer-list xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item&gt; &lt;shape android:shape="rectangle" &gt; &lt;corners android:radius="5dip" /&gt; &lt;solid android:color="#000000" /&gt; &lt;stroke android:width="5dip" android:color="#0000FF"/&gt; &lt;/shape&gt; &lt;/item&gt; &lt;/layer-list&gt; </code></pre> <p><strong>red_background</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;layer-list xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item&gt; &lt;shape android:shape="rectangle" &gt; &lt;corners android:radius="5dip" /&gt; &lt;solid android:color="#000000" /&gt; &lt;stroke android:width="5dip" android:color="#FF0000"/&gt; &lt;/shape&gt; &lt;/item&gt; &lt;/layer-list&gt; </code></pre>
[]
[ { "body": "<p>First of all I tried to change outer <code>TableLayout</code> to <code>RelativeLayout</code> and that's what I've got</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\"?&gt;\n&lt;RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\" &gt;\n\n &lt;TextView\n android:id=\"@+id/topButton\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentTop=\"true\"\n android:background=\"@drawable/red_background\"\n android:gravity=\"center\"\n android:text=\"STATS\"\n android:textColor=\"#FF0000\"\n android:textSize=\"30dip\"\n android:textStyle=\"bold\" /&gt;\n\n &lt;LinearLayout\n android:id=\"@+id/bottomButtons\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentBottom=\"true\"\n android:orientation=\"horizontal\" &gt;\n\n &lt;Button\n android:id=\"@+id/quit\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_weight=\"1\"\n android:background=\"@drawable/blue_background\"\n android:onClick=\"onClick\"\n android:text=\"Quit\"\n android:textColor=\"#0000FF\"\n android:textSize=\"30dip\"\n android:textStyle=\"bold\" /&gt;\n\n &lt;Button\n android:id=\"@+id/play\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_weight=\"1\"\n android:background=\"@drawable/blue_background\"\n android:onClick=\"onClick\"\n android:text=\"Play\"\n android:textColor=\"#0000FF\"\n android:textSize=\"30dip\"\n android:textStyle=\"bold\" /&gt;\n\n &lt;Button\n android:id=\"@+id/post\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_weight=\"1\"\n android:background=\"@drawable/blue_background\"\n android:onClick=\"onClick\"\n android:text=\"Post\"\n android:textColor=\"#0000FF\"\n android:textSize=\"30dip\"\n android:textStyle=\"bold\" /&gt;\n &lt;/LinearLayout&gt;\n\n &lt;TableLayout\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:layout_above=\"@id/bottomButtons\"\n android:layout_below=\"@id/topButton\"\n android:layout_gravity=\"center\"\n android:layout_marginBottom=\"20dp\"\n android:layout_marginTop=\"20dp\"\n android:background=\"@drawable/red_background\"\n android:gravity=\"center\" &gt;\n\n &lt;TableRow\n android:layout_gravity=\"center\"\n android:gravity=\"center\" &gt;\n\n &lt;TextView\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:text=\"Score:\"\n android:textColor=\"#FF0000\"\n android:textSize=\"20dip\"\n android:textStyle=\"bold\" /&gt;\n\n &lt;TextView\n android:id=\"@+id/Score\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:text=\"10\"\n android:textColor=\"#0000FF\"\n android:textSize=\"20dip\"\n android:textStyle=\"bold\" /&gt;\n &lt;/TableRow&gt;\n\n &lt;TableRow\n android:layout_gravity=\"center\"\n android:gravity=\"center\" &gt;\n\n &lt;TextView\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:text=\"Sliced:\"\n android:textColor=\"#FF0000\"\n android:textSize=\"20dip\"\n android:textStyle=\"bold\" /&gt;\n\n &lt;TextView\n android:id=\"@+id/Sliced\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:text=\"1000\"\n android:textColor=\"#0000FF\"\n android:textSize=\"20dip\"\n android:textStyle=\"bold\" /&gt;\n &lt;/TableRow&gt;\n\n &lt;TableRow\n android:layout_gravity=\"center\"\n android:gravity=\"center\" &gt;\n\n &lt;TextView\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:text=\"Scorched:\"\n android:textColor=\"#FF0000\"\n android:textSize=\"20dip\"\n android:textStyle=\"bold\" /&gt;\n\n &lt;TextView\n android:id=\"@+id/Scorched\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:text=\"10000\"\n android:textColor=\"#0000FF\"\n android:textSize=\"20dip\"\n android:textStyle=\"bold\" /&gt;\n &lt;/TableRow&gt;\n\n &lt;TableRow\n android:layout_gravity=\"center\"\n android:gravity=\"center\" &gt;\n\n &lt;TextView\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:text=\"Frozen:\"\n android:textColor=\"#FF0000\"\n android:textSize=\"20dip\"\n android:textStyle=\"bold\" /&gt;\n\n &lt;TextView\n android:id=\"@+id/Frozen\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:text=\"1000000\"\n android:textColor=\"#0000FF\"\n android:textSize=\"20dip\"\n android:textStyle=\"bold\" /&gt;\n &lt;/TableRow&gt;\n\n &lt;TableRow\n android:layout_gravity=\"center\"\n android:gravity=\"center\" &gt;\n\n &lt;TextView\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:text=\"Bowled:\"\n android:textColor=\"#FF0000\"\n android:textSize=\"20dip\"\n android:textStyle=\"bold\" /&gt;\n\n &lt;TextView\n android:id=\"@+id/Bowled\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:text=\"1000000000000\"\n android:textColor=\"#0000FF\"\n android:textSize=\"20dip\"\n android:textStyle=\"bold\" /&gt;\n &lt;/TableRow&gt;\n &lt;/TableLayout&gt;\n\n&lt;/RelativeLayout&gt;\n</code></pre>\n\n<p>It seems to me that user will see is exactly the same <img src=\"https://i.stack.imgur.com/FYTkQ.png\" alt=\"screen\"></p>\n\n<p>After these changes I wanted to understand if this layout is faster or not. For this purpose we need <a href=\"http://developer.android.com/tools/help/hierarchy-viewer.html\" rel=\"nofollow noreferrer\"><code>hierarchyviewer</code> tool from Android SDK</a>.</p>\n\n<p>Your layout based on <code>TableLayout</code> has:</p>\n\n<ul>\n<li><p>29 views</p></li>\n<li><p>Measure: 27,508ms</p></li>\n<li><p>Layout: 0,525ms</p></li>\n<li><p>Draw: 17,195ms</p></li>\n</ul>\n\n<p><img src=\"https://i.stack.imgur.com/lzlM0.png\" alt=\"table_time\"></p>\n\n<p>The full hierarchy can be viewed here <img src=\"https://i.stack.imgur.com/PDpJs.png\" alt=\"table_hierarchy\"></p>\n\n<p>Layout based on <code>RelativeLayout</code> has:</p>\n\n<ul>\n<li><p>22 views</p></li>\n<li><p>Measure: 12,150ms</p></li>\n<li><p>Layout: 0,395ms</p></li>\n<li><p>Draw: 16,446ms</p></li>\n</ul>\n\n<p><img src=\"https://i.stack.imgur.com/Smw3j.png\" alt=\"relative_time\"></p>\n\n<p>And the full hierarchy <img src=\"https://i.stack.imgur.com/EtJCa.png\" alt=\"relative_hierarchy\"></p>\n\n<p>As a conclusion we can say that the less views we have the faster the layout is. And in this case <code>RelativeLayout</code> is a little bit faster than <code>TableLayout</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T21:49:00.873", "Id": "26718", "Score": "0", "body": "Thanks, I like it, those `android:layout_alignParentBottom=\"true\"` clauses were definitely something I did not know about." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T10:43:09.977", "Id": "16397", "ParentId": "16373", "Score": "4" } } ]
{ "AcceptedAnswerId": "16397", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T20:54:15.403", "Id": "16373", "Score": "2", "Tags": [ "android", "xml" ], "Title": "An XML stats page for my game" }
16373
<p>I'm implementing a variation of the SuperFastHash in VBA for use in Excel (32-bit version, so no LongLong available) to hash strings.</p> <p>To get around the limitations of signed 32-bit Long values, I'm doing the addition and bit-shifting using Double types, and then converting from Double to Long in a way that truncates it at 31 bits (the maximum positive value -- don't want to deal with two's complement and signs).</p> <p>I'm getting answers and avoiding overflows so far, but I have a suspicion I'm making some mistakes in translation, since most implementations use all 32 bits of a uint and also deal with individual bytes from an array rather than 16-bit values coming from AscW().</p> <p>Any suggestions of improvement, especially of the string-handling, bit-shifting, or the final avalanche?</p> <pre><code>Public Function shr(ByVal Value As Long, ByVal Shift As Byte) As Long shr = Value If Shift &gt; 0 Then shr = shr \ (2 ^ Shift) End Function Public Function shl(ByVal Value As Long, ByVal Shift As Byte) As Long If Shift &gt; 0 Then shl = LimitDouble(CDbl(Value) * (2&amp; ^ Shift)) Else shl = Value End If End Function Public Function LimitDouble(ByVal d As Double) As Long '' Prevent overflow by lopping off anything beyond 31 bits Const MaxNumber As Double = 2 ^ 31 LimitDouble = CLng(d - (Fix(d / MaxNumber) * MaxNumber)) End Function Public Function SuperFastHash(ByVal dataToHash As String) As Long Dim dataLength As Long dataLength = Len(dataToHash) If (dataLength = 0) Then SuperFastHash = 0 Exit Function End If Dim hash As Long hash = dataLength Dim remainingBytes As Integer remainingBytes = dataLength Mod 2 Dim numberOfLoops As Integer numberOfLoops = dataLength \ 2 Dim currentIndex As Integer currentIndex = 0 Dim tmp As Double Do While (numberOfLoops &gt; 0) hash = LimitDouble(CDbl(hash) + AscW(Mid$(dataToHash, currentIndex + 1, 1))) tmp = shl(AscW(Mid$(dataToHash, currentIndex + 2, 1)), 11) Xor hash hash = shl(hash, 16) Xor tmp hash = LimitDouble(CDbl(hash) + shr(hash, 11)) currentIndex = currentIndex + 2 numberOfLoops = numberOfLoops - 1 Loop If remainingBytes = 1 Then hash = LimitDouble(CDbl(hash) + AscW(Mid$(dataToHash, currentIndex + 1, 1))) hash = hash Xor shl(hash, 10) hash = LimitDouble(CDbl(hash) + shr(hash, 1)) End If '' Final avalanche hash = hash Xor shl(hash, 3) hash = LimitDouble(CDbl(hash) + shr(hash, 5)) hash = hash Xor shl(hash, 4) hash = LimitDouble(CDbl(hash) + shr(hash, 17)) hash = hash Xor shl(hash, 25) hash = LimitDouble(CDbl(hash) + shr(hash, 6)) SuperFastHash = hash End Function </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T09:44:54.067", "Id": "26665", "Score": "0", "body": "Have you considered using `Decimal` data type? From excel help `Decimal variables are stored as 96-bit (12-byte) signed integers scaled by a variable power of 10`. `Decimal` can store 32bit or 64 bit unsigned integers" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T13:51:26.237", "Id": "26683", "Score": "0", "body": "Doubles perform better than Decimal, and the Decimal type stores numbers in a way that wouldn't work with the AND and XOR operations, so I still have to thunk them back and forth to a 32-bit integer of some sort for the computation." } ]
[ { "body": "<p><strong>This is quite possibly the most clever VBA code I have ever seen.</strong></p>\n\n<p>There's not much room for improvement here, except a couple naming nitpicks:</p>\n\n<ul>\n<li>If that's what they stand for, functions <code>shr</code> and <code>shl</code> could afford to be called <code>ShiftRight</code> and <code>ShiftLeft</code>.</li>\n<li>I don't see a reason for <code>shr</code> and <code>shl</code> to not follow the <strong>PascalCasing</strong> naming convention.</li>\n<li>Given the almost-flawlessly consistent <strong>camelCasing</strong> convention for locals &amp; parameters, I don't see a reason for <code>Value</code> and <code>Shift</code> parameters to not stick to it. (except perhaps VBA/VB6's stubornness with casing?)</li>\n</ul>\n\n<p>As for string handling, as per <a href=\"http://www.aivosto.com/vbtips/stringopt3.html\">this source</a> <code>AscW</code> is faster than <code>Asc</code> so again, good call:</p>\n\n<blockquote>\n <p><strong>AscW(Mid$(..)) considerations</strong></p>\n \n <p>Don't copy too many characters with Mid$. AscW only examines the first\n character anyway. AscW(Mid$(s, x, 1)) is the best call. Note that if\n you call AscW(Mid$(s, x)) without the third parameter, Mid$ executes\n slowly when s is a long string.</p>\n \n <p>Example of potentially slow code:</p>\n\n<pre><code>For x = 1 To Len(s)\n If AscW(Mid$(s, x)) = ... Then ... \nNext\n</code></pre>\n \n <p>The above is better written as:</p>\n\n<pre><code>For x = 1 To Len(s)\n If AscW(Mid$(s, x, 1)) = ... Then ... \nNext\n</code></pre>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T06:59:50.327", "Id": "35473", "ParentId": "16377", "Score": "7" } }, { "body": "<p>in your <code>SuperFastHash</code> function you are Dimming and setting variables and then using them in a fashion that looks messy to me even though it is in a logical order. </p>\n\n<p>the set up should be separate from the actual logic of the code to make it more clear and readable.</p>\n\n<p>you should Dim all the variables at the beginning of the function and then follow with the logic so that it the flow is clear and understandable</p>\n\n<p>it should look like this:</p>\n\n<pre><code>Public Function SuperFastHash(ByVal dataToHash As String) As Long\n Dim dataLength As Long\n Dim hash As Long\n Dim remainingBytes As Integer\n Dim numberOfLoops As Integer\n Dim currentIndex As Integer\n Dim tmp As Double\n\n dataLength = Len(dataToHash)\n If (dataLength = 0) Then\n SuperFastHash = 0\n Exit Function\n End If\n hash = dataLength \n remainingBytes = dataLength Mod 2\n numberOfLoops = dataLength \\ 2\n currentIndex = 0\n</code></pre>\n\n<p>this looks much clearer about what is going on and is a good coding practice</p>\n\n<p><em>(as I was writing this I thought this was going to be the only answer, but then retailcoder posted an answer)</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T07:23:40.990", "Id": "57500", "Score": "0", "body": "+1 for finding something to say on that one - although I didn't mention this point because I felt (with the *camelCasing* of locals) the programmer came from a C or C# background, where the norm is more to declare *as close as possible to usage*. But I agree in short VBA/VB6 functions it *does* look cleaner that way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T07:31:54.570", "Id": "57501", "Score": "0", "body": "I mostly Code in C# and I disagree with *declare as close as possible to usage* if it isn't super huge then I declare at the beginning, and never staggered like that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-02-18T01:54:24.470", "Id": "294712", "Score": "1", "body": "I cut my teeth in BASIC, followed by QB, VBA, etc., but over the last 10 years or so I spend most of my time in C#, where variables are more traditionally declared before first use. I struggle with being consistent here between C#, VBA, JS, T-SQL, and other languages I switch among during the day. Advantage for top-declaration is clarity of what variables are needed. Advantage of JIT declaration is better control over when a variable *should* be useable. I think you're right in this case -- the function is short enough that top declaration would be cleaner." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-16T07:20:38.510", "Id": "35474", "ParentId": "16377", "Score": "5" } }, { "body": "<p>Nothing major, just some stylistic comments....</p>\n\n<ul>\n<li><p>The Do While loop can be rewritten more clearly as a <code>For i = 0 to dataLength \\ 2</code> </p></li>\n<li><p>the variable <code>remainingBytes</code> is unnecessary, and if used should be a boolean not an integer. </p></li>\n<li><p><code>tmp</code> can be declared inside the loop as it is never used outside it.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T20:52:35.173", "Id": "57667", "Score": "0", "body": "I find a better name for a Boolean would be `hasRemainingBytes` - `remainingBytes` does sound like an integer to me, although I agree with your point. Also in VBA declaring variables inside a loop affects readability negatively imho - VBA doesn't scope variables at that level." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-18T05:56:57.683", "Id": "57723", "Score": "1", "body": "@retailcoder: I'd prefer to just get rid of `remaingBytes`, but if not changing the name as well would be good. As for `tmp` and scope, I think VBA gives you a choice of evils, and putting it where it should be if there was a good choice is the best you can do in this case. Fortunately, the value truly is temporary in this case, assigned and then read just once per iteration. Declaring it outside of the loop gives the impression that it will be used outside of the loop, when the truth is it could be, but isn't, no matter where it is declared." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T07:13:25.243", "Id": "35522", "ParentId": "16377", "Score": "6" } } ]
{ "AcceptedAnswerId": "35473", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T22:13:33.910", "Id": "16377", "Score": "15", "Tags": [ "algorithm", "vba" ], "Title": "How can I improve this 31-bit SuperFastHash implementation in VBA?" }
16377
<p>How should I make this more Ruby-like or just "better"?</p> <pre><code>def password_format_is_valid?(submitted_password) #Gets regular expression for password format validation from settings and applies it regex = Regexp.new(Setting['global_admin.password_format_regex']) if submitted_password =~ regex then return true else self.errors.add(:password, Setting['global_admin.password_format_error_message']) return false end end </code></pre>
[]
[ { "body": "<p>There is no need to write explicit <strong>return</strong> . You can omit it. Because in Ruby the result of last executed statement in your code is returned automatically.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T04:30:57.940", "Id": "26658", "Score": "0", "body": "Care to expand your answer a bit to explain _why_ `return` can be omitted?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T03:18:38.893", "Id": "16383", "ParentId": "16378", "Score": "0" } }, { "body": "<p>It seems like you need a Rails validation callback (and a virtual attribute for <code>submitted_password</code>). I'd write:</p>\n\n<pre><code>attr_accessor :submitted_password\nvalidate :password_format_is_valid?\n\ndef password_format_is_valid?\n regex = Regexp.new(Setting['global_admin.password_format_regex'])\n unless submitted_password =~ regex\n self.errors.add(:password, Setting['global_admin.password_format_error_message'])\n false\n end\nend\n</code></pre>\n\n<p>Comments:</p>\n\n<ul>\n<li><p>In the vein of Lisp, the last expression of a body in Ruby is the return value of the method/block, so no need to use an explicit <code>return</code> (in fact it's unidiomatic and discouraged)</p></li>\n<li><p>Note that Rails can validate fields with regular expression, you should use the predefined validations whenever possible: <a href=\"http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_format_of\" rel=\"nofollow\"><code>validates_format_of</code></a>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T15:03:43.447", "Id": "26689", "Score": "0", "body": "Thank you for the explanation and example - much appreciated!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T21:09:12.380", "Id": "29419", "Score": "0", "body": "This returns `nil` when the password is valid." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-10T21:42:31.933", "Id": "29420", "Score": "0", "body": "@steenslag: Indeed, I tried to write the method as a Rails callback, but the code was incomplete. Edited." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T09:05:00.707", "Id": "16393", "ParentId": "16378", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T22:22:08.607", "Id": "16378", "Score": "5", "Tags": [ "ruby", "validation" ], "Title": "Validating a password format" }
16378
<p>I am trying to write a price calculator for proof reading using javascript. It works but I am sure that my code could be improved quite a bit. </p> <p>The concept is as follows:</p> <p>There are three factors affecting the price:</p> <ul> <li>word count</li> <li>proof reading type</li> <li>timeline (how quickly the document is proof read)</li> </ul> <p>The user enters a word count and then selects a proof reading type.</p> <p>The timeline select box (which has various timeline options such as 6hours, 24hours etc) will be generated based on the wordcount.</p> <ul> <li>If the word count is less than 5000 there will be 5 options</li> <li>If the word count is between 5000-10000, there will be only four options (it's not humanly possible to proof read 10000 words in 6 hours)</li> <li>and so on</li> </ul> <p>Can you have a look at the code and tell me how this can be improved?</p> <p>A working version of the code can be found on jsfiddle here:</p> <blockquote> <p><a href="http://jsfiddle.net/8K6wr/" rel="nofollow">http://jsfiddle.net/8K6wr/</a></p> </blockquote> <p>Here is the source:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; function getQuantity() { var theForm = document.forms["pricequote"]; var quantity = theForm.elements["quantity"]; var howmany =0; if(quantity.value!="") { howmany = parseInt(quantity.value); } return howmany; } function ClearOptionsFast(hoursbased) { var selectObj = document.getElementById('hoursbased'); var selectParentNode = selectObj.parentNode; var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy selectParentNode.replaceChild(newSelectObj, selectObj); return newSelectObj; } function setOption1(arrayvals) { document.pricequote.hoursbased.options[0]=new Option("Select Hour Specifications",""); document.pricequote.hoursbased.options[1]=new Option("6 Hours",arrayvals[0]); document.pricequote.hoursbased.options[2]=new Option("24 Hours",arrayvals[1]); document.pricequote.hoursbased.options[3]=new Option("48 Hours",arrayvals[2]); document.pricequote.hoursbased.options[4]=new Option("1 Week",arrayvals[3]); document.pricequote.hoursbased.options[5]=new Option("2 Weeks",arrayvals[4]); return true; } function setOption2(arrayvals) { document.pricequote.hoursbased.options[0]=new Option("Select Hour Specifications",""); document.pricequote.hoursbased.options[1]=new Option("24 Hours",arrayvals[1]); document.pricequote.hoursbased.options[2]=new Option("48 Hours",arrayvals[2]); document.pricequote.hoursbased.options[3]=new Option("1 Week",arrayvals[3]); document.pricequote.hoursbased.options[4]=new Option("2 Weeks",arrayvals[4]); return true; } function setOption3(arrayvals) { document.pricequote.hoursbased.options[0]=new Option("Select Hour Specifications",""); document.pricequote.hoursbased.options[1]=new Option("48 Hours",arrayvals[2]); document.pricequote.hoursbased.options[2]=new Option("1 Week",arrayvals[3]); document.pricequote.hoursbased.options[3]=new Option("2 Weeks",arrayvals[4]); return true; } function setOption4(arrayvals) { document.pricequote.hoursbased.options[0]=new Option("Select Hour Specifications",""); document.pricequote.hoursbased.options[1]=new Option("1 Week",arrayvals[3]); document.pricequote.hoursbased.options[2]=new Option("2 Weeks",arrayvals[4]); return true; } function setOption5(arrayvals) { document.pricequote.hoursbased.options[0]=new Option("Select Hour Specifications",""); document.pricequote.hoursbased.options[1]=new Option("2 Weeks",arrayvals[4]); return true; } function fixUnitPrice(proofarray) { if(getQuantity() &lt;= 5000) { ClearOptionsFast('MySelect'); setOption1(proofarray); } else if(getQuantity() &gt;= 5000 &amp;&amp; getQuantity() &lt;= 10000){ ClearOptionsFast('MySelect'); setOption2(proofarray); } else if(getQuantity() &gt;= 10000 &amp;&amp; getQuantity() &lt;= 30000){ ClearOptionsFast('MySelect'); setOption3(proofarray); } else if(getQuantity() &gt;= 30000 &amp;&amp; getQuantity() &lt;= 60000){ ClearOptionsFast('MySelect'); setOption4(proofarray); } else if(getQuantity() &gt;= 60000 &amp;&amp; getQuantity() &lt;= 100000){ ClearOptionsFast('MySelect'); setOption5(proofarray); } else { ClearOptionsFast('MySelect'); } return true; } function hourBasisPrice(documtype) { document.pricequote.hoursbased.options.length = 0; switch (documtype) { case "students": var studarray = [0.8,0.6,0.5,0.45,0.4]; fixUnitPrice(studarray); break; case "academicians": var acadarray = [1.0,0.7,0.6,0.5,0.45]; fixUnitPrice(acadarray); break; case "professionals": var profarray = [1.2,0.8,0.7,0.6,0.55]; fixUnitPrice(profarray); break; case "personal": var persarray = [1.4,0.9,0.8,0.7,0.65]; fixUnitPrice(profarray); break; } return true; } function getTotal() { var e = document.getElementById("hoursbased"); var strUser = e.options[e.selectedIndex].value; var totalPrice = getQuantity() * strUser; //display the result document.getElementById('totalPrice').innerHTML = "Total Price For Proofreading USD"+totalPrice; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="#" id="pricequote" name="pricequote" onsubmit="return false"&gt; &lt;table width="501" border="0" cellpadding="10" cellspacing="20" style="padding-top:30px;"&gt; &lt;tr&gt; &lt;th scope="row"&gt;Word Count:&lt;/th&gt; &lt;td&gt;&lt;input type="text" name="quantity" id="quantity" onchange="javascript: hourBasisPrice(document.pricequote.size.options[document.pricequote.size.selectedIndex].value);"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th width="67" scope="row"&gt;Type:&lt;/th&gt; &lt;td width="273" class="select-box"&gt; &lt;select id="type" name="size" onchange="javascript: hourBasisPrice(this.options[this.selectedIndex].value);"&gt; &lt;option value="None"&gt;Select Type&lt;/option&gt; &lt;option value="students"&gt;Proofreading for students&lt;/option&gt; &lt;option value="academicians"&gt;Proofreading for academicians&lt;/option&gt; &lt;option value="professionals"&gt;Proofreading for Professionals/Businesses&lt;/option&gt; &lt;option value="personal"&gt;Proofreading &amp;amp; editing personal documents&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th width="67" scope="row"&gt;Hour Specifications:&lt;/th&gt; &lt;td width="273" class="select-box"&gt; &lt;select id="hoursbased" name="hoursbased"&gt; &lt;option value=""&gt;Select Hour Specifications&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th scope="row"&gt;&amp;nbsp;&lt;/th&gt; &lt;td&gt;&lt;input class="button" type="button" value="Update" onmousedown="getTotal()"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt; Price:&lt;/th&gt; &lt;td&gt;&lt;div id="totalPrice" style="float:right;"&gt;&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;​ </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T20:24:30.387", "Id": "26645", "Score": "0", "body": "Your calculation is not clear .. can you break it down to simple formula x + y etc ...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T20:45:20.877", "Id": "26646", "Score": "0", "body": "@Baba If you can have a look at the code and its result, it may give you an idea i believe..." } ]
[ { "body": "<p>You repeat yourself alot. You always want to keep things DRY (don't repeat yourself). Look at your code. If you see sections that are similar but different in small ways combine the similarities.</p>\n\n<p>e.g. in your <code>hourBasisPrice</code> function you do the same thing for each switch option. Establish an array and then pass on to the other function. Instead I would establish an array with all of this info and then perform a lookup. Check the code below. All the values are in one place and then the work is done at the bottom.</p>\n\n<pre><code>var priceArray = [\n [\"students\", [0.8, 0.6, 0.5, 0.45, 0.40]],\n [\"academicians\", [1.0, 0.7, 0.6, 0.50, 0.45]],\n [\"professionals\", [1.2, 0.8, 0.7, 0.60, 0.55]],\n [\"personal\", [1.4, 0.9, 0.8, 0.70, 0.65]]\n ]\n\n for (i = 0; i &lt; priceArray.length; i++) {\n if (priceArray[i][0] == documtype) {\n fixUnitPrice(priceArray[i][1]);\n break;\n }\n }\n</code></pre>\n\n<p>Your <code>fixUnitPrice</code> function does a few things that I would change. One is that you call <code>getQuantity</code> over and over again. If the value was 75,000 then it would have to calculate the quantity nine times. Call it once and put the value into a local variable. Then check that value.</p>\n\n<p>But better yet would be to rethink the adding of options completely. You are checking whether a value is between two values and then adding options accordingly. But the options are all the same (with the lower ones missing). So really you are adding an option if the value is below a certain threshold. This is how I would handle this. I build another lookup table and check if the hours worked (notice the more descriptive variable name) is less than the threshold. Then I return the available options.</p>\n\n<pre><code>function getAllowedOptions(rateArray) {\n var hoursWorked = getQuantity();\n\n var hourlyTable = [\n [5000, \"6 Hours\"],\n [10000, \"24 Hours\"],\n [30000, \"48 Hours\"],\n [60000, \"1 Week\"], \n [100000, \"2 Weeks\"]\n ]\n\n var options = [];\n\n for (i = 0; i &lt; hourlyTable.length; i++) {\n if (hoursWorked &lt; hourlyTable[i][0]) { \n options.push(new Option(hourlyTable[i][1], rateArray[i]));\n }\n }\n\n return options;\n}\n</code></pre>\n\n<p>This would change the other function as follows:</p>\n\n<pre><code>function fixUnitPrice(rateArray) {\n\n var options = getAllowedOptions(rateArray);\n\n ClearOptionsFast('MySelect');\n\n document.pricequote.hoursbased.options[0] = new Option(\"Select Hour Specifications\", \"\"); // always added\n\n for (i = 0; i &lt; options.length; i++) {\n document.pricequote.hoursbased.options.add(options[i]);\n }\n return true; // not sure why we are returning true here but I left it.\n}\n</code></pre>\n\n<p>I did not look at the other functions. These jumped out at me as the problem.</p>\n\n<p><a href=\"http://jsfiddle.net/8K6wr/2/\" rel=\"nofollow\">http://jsfiddle.net/8K6wr/2/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T10:09:38.160", "Id": "26668", "Score": "0", "body": "Thanks for your answer...I have learned so many things from your answer... Is it possible to update the totalprice as soon as we change the word-count to increase or decrease? I have edited the code of yours with new variable names... and Here it is http://jsfiddle.net/YeCSh/\n\nThanks again... Thanks a lot" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T01:59:58.720", "Id": "16381", "ParentId": "16379", "Score": "1" } } ]
{ "AcceptedAnswerId": "16381", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-09T20:19:04.740", "Id": "16379", "Score": "4", "Tags": [ "javascript" ], "Title": "Calculate cost based on wordcount and hour basis" }
16379
<p>I threw this together for a web dev class I am taking at school and I thought I'd throw it up to see what criticism I could get on my JavaScript, design, whatever.</p> <p>Bonus points if you can tell me how I can fix the bug with users clicking to quickly and more than two cards flipping at a time.</p> <p>Disclaimer: I know that I left the cheat in so you can get the first set of cards. I didn't want anybody going crazy before getting that first set.</p> <p>Here is the <a href="http://mattgowie.com/im2401_ex03/" rel="nofollow">Card Matching Game</a>.</p> <pre><code>// Author: Matt Gowie // Created on: 10/01/12 // Project for Web Dev 2400 $(document).ready(function(){ var cardArray = [ 'd-ace', 'd-ace', 's-ace', 's-ace', 'c-ace', 'c-ace', 'h-ace', 'h-ace', 'd-king', 'd-king', 's-king', 's-king', 'c-king', 'c-king', 'h-king', 'h-king', 'd-quen', 'd-quen', 's-quen', 's-quen', 'c-quen', 'c-quen', 'h-quen', 'h-quen', 'd-jack', 'd-jack', 's-jack', 's-jack', 'c-jack', 'c-jack', 'h-jack', 'h-jack', 'd-ten', 'd-ten', 's-ten', 's-ten', 'c-ten', 'c-ten', 'h-ten', 'h-ten', 'd-nine', 'd-nine', 's-nine', 's-nine', 'c-nine', 'c-nine', 'h-nine', 'h-nine', 'd-sev', 'd-sev', 's-sev', 's-sev', 'c-sev', 'c-sev', 'h-sev', 'h-sev', 'd-six', 'd-six', 'joker', 'joker' ]; var cardsToFlip = []; var matches = 0; var score = 0; var multiplyer = 10; fillBoard = function(){ $('.board').html('') var rowCount = 1; var colCount = 1; var card = '&lt;div class="card back"&gt;&lt;/div&gt;'; for(var i = 1; i &lt;= 60; i++ ){ var cardPick = Math.floor(Math.random() * cardArray.length); var cardClass = cardArray.splice(cardPick, 1)[0]; var $card = $(card).data('cardClass', cardClass); // For debugging! if(cardClass == 's-ace'){ $card.addClass('debug'); } var $container = $('&lt;div class="container"&gt;').attr('id', "card" + i) .addClass("row" + rowCount).addClass("col" + colCount); var $cardContainer = $('&lt;div class="card-container"&gt;') .data('cardSide', 'back').append($card); $container.html($cardContainer); $('.board').append($container); colCount += 1; if(i % 10 === 0){ rowCount += 1; colCount = 1; } } }(); $('.container').bind('click', function(){ var cardId = $(this).attr('id'); if(cardsToFlip.length &lt;= 1 &amp;&amp; cardsToFlip[0] !== cardId){ flipCard(this); cardsToFlip.push(cardId); } else { if(cardsMatch()){ console.log("Cards Matched!"); $(cardsToFlip).each(function(i, e){ $("#" + e).html('') }) matches += 1; $('.matches').html(matches); score += 10 * multiplyer; $('.score').html(score) $('.mult').html('10X') } else { console.log('Multiplyer: ' + multiplyer); if(multiplyer != 1){ multiplyer -= 1; } $('.mult').html(multiplyer + 'X'); $(cardsToFlip).each(function(i, e){ flipCard($("#" + e)); }) } cardsToFlip = []; } }); var cardsMatch = function() { var cardOneClass = $('#' + cardsToFlip[0]).find('.card').data('cardClass'); var cardTwoClass = $('#' + cardsToFlip[1]).find('.card').data('cardClass'); if(cardOneClass === cardTwoClass){ return true; } else { return false; } } var flipCard = function(container) { var classToRemove, classToAdd, flipDir; console.log("flipCard called"); var $cardContainer = $(container).children('.card-container'); var $card = $cardContainer.children('.card'); var cardSide = $cardContainer.data('cardSide'); var cardClass = $card.data('cardClass'); if(cardSide == 'back'){ classToRemove = 'back'; classToAdd = cardClass; flipDir = 'rl'; $cardContainer.data('cardSide', 'front'); } else { classToRemove = 'front ' + cardClass; classToAdd = 'back'; flipDir = 'lr'; $cardContainer.data('cardSide', 'back'); } $card.css({ 'background-color': '#AB0000' }); $card.flip({ direction: flipDir, onBefore: function() { console.log("classToRemove in onBefore: " + classToRemove); $card.removeClass(classToRemove).addClass(classToAdd); }, onEnd: function() { $card.css({ 'background-color': 'rgba(0, 0, 0, 0.0)' }); }, speed: '750', color: '#AB0000' }) } }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T03:13:24.847", "Id": "26728", "Score": "0", "body": "Always useful to send the code through [jshint](http://www.jshint.com) and see what warnings you get (I see a bunch of missing semi-colons and one implied global). Oh, and it's spelled \"multiplier\" :)" } ]
[ { "body": "<p>Haven't had the time to go over all your code in detail, but here are a few ideas.</p>\n\n<p>Overall, my first suggestion would be to separate the various pieces into several more functions. Keep the HTML-manipulation (building, styling, flipping cards) separate from the more abstract parts (score calculation, the card repetoire, etc.). In the same way a game of chess can be played by players with a board made of pebbles and chalk - or without a board entirely - the <em>logic</em> of this game is independent of its <em>presentation</em>.</p>\n\n<p>You have several discreet steps here: Make a deck of <em>n</em> pairs, shuffle the deck, then make the actual HTML. Each of these steps should be a separate function. This is basically <em>top-down design</em>: Figure out what are the overall steps are, then figure out how to do each step.</p>\n\n<p>I'd also say you could be more abstract, just in general. For one, you don't really have to care about the actual suit and value of a card - at least not in your JS; the point is just that there are <em>n</em> number of discreet pairs. It doesn't need to be playing cards. You have 30 pairs, but I say <em>n</em> because the exact number is irrelevant. There just needs to be at least 1 pair.</p>\n\n<p>So far you might have something like:</p>\n\n<pre><code>function buildDeck(numberOfPairs) {\n var i, deck = [];\n for( i = 0 ; i &lt; numberOfPairs ; i++ ) {\n deck = deck.push(i, i);\n }\n return deck;\n\n /* re the comments, you could alternatively do this:\n for( i = 0 ; i &lt; numberOfPairs ; i++ ) {\n deck = deck.push(i);\n }\n return deck.concat(deck);\n */\n}\n\nfunction shuffleDeck(deck) {\n var rand, shuffled = [];\n while( deck.length &gt; 0 ) {\n rand = Math.random() * deck.length;\n shuffled.push(deck.splice(rand, 1)[0]);\n }\n return shuffled;\n}\n\nfunction buildCards(deck) {\n var i, l;\n for( i = 0, l = deck.length ; i &lt; l ; i++ ) {\n buildCard(deck[i]);\n }\n}\n</code></pre>\n\n<p>The <code>buildCard</code> function isn't implemented yet, but it would be responsible for making the HTML for a single card, and adding it to the board. That step could also be divided into more discreet steps: Build a blank card, give it its specific value, append to document, etc..</p>\n\n<p>Note that the deck is just an array of numbers at this point. The deck can be any size (that's divisible by 2 anyway), since it's not based on a pre-defined, finite list of aces, kings, queens, jacks, etc.. Now obviously, each card needs to <em>look</em> different, but that can be accomplished in the CSS alone. Simply give each card a class like <code>\"card_\" + value</code> (kinda like you're already doing for the <code>id</code> attribute, except IDs must be unique, whereas there must be exactly 2 cards with the same value-class), and only deal with the \"class_x → image_y\" in the CSS.</p>\n\n<p>Of course, you could further encapsulate the deck-logic in a <code>Deck</code> class and so on, and so on. But that's for another day.</p>\n\n<p>Hopefully this gives you some ideas.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T21:02:23.833", "Id": "27886", "Score": "0", "body": "Thanks! I will definitely go about implementing this and put up and update a bit later. I'd upvote your answer, but it seems I cant do that since I have 11 reputation. I appreciate the help though" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T21:20:34.520", "Id": "27889", "Score": "0", "body": "Question: Why did you use the array method concat in buildDeck and then push in shuffled? Looking up the concat method it seems, at least at first glance, that it is equivalent to push? Is there a reason behind that? Thanks again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T21:33:21.640", "Id": "27890", "Score": "0", "body": "@Gowie47 You're right; the use of `concat` could and should be `.push(i, i)`. Or you could push just 1 `i`, and concat the array with itself afterwards. I'll update my answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T21:50:13.403", "Id": "27891", "Score": "1", "body": "@Gowie47 re your first comment: Don't update the code in your question. If people update their questions, everyone would have to rewrite their answers too, or they'd lose their meaning. So leave your original code in the question untouched (you can add new stuff to the question, though). As for upvoting, thanks, but there's no need for that since you asked the question, which means you - and only you - can checkmark the answer that helped the most. Wait and see if someone else posts something, but sooner or later you have to checkmark an answer in order to mark this question as answered." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T23:21:30.650", "Id": "16491", "ParentId": "16386", "Score": "3" } } ]
{ "AcceptedAnswerId": "16491", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T05:43:47.067", "Id": "16386", "Score": "3", "Tags": [ "javascript", "html", "game", "css", "playing-cards" ], "Title": "How'd I do on this card matching game?" }
16386
<p>Gentlemen!</p> <p>So what I have here is a function who's main purpose is to check whether an attribute exists and if so add it to another list for a maximum of 3 entries. The first item in the list should always be checked while the rest of the list should be inserted into the new list randomly.</p> <p>ex: Old List: 0, 1, 2, 3, 4 New List: 0, 3, 1</p> <p>Code follows.</p> <pre><code>private function getList(&amp;$oldList, $type = 'atrb1') { $list = array(); if(isset($oldList-&gt;item[0]-&gt;attribute)) { if($oldList-&gt;item[0]-&gt;attribute-&gt;type == $type) { $list[] = 0; } } $keys = array_keys($oldList-&gt;items); shuffle($keys); for($i = 0; $i &lt; count($keys); $i++) { if(isset($oldList-&gt;item[$keys[$i]]-&gt;attribute) &amp;&amp; $keys[$i] != 0 ) { if($oldList-&gt;item[$keys[$i]]-&gt;attribute-&gt;type == $type) { if(count($list) == 3) { break; } else { $list[count($list)] = $keys[$i]; } } } } return $list; } </code></pre> <p>I appreciate the review, I have some more but they take time to sanitize :)</p>
[]
[ { "body": "<p>This method seems... odd... Why would you need to do this? Anyways, unimportant... Like I mentioned in the other review, the referenced parameters are unnecessary when you could more easily use, and put better use to, properties.</p>\n\n<p>Also, as I mentioned in that other review, there is room for adding more methods here. I didn't give an example in the last review, but I'll give a hint here. That first if statement would make a lovely new addition. Try to think about how that could be reused, and is used currently. My examples below and in the previous review should help you to figure this out.</p>\n\n<p>Don't call functions in the parameter list for for or while loops. They are called on each iteration of the loop, meaning your program will become less efficient. Perform the count before the loop and set it as a variable, then pass that variable into the loop instead.</p>\n\n<pre><code>$count = count( $keys );\nfor( $i = 0; $i &lt; $count; $i++ ) {\n</code></pre>\n\n<p>As I mentioned in the last review, don't violate DRY, or the Arrow anti pattern.</p>\n\n<pre><code>$item = $oldList-&gt;item[ $keys[ $i ] ];\nif( ! isset( $item-&gt;attribute ) || $keys[ $i ] == 0 ) {\n continue;\n}\n</code></pre>\n\n<p>To help with the Arrow anti pattern, you should add the following statement before the one mentioned above the to ensure no unnecessary processing is done.</p>\n\n<pre><code>if( count( $list ) == 3 ) {\n break;\n}\n</code></pre>\n\n<p>Of course, the above would become unnecessary if you limited your loop or array to the proper size initially. Limiting the loop might be impossible in this context, but I mention it for completeness. The following is about to get a little complicated and may not even be \"better\" (I didn't test or profile it). So, you can follow along if you want, but you don't need to use it, I'm just demonstrating. BTW: this requires a relatively new version of PHP (5.3 I believe).</p>\n\n<pre><code>//remove all unwanted keys\n$keys = array_filter( $keys, function( $val ) use( $keys, $oldList, $type ) {\n //remove zero as you appear not to want it\n if( $val == 0 ) {\n return FALSE;\n }\n\n //remove elements without the proper attribute\n $item = $oldList-&gt;item[ key( $keys ) ];\n return isset( $item-&gt;attribute ) &amp;&amp; $item-&gt;attribute-&gt;type == $type;\n} );\n\nshuffle( $keys );\n\n//get max size, adjusted for initial addition\n$max = 3 - count( $list );\n\n//get correctly sized portion\n$keys = array_slice( $keys, 0, $max );\n\n//loop unnecessary, merge arrays\n$list = array_merge( $list, $keys );\n</code></pre>\n\n<p>Again, as I don't have 5.3 on this machine, the above example is untested and has not been profiled. Mostly I did this because I enjoy the mind stretch. If you understand what is going on here, find it easier to read, can reproduce it on your own, and it is more efficient, go ahead and use it; if not, you might want to stick to the loops for now. I hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T08:23:55.223", "Id": "26768", "Score": "0", "body": "great answer, thank you for the review i learned a bit :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T09:25:58.077", "Id": "26774", "Score": "0", "body": "Sorry i should mention, it wasn't that i didn't want index 0 it was that index 0 must be the first item present in the new list. I took your suggestions and refactored with that in mind and it looks a bit better now." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T17:08:18.797", "Id": "16412", "ParentId": "16387", "Score": "3" } } ]
{ "AcceptedAnswerId": "16412", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T06:08:52.037", "Id": "16387", "Score": "2", "Tags": [ "php" ], "Title": "PHP Random List" }
16387
<p>Gentlemen!</p> <p>I am hoping to find a more efficient (less hairy) way to do the following code. </p> <p>The public interface will call calculateListItemValue and pass the following variables</p> <ul> <li>$source_list: stdClass() with a structure similar to List JSON below.</li> <li>$target_list: stdClass() with a structure similar to List JSON below.</li> <li>$item_index: integer index pointing to the index of the array (list)->items[$item_index]</li> <li>$type: string value containing the controlling type $source_list->attribute->type to be compared to</li> </ul> <p>calculateListItemValue should check the value of attribute->value and calculate the final value of the operation based on range and operator</p> <ul> <li>If value >= 0 result should be positive</li> <li>If value &lt; 0 result should be negative</li> <li>If range is 0 apply Operator() to self</li> <li>If range is 4 apply Operator() to all items in source_list (or target_list if value &lt; 0)</li> <li>Else apply to items with attribut->attrNo == range</li> </ul> <p>Code follows.</p> <pre><code>/* List JSON example * { * "attributes": { * "operator": "+", * "value": "10", * "range": "2,3", * "type": "ATK", * "leader": true, * "attrNo": 2 * } * } * */ private function calculateListItemValue(&amp;$source_list, &amp;$target_list, $item_index, $type = 'ATK') { $power = array(); $operator = $source_list-&gt;items[$item_index]-&gt;attribute-&gt;operator; $value = intval($source_list-&gt;items[$item_index]-&gt;attribute-&gt;value); $leader = $source_list-&gt;items[$item_index]-&gt;attribute-&gt;leader ? 1 : .3; $item_type = $source_list-&gt;items[$item_index]-&gt;attribute-&gt;affect; $range = explode(',', $source_list-&gt;items[$item_index]-&gt;attribue-&gt;range); if($value &gt;= 0) { if(array_search('0', $range) !== false) { if($item_type == $type) { $power['power_up'] = $this-&gt;Operator($operator, ($type == 'ATK' ? $source_list-&gt;items[$item_index]-&gt;ATK : $source_list-&gt;items[$item_index]-&gt;DEF), $value, $leader); } } elseif(array_search('4', $range) !== false) { foreach($source_list-&gt;items as $item) { if($item_type == $type) { $power['power_up'] += $this-&gt;Operator($operator, ($type == 'ATK' ? $item-&gt;ATK : $item-&gt;DEF), $value, $leader); } } } else { foreach($source_list-&gt;items as $item) { if(isset($item-&gt;attribute-&gt;attrNo)) { if(array_search($item-&gt;attribute-&gt;attrNo, $range) !== false) { if($item_type == $type) { $power['power_up'] = $this-&gt;Operator($operator, ($type == 'ATK' ? $item-&gt;ATK : $item-&gt;DEF), $value, $leader); } } } } } } elseif($value &lt; 0) { if(array_search('0', $range) !== false) { return $power; } elseif(array_search('4', $range) !== false) { foreach($target_list-&gt;items as $item) { if($item_type == $type) { $power['power_down'] += $this-&gt;Operator($operator, ($type == 'ATK' ? $item-&gt;ATK : $item-&gt;DEF), $value, $leader); } } } else { foreach($target_list-&gt;items as $item) { if(isset($item-&gt;attribute-&gt;attrNo)) { if(array_search($item-&gt;attribute-&gt;attrNo, $range) !== false) { if($item_type == $type) { $power['power_down'] += $this-&gt;Operator($operator, ($type == 'ATK' ? $item-&gt;ATK : $item-&gt;DEF), $value, $leader); } } } } } } return $power; } private function Operator($operator, $base, $value, $mul) { $result = 0; if($operator == '*') { $result = abs(ceil(($base * ($value * $mul)) - $base)); } elseif($operator == '+') { $result = abs(ceil(($base + ($value * $mul)) - $base)); } return $result; } </code></pre> <p>Edit: Let me say that the code itself works fine, no problems.. but it's a nightmare to look at and explain to other people.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T07:21:21.970", "Id": "26710", "Score": "0", "body": "it is good to have algorithm along with the code, specifically when the code long." } ]
[ { "body": "<p>Well, first off, you should be wary of using referenced parameters. It sometimes makes legibility difficult, but in this case it is not even necessary. The method you are using these referenced variables in is private, therefore the class is the only thing that will ever use these values. Why not use properties instead? It accomplishes the same thing, is more legible, and is more extensible.</p>\n\n<pre><code>private\n $source_list,\n $target_list\n;\n\nprivate function calculateListItemValue( $item_index, $type = 'ATK' ) {\n $this-&gt;source_list;//do something to source list\n $this-&gt;target_list;//do something to target list\n //etc...\n}\n</code></pre>\n\n<p>Second, why is this method so long? Break this up into multiple methods based on functionality. If we follow the Single Responsibility Principle, then our methods should only do just enough to fulfill their purpose. No more, no less. Methods can call other methods to accomplish their task, but they should not need to know how those other methods do so.</p>\n\n<p>There are a lot of violations of the \"Don't Repeat Yourself\" (DRY) Principle. The following is a pretty basic example of it. You should also notice that I'm using type casting instead of <code>intval()</code>. This makes your code just a bit easier to read by removing the need to wrap the entire line in parenthesis.</p>\n\n<pre><code>$attribute = $source_list-&gt;items[ $item_index ]-&gt;attribute;\n$operator = $attribute-&gt;operator;\n$value = ( int ) $attribute-&gt;value;\n$leader = $attribute-&gt;leader ? 1 : .3;\n$item_type = $attribute-&gt;affect;\n</code></pre>\n\n<p>Why are you using <code>array_search()</code> here? <code>array_search()</code> returns the array key if found, FALSE otherwise. Because of this you are forced to explicitly check for FALSE. If that is all you want, why not use <code>in_array()</code> instead? It is cleaner because it only ever returns TRUE/FALSE. It's either found or it isn't. BTW: there is no need to treat \"0\" as a string. Just use the integer, PHP is loosely typed and will alow it.</p>\n\n<pre><code>if( in_array( 0, $range ) ) {\n //etc...\n}\n</code></pre>\n\n<p>Asides from those principles I've already mentioned, you are also violating the Arrow Anti-Pattern. By this I mean that your code is too heavily indented. The two principles I mentioned above will help. For instance, each if/else statement terminates in a final check (<code>$item_type == $type</code>). This could be done once, just before the first if statement and return early. This follows the DRY principle, helps the Arrow Anti-Pattern by removing a level of indentation across the entire method, and increases efficiency, meaning your program will run faster.</p>\n\n<pre><code>if( $item_type != $type ) {\n return $power;//empty array because nothing was done with it.\n}\n</code></pre>\n\n<p>Let's talk about ternary statements for a moment. Ternary is a very powerful tool, and is wonderful if used correctly. However, it quickly becomes a pain and makes your code illegible if used incorrectly. If you find that your statements become too long, then you should opt for a full if/else structure. If you find that you are opting for multiline ternary to make them more legible, then you should opt instead for a full if/else structure. If you find the statement too complex, making it difficult to read, then you should opt for the full if/else structure. So...</p>\n\n<pre><code>$power['power_up'] = $this-&gt;Operator($operator, ($type == 'ATK' ? $source_list-&gt;items[$item_index]-&gt;ATK : $source_list-&gt;items[$item_index]-&gt;DEF), $value, $leader);\n//compared to\nif( $type == 'ATK' ) {\n $power[ 'power_up' ] = $this-&gt;Operator( $operator, $source_list-&gt;items[ $item_index ]-&gt;ATK ), $value, $leader );\n} else {\n $power[ 'power_up' ] = $this-&gt;Operator( $operator, $source_list-&gt;items[ $item_index ]-&gt;DEF, $value, $leader );\n}\n</code></pre>\n\n<p>You should notice an immediate difference in how this looks. In the first example, that could easily be mistaken for multiple statements (or so it appeared in my editor), or mistaken for a really long single statement as the ternary is hard to spot. In the second you instantly know what's going on. Of course, you'll notice that the above is still violating the DRY principle and is still a little difficult to read. So let's modify it a little more.</p>\n\n<pre><code>$item = $source_list-&gt;items[ $item_index ];\nif( $type == 'ATK' ) {\n $power_up = $item-&gt;ATK;\n} else {\n $power_up = $item-&gt;DEF;\n}\n//or ternary now\n$power_up = $type == 'ATK' ? $item-&gt;ATK : $item-&gt;DEF;\n\n$power[ 'power_up' ] = $this-&gt;Operator( $operator, $power_up, $value, $leader );\n</code></pre>\n\n<p>There, much better. The rest of your code pretty much follows the same logic. All of it can benefit from the above suggestions, so I will stop here and allow you to do the rest. If you need any clarification, let me know.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T08:24:38.127", "Id": "26769", "Score": "0", "body": "Thanks for reviewing both of my submissions, they are really informative and helped me out quite a bit to change my approach to problems." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T15:09:19.010", "Id": "16409", "ParentId": "16388", "Score": "1" } } ]
{ "AcceptedAnswerId": "16409", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T06:42:20.417", "Id": "16388", "Score": "4", "Tags": [ "php" ], "Title": "PHP List Iteration" }
16388
<p>Here's a bit of one of my web forms which is reached by clicking on a link in a calendar. Based on what you click, you end up at this page with a different <code>QueryString</code>. Based on that <code>QueryString</code>, we hide/show and enable/disable controls related to actions associated with the <code>QueryString</code>, as well as the role of user.</p> <p>We have three different types of events:</p> <ul> <li><code>VacationDays</code> (days where people took paid vacation)</li> <li><code>VacationDaysUnpaid</code> (days where people took unpaid vacation)</li> <li><code>CalendarEvents</code> (everything else such as meetings and client visits)</li> </ul> <p>Here's a slimmed down version of how the page is prepared:</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { InitializePage(); } } private void InitializePage() { CheckRoles(); if (!String.IsNullOrEmpty(Request.QueryString["CalendarEventID"])) { if (!HttpContext.Current.User.IsInRole("Guest")) { //if this is just a regular calendar event, allow non-guests to edit btnedit.Enabled = true; btndelete.Visible = false; } } if (!String.IsNullOrEmpty(Request.QueryString["VacationDayID"])) { if (!HttpContext.Current.User.IsInRole("Guest")) { //for vacation days, edits are not allowed, but the ability to delete is btnedit.Visible = false; btndelete.Enabled = true; btndelete.Visible = true; } } if (!String.IsNullOrEmpty(Request.QueryString["VacationDayUnpaidID"])) { //unpaid vacation days can only be deleted by administrators if (HttpContext.Current.User.Identity.Name.ToString().ToLower() == "administrator") { btndelete.Visible = true; } else { btndelete.Visible = false; } } } private void CheckRoles() { if (HttpContext.Current.User.IsInRole("Guest")) { //disable all write controls if guest btnedit.Visible = false; btndelete.Visible = false; btnsave.Visible = false; } } </code></pre> <p>It's jumbled, it's confusing, and it's difficult to maintain. Is there any kind of common design or plan of attack for doing what I'm trying to do here? I mean this works, I can work with it, I guess, but I really feel like there must just be some technique that I don't know about which will help improve this into something much easier and manageable.</p> <p>One idea that I'm considering, and that I know will work, is to separate the code related to the different types of events into separate files as "partial"</p> <p>That way in my <code>InitializePage()</code> method, for each type of <code>QueryString</code>, I'll have code that says like <code>EnableCalendarEventMode()</code>, which would be located in the partial class and would contain all the code related to calendar events. This idea will make it easier to manage for me personally, but it still doesn't change the code, it just moves it around.</p>
[]
[ { "body": "<p>For one thing, everything is just setting booleans. Condense down all those nested <code>if</code> blocks down into boolean statements and use good names, and it'll even make sense in \"plain English\".</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e) {\n if (IsPostBack) return;\n Func&lt;string, bool&gt; QueryStrHas = key =&gt; !String.IsNullOrEmpty(Request.QueryString[key]);\n var isCalEvent = QueryStrHas(\"CalendarEventID\");\n var isVacDay = QueryStrHas(\"VacationDayID\");\n var isUnpaidVac = QueryStrHas(\"VacationDayUnpaidID\");\n\n var user = HttpContext.Current.User;\n var isGuest = user.IsInRole(\"Guest\");\n var isAdmin = user.Identity.Name.ToString().ToLower() == \"administrator\";\n\n // guests cannot edit\n // non-guests can edit regular calendar events, but not vacation days\n // non-guests can delete vacation days\n // unpaid vacation days can only be deleted by administrators\n btnedit.Enabled = !isGuest &amp;&amp; isCalEvent &amp;&amp; !isVacDay;\n btndelete.Enabled = !isGuest &amp;&amp; isVacDay;\n btndelete.Visible = !isGuest &amp;&amp;\n (isVacDay||\n (isAdmin &amp;&amp; isUnpaidVac));\n}\n</code></pre>\n\n<p>Make sure you double-check the boolean arithmetic by testing it though. There're some missing cases (kind of), and you should make sure it's all well-defined.</p>\n\n<p>Oh, by the way, just cosmetically \"hiding\" the btnedit when a user isn't an Admin does not count for true security. Anybody can actually modify all these values when it reaches their browser client-side.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T00:03:08.973", "Id": "26763", "Score": "0", "body": "Ooo, great answer. Thanks for that. Can you briefly explain how I would be able to make a page *actually* secure, not just hiding the button? The design request is that the user can still access the page and see stuff if Guest, so just shutting out the whole page is no good. I'm guessing I need to add something in the button click event that checks once again to make sure you actually have the right role, and if not, do not proceed with the execution/saving. Something along those lines?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T00:57:57.010", "Id": "26764", "Score": "0", "body": "Just don't rely on the client-side buttons for security. Someone who's not authorized could write their own html/javascript and tell the server that he pressed the button. The server needs to be able to determine whether or not the user clicking is allowed to execute the command. If you do that check in the ASP.net `button.click` event handler, you should be fine." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T16:23:34.130", "Id": "16443", "ParentId": "16391", "Score": "3" } }, { "body": "<p>Here's an alternative to the approved answer that provides a different perspective. I try to write self-documenting code so the next developer can understand it without have to think about it. I believe this code achieves that goal. It does end up being more code but when the requirements change it will be easy to make changes to this code.</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n if (!IsPostBack)\n InitializePage();\n}\n\nprivate void InitializePage()\n{\n CheckRoles();\n CheckCalendarEvent();\n CheckVacationDay();\n CheckVacationDayUnpaid();\n}\n\nprivate void CheckRoles()\n{\n if (IsGuest())\n {\n //disable all write controls if guest\n btnedit.Visible = false;\n btndelete.Visible = false;\n btnsave.Visible = false;\n }\n}\n\nprivate void CheckCalendarEvent()\n{\n if (ParameterExists(\"CalendarEventID\") &amp;&amp; !IsGuest())\n {\n //if this is just a regular calendar event, allow non-guests to edit\n btnedit.Enabled = true;\n btndelete.Visible = false;\n }\n}\n\nprivate void CheckVacationDay()\n{\n if (ParameterExists(\"VacationDayID\") &amp;&amp; !IsGuest())\n {\n //for vacation days, edits are not allowed, but the ability to delete is\n btnedit.Visible = false;\n btndelete.Enabled = true;\n btndelete.Visible = true;\n }\n}\n\nprivate void CheckVacationDayUnpaid()\n{\n //unpaid vacation days can only be deleted by administrators\n btndelete.Visible = ParameterExists(\"VacationDayUnpaidID\") &amp;&amp; IsAdministrator();\n}\n\nprivate bool IsGuest()\n{\n return HttpContext.Current.User.IsInRole(\"Guest\");\n}\n\nprivate bool IsAdminstrator()\n{\n return HttpContext.Current.User.Identity.Name.ToString().ToLower() == \"administrator\";\n}\n\nprivate bool ParameterExists(string p)\n{\n return !String.IsNullOrEmpty(Request.QueryString[p]);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-26T17:04:48.257", "Id": "17967", "ParentId": "16391", "Score": "0" } } ]
{ "AcceptedAnswerId": "16443", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T07:25:42.977", "Id": "16391", "Score": "2", "Tags": [ "c#", "asp.net", "http" ], "Title": "Calendar events based on user feedback" }
16391
<p>What is your opinion on method ordering?</p> <p>Should it be public methods at the top followed by private methods?</p> <p>or</p> <p>Should it be linear order so that methods calling methods stack on top of each other?</p> <p><strong>Which do you think is better for maintainability / readability?</strong></p> <p>Examples</p> <p><strong>Public first:</strong></p> <pre><code>public class Main { @Override public void onCreate(Bundle savedInstanceState) { // } @Override protected void onResume() { startUploadActivity(); } @FromXML public void onSignInClick(View button){ startAuthorisationForYouTube(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultIsASignInAttempt(requestCode) &amp;&amp; signedInSucccessfully(resultCode)){ dealWithResult(data); } else if(resultIsASignInAttempt(requestCode) &amp;&amp; signInFailed(resultCode)){ startRefusalActivity(); } } @Override protected void onStop() { super.onStop(); } private void startUploadActivity() { // } private void startAuthorisationForYouTube() { // } private static boolean resultIsASignInAttempt(int requestCode) { // } private static boolean signedInSucccessfully(int resultCode) { // } private static boolean signInFailed(int resultCode) { // } private void dealWithResult(Intent data) { // } private static Tokens getAccessTokens(Intent data) { // } private void startRefusalActivity() { // } } </code></pre> <p><strong>Calling order:</strong></p> <pre><code>public class Main { @Override public void onCreate(Bundle savedInstanceState) { // } @Override protected void onResume() { startUploadActivity(); } private void startUploadActivity() { // } @FromXML public void onSignInClick(View button){ startAuthorisationForYouTube(); } private void startAuthorisationForYouTube() { // } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultIsASignInAttempt(requestCode) &amp;&amp; signedInSucccessfully(resultCode)){ dealWithResult(data); } else if(resultIsASignInAttempt(requestCode) &amp;&amp; signInFailed(resultCode)){ startRefusalActivity(); } } private static boolean resultIsASignInAttempt(int requestCode) { // } private static boolean signedInSucccessfully(int resultCode) { // } private static boolean signInFailed(int resultCode) { // } private void dealWithResult(Intent data) { // } private static Tokens getAccessTokens(Intent data) { // } private void startRefusalActivity() { // } @Override protected void onStop() { super.onStop(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T19:20:18.337", "Id": "26708", "Score": "0", "body": "I think this is slightly off topic but on a personal note, I tend to group my methods by public, private, protected regions. But everyone's different and probably comes down to the accepted standards of the project TBH." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T20:13:21.440", "Id": "26713", "Score": "1", "body": "Yeah so if I start the project I choose the standard :-) I don't see why this was closed as not constructive :-/ clearly those people don't have enough OCD over their code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T07:41:41.347", "Id": "26729", "Score": "0", "body": "haha I agree, I am also pretty OCD about code beauty" } ]
[ { "body": "<p>I don't have strong feelings, but I keep methods in calling order. The argument for \"public up top\" seems to be that someone wants to see what methods they can call on an Object as opposed to what a particular method does. However in today's world, this is generally accomplished by an IDE or javadoc. If that's not possible, the time lost jumping through a file looking for the public methods is minimal.</p>\n\n<p>When I'm looking at code for a class I haven't written, I'm inevitably trying to find out how it works. And when reading the content of a method, jumping to private methods becomes more important, and slightly more time is lost if the class isn't ordered for callability.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T18:37:12.333", "Id": "16417", "ParentId": "16395", "Score": "1" } } ]
{ "AcceptedAnswerId": "16417", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T10:21:32.763", "Id": "16395", "Score": "0", "Tags": [ "java" ], "Title": "Method Ordering - Readability / Maintainability" }
16395
<p>I have a node template that grabs fields from a content type.</p> <p>In the node--[contenttype].tpl.php file I have two sections (The second is html/php and grabs variables from the first section or from the content type and simply displayed it). The first is strictly php and does three things:</p> <ol> <li>Grabs numbers from one of the content type fields and rearranges them according to some criteria. Setting this output as a variable to be used later in the page.</li> <li>Grabs two taxonomy terms and sets them as variables to be used later in the page. Also compares these variables to an array as the key in order to set the value as another variable to be used later in the page.</li> <li>Creates a function for converting stdClass Objects to Arrays and uses it in one of the above two actions.</li> </ol> <p>My question is, should this php even go in the node--[contenttype].tpl.php file? The numbers output and taxonomy output is only ever going to be used in this node (the arrays set for comparison are only relevant with this content type), but the Class function could be used on other pages.</p> <p>I'm not getting how I can leverage the Drupal system in order to get a strong and easily upgradable code base (for going to Drupal 8 in the future).</p> <p>How should my mind be processing executable challenges. Should I be asking certain questions in order to determine if something goes into template.php, into a new module, or where its css goes? Should all that css be going into style.css? Can I break it out somehow?</p> <p>EDIT: Here is my code for node--[contenttype].tpl.php </p> <pre><code>&lt;?php /////**** set link and text for Category and Location section ****//////// $category_to_nid = array( "Professional Development" =&gt; 34, "Curriculum" =&gt; 35, "Study Labs" =&gt; 36, "Stage Performances" =&gt; 37, ); $location_to_nid = array( "Visit Examples" =&gt; 38, "We Come To You" =&gt; 39); // to array (from stdClass object) // for field_location_category to get name // without it, get white screen of death because ['taxonomy_term'] is an object not array // Credit: http://www.if-not-true-then-false.com/2009/php-tip-convert-stdclass-object-to-multidimensional-array-and-convert-multidimensional-array-to-stdclass-object/ function objectToArray($d) { if (is_object($d)) { // Gets the properties of the given object // with get_object_vars function $d = get_object_vars($d); } if (is_array($d)) { /* * Return array converted to object * Using __FUNCTION__ (Magic constant) * for recursive call */ return array_map(__FUNCTION__, $d); } else { // Return array return $d; } } $location_text_array = objectToArray($node-&gt;field_location_category['und'][0]['taxonomy_term']); $location_text = $location_text_array['name']; $category_text_array = objectToArray($node-&gt;field_location_category['und'][1]['taxonomy_term']); $category_text = $category_text_array['name']; $location_link = "http://www.server.com/node/" . $location_to_nid[$location_text]; $category_link = "http://www.server.com/node/" . $category_to_nid[$category_text]; /////**** Check if new category or location ****/////// $display_category_tab = TRUE; $display_location_tab = TRUE; if ($category_text != $category_text_previous){ $display_category_tab = TRUE; } else{ $display_category_tab = FALSE;} if ($location_text != $location_text_previous){ $display_location_tab = TRUE; } else{ $display_location_tab = FALSE;} /*print $location_text . "&lt;br /&gt;"; print $location_text_previous . "&lt;br /&gt;"; print $category_text . "&lt;br /&gt;"; print $category_text_previous . "&lt;br /&gt;"; if($display_location_tab){print "Location TAB" . "&lt;br /&gt;";} if($display_category_tab){print "Category TAB" . "&lt;br /&gt;";} */ $location_text_previous = $location_text; $category_text_previous = $category_text; /////**** set Taxonomy Term Color ****/////// $color_category_array = array( 196 =&gt; "orange", // "Inspiration for Users" 177 =&gt; "green", // "Visit Examples" 178 =&gt; "blue", // "We Come to You" 197 =&gt; "red", // "Content for Homeschoolers" 198 =&gt; "grey" // "School Partnerships" ); $tid_array = array(); for ($i=0; $i &lt; count($node-&gt;field_location_category['und']); $i++): $tid_array[] = $node-&gt;field_location_category['und'][$i]['tid']; endfor; $taxonomy_terms = array_intersect($tid_array, array(196, 177, 178, 197, 198)); $taxonomy_color_class = $color_category_array[$taxonomy_terms[0]]; // Use the following for setting class for color: $color_category_array[$taxonomy_term]; /////**** set Grades $display variable ****/////// if(!empty($content['field_grades'])): // Grab Grades string and create into array // note: because not able to grab as array $grades_string = render($content['field_grades']); $grades_string = str_replace("Adult", "13", $grades_string); $grades_string = str_replace("K", "00", $grades_string); $new_grades_array = str_split($grades_string, 2); // loop for creating $display string based on consecutives for ($i = 0; $i &lt; count($new_grades_array); $i++): // set grade digit for K and Adult switch ($new_grades_array[$i]): case "K": $currentgrade_dig = 0; break; case "Adult": $currentgrade_dig = 13; break; default: $currentgrade_dig = $new_grades_array[$i]; endswitch; // concatenates string to display variable based on situation if ($i == 0): // if the first grade listed $display = $new_grades_array[$i]; elseif ($i +1 == count($new_grades_array)): //if the last grade listed if ($currentgrade_dig - $last ==1): $display .= " - " . $new_grades_array[$i]; else: if ($conseq != FALSE): $display .= " - " . $last . ", " . $new_grades_array[$i]; else: $display .= ", " . $new_grades_array[$i]; endif; endif; $conseq = FALSE; elseif ($currentgrade_dig - $last ==1): // if consecutive number from previous $conseq = TRUE; else: // if not a consecutive number if ($conseq != FALSE): $display .= " - " . $last . ", " . $new_grades_array[$i]; $conseq = FALSE; else: $display .= ", " . $new_grades_array[$i]; endif; endif; $last = $new_grades_array[$i]; endfor; $display = str_replace("13", "Adult", $display); $display = str_replace("00", "K", $display); $display = str_replace(" 0", " ", $display); if($display[0]=="0"): $display = substr($display, 1, strlen($display)); endif; $display = "Grades " . $display; else: $display = "All Ages"; endif; ?&gt; &lt;?php /** * &lt;div id="node-&lt;?php print $node-&gt;nid; ?&gt;" class="&lt;?php print $classes; ?&gt; block_1_column clearfix"&lt;?php print $attributes; ?&gt;&gt; */ // Check if published if($content['body']['#object']-&gt;status || $user-&gt;uid &gt; 0): ?&gt; &lt;!--&lt;?php if(isset($content['field_3column_name'])): ?&gt; &lt;h2 class="title-main"&gt;&lt;?php print render($content['field_3column_name']); ?&gt;&lt;/h2&gt; &lt;?php endif; ?&gt;--&gt; &lt;div &lt;?php if(!isset($content['field_3column_icons'])): ?&gt;class="no-icons"&lt;?php endif; ?&gt;&gt; &lt;div class="query-item"&gt; &lt;div class="query-title big_header_dark-red query-&lt;?php print $taxonomy_color_class; ?&gt;"&gt;&lt;?php print $title; ?&gt;&lt;/div&gt; &lt;div class="query-where"&gt; &lt;a href="&lt;?php print $location_link; ?&gt;" class=""&gt;&lt;?php print $location_text; ?&gt;&lt;/a&gt; &amp;nbsp;&gt;&amp;nbsp; &lt;a href="&lt;?php print $category_link; ?&gt;" class=""&gt;&lt;?php print $category_text; ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="query-basics-group"&gt; &lt;span&gt;&lt;?php print $display; ?&gt;&lt;/span&gt; &lt;?php if(!empty($content['field_duration'])): ?&gt;&lt;span&gt;&lt;?php print render($content['field_duration']); ?&gt;&lt;/span&gt;&lt;?php endif; ?&gt; &lt;?php if(!empty($content['field_capacity'])): ?&gt;&lt;span&gt;&lt;?php print render($content['field_capacity']); ?&gt;&lt;/span&gt;&lt;?php endif; ?&gt; &lt;?php if(!empty($content['field_availability'])): ?&gt;&lt;span&gt;&lt;?php print render($content['field_availability']); ?&gt;&lt;/span&gt;&lt;?php endif; ?&gt; &lt;/div&gt; &lt;?php if(isset($content['field_cost']) || isset($content['field_subject_area']) || isset($content['field_note'])): ?&gt; &lt;div class="query-basics-group"&gt; &lt;?php if(!empty($content['field_cost'])): ?&gt;&lt;span&gt;&lt;?php print render($content['field_cost']); ?&gt;&lt;/span&gt;&lt;?php endif; ?&gt; &lt;?php if(!empty($content['field_subject_area'])): ?&gt;&lt;span&gt;&lt;?php print render($content['field_subject_area']); ?&gt;&lt;/span&gt;&lt;?php endif; ?&gt; &lt;?php if(!empty($content['field_note'])): ?&gt;&lt;span&gt;&lt;?php print render($content['field_note']); ?&gt;&lt;/span&gt;&lt;?php endif; ?&gt; &lt;/div&gt;&lt;?php endif; ?&gt; &lt;div class="query-description"&gt;&lt;?php // render(field_view_filed()); instead of just render($content['body']); kept the WYSIWYG formatting print render(field_view_field('node', $node, 'body')); ?&gt; &lt;/div&gt; &lt;?php if(!empty($content['field_register_link'])): ?&gt; &lt;div class="query-link"&gt;&lt;?php // render(field_view_filed()); instead of just render(); kept the WYSIWYG formatting print render($content['field_register_link']); ?&gt; &lt;/div&gt;&lt;?php endif; ?&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;?php if(isset($content['field_gallery'])): ?&gt; &lt;?php print render($content['field_gallery']); ?&gt; &lt;?php endif; ?&gt; &lt;?php if(isset($content['field_3column_icons'])): ?&gt; &lt;div class="icons"&gt;&lt;div class="icons-highlight"&gt;&lt;?php print render($content['field_3column_icons']); ?&gt;&lt;/div&gt;&lt;/div&gt; &lt;?php endif; ?&gt; &lt;?php else: endif; //dsm("Charity:&lt;pre&gt;" . print_r($content['field_location_category'], TRUE) . '&lt;/pre&gt;'); //dsm("Charity:&lt;pre&gt;" . print_r($taxonomy_terms, TRUE) . '&lt;/pre&gt;'); ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T13:53:14.047", "Id": "26684", "Score": "0", "body": "According to the FAQ, you should include any pertinent code. If, as this question appears, your question is not about code, or is an abstract question about how best to do something, then it should be on Programmers.SE instead." } ]
[ { "body": "<p>I can't speak specifically to Drupal as I have never used it before. But the following should be helpful in any situation. In order to best answer your specific questions I'm going to have to go through this line by line, which means I need to decipher your code first. Since I'm having to do so anyways, I figured I'd share the results as a review, after all, this is code review.</p>\n\n<p><strong>Style</strong></p>\n\n<p>Be consistent with your style/code. You have two arrays at the very beginning, both are styled slightly differently. Either method is fine, but you should stick to one or the other. Mixing styles makes it appear to be copy-pasted together.</p>\n\n<p><strong>Arrays and Constants</strong></p>\n\n<p>I would have to ask what these arrays are for that they are sequentially ordered in this way. Skimming the rest of this document I see that these arrays are only used once, and are used in such a way that they can be combined. Honestly I think these should actually be refactored into constants, but I can't really see how to do this to demonstrate. However, combining them definitely wont hurt.</p>\n\n<pre><code>$category_to_nid = array(\n \"Professional Development\" =&gt; 34,\n \"Curriculum\" =&gt; 35,\n \"Study Labs\" =&gt; 36,\n \"Stage Performances\" =&gt; 37,\n \"Visit Examples\" =&gt; 38,\n \"We Come To You\" =&gt; 39\n);\n</code></pre>\n\n<p><strong>Comments</strong></p>\n\n<p>Now, I kind of skipped over the first thing I wanted to cover, but let me return to it now. There are three different kinds of comments. Your single line comments <code>//single line comment</code>, your multi-line comments <code>/* multi-line comment */</code>, and finally your doccomments <code>/** doccomment */</code>. While this doesn't really effect performance, it does help with legibility when you use them properly.</p>\n\n<pre><code>//set link and text for Category and Location section\n\n/*\nto array (from stdClass object)\nfor field_location_category to get name\netc...\n*/\n</code></pre>\n\n<p><strong>Adopted Code</strong></p>\n\n<p>Its good to give credit to borrowed code, especially when trying to look it up later, but don't just copy-paste it in. Take the time to manually type it into your own code, and tweak it to your own style and habits while you are at it. This ensures seamless integration and will help you, if not understand it, to at least know its inner workings better. For instance, you use very descriptive names for all of your variables, but in that function you use a very vague variable. In fact, it is just good practice to be descriptive anyways. This makes your code self documenting, making many of these comments unnecessary.</p>\n\n<p><strong>Don't Repeat Yourself</strong></p>\n\n<p>There is a principle called \"Don't Repeat Yourself\" (DRY). As the name implies, you should do your best to make sure your code is not repetitive. Sometimes this means using loops, sometimes variables, and usually it means using functions. But to fully benefit from this principle you should use them all. I'm not going to discuss each method here, but you should definitely take a look at this principle more in depth. Specifically I want to look at variables here. Variables help make your code DRY by ensuring you don't have to type the same sequences repeatedly. This also reduces the line length of your code, for example:</p>\n\n<pre><code>$und = $node-&gt;field_location_category[ 'und' ];\n$location_text_array = objectToArray( $und[ 0 ] [ 'taxonomy_term' ] );\n\n//AND\n\n$address = 'http://www.server.com/node/';\n$location_lin = $address . $location_to_nid[ $location_text ];\n</code></pre>\n\n<p>This has the added benefit of making your code easier to edit. Imagine your URL changed. You would then have to update that URL everywhere. Sure, you can use the find/replace tool, but only having to do it once ensures that nothing is accidentally missed AND it makes your code smaller.</p>\n\n<p><strong>Conditions</strong></p>\n\n<p>So a neat little trick here. If you have a variable you want to set to TRUE/FALSE, based on the outcome of a condition, you can just pass that condition to the variable for the same results, for example:</p>\n\n<pre><code>$display_category_tab = $category_text != $category_text_previous;\n</code></pre>\n\n<p>However, while this is a neat trick, it is unnecessary in this context, because the variables are unnecessary. You only use these variables once. So instead of performing the same expression twice, just use those conditions once, when you actually need them.</p>\n\n<pre><code>if( $category_text != $category_text_previous ) {\n print \"Category TAB\" . \"&lt;br /&gt;\";\n}\n</code></pre>\n\n<p><strong>Echo vs Print</strong></p>\n\n<p>This is a matter of preference, but typically you see <code>echo</code> being used over <code>print</code>. Both are just fine, but <code>echo</code> seems to be a smidge faster, which I guess is the reason its more widely used. Otherwise there is no difference, at least that I know of.</p>\n\n<p><strong>Alternative Syntax</strong></p>\n\n<p>Every statement/loop has an alternate syntax that is used in templating. This alternate syntax uses a colon instead of the opening brace, and an <code>endXXX</code> instead of the closing brace. As I said, this syntax is used in templating, so seeing it in a the middle of a PHP block is jarring. I would use the traditional syntax instead.</p>\n\n<pre><code>$count = count( $und );\nfor( $i = 0; $i &lt; $count; $i++ ) {\n $tid_array[] = $und[ $i ] [ 'tid' ];\n}\n</code></pre>\n\n<p>You may notice that I abstracted the count from the loop in the code above. For and while loops call any functions passed into their parameter lists on each iteration, therefore <code>count()</code> is being called each time. This is pretty common and is sometimes overlooked, but it is still good practice to abstract it with a variable. Besides, it also makes the code more legible when using long statements.</p>\n\n<p>Another change you may have noticed was that I am continuing to use that variable I abstracted at the beginning, this makes the code so much shorter, and as a result much easier to read.</p>\n\n<p><strong>Final Notes</strong></p>\n\n<p>I'm not sure what <code>render()</code> does, but if it does what I think it does (converts an array to a string), then you can probably use array functions instead. Without knowing for sure, and not wanting to confuse you, I don't really want to tackle this.</p>\n\n<p>Definitely take a look at incorporating functions. The rest of your code, from where I left off above, could definitely benefit from it.</p>\n\n<p><strong>should this php even go in the node--[contenttype].tpl.php file?</strong></p>\n\n<p>I would say no. Just because of the size and complexity. Honestly this looks like this could be split into multiple pages, thus adopting a framework, such as MVC, would definitely be a possibility.</p>\n\n<p><strong>I'm not getting how I can leverage the Drupal system in order to get a strong and easily upgradable code base (for going to Drupal 8 in the future).</strong></p>\n\n<p>Some of the above suggestions should help. Again, I can't help you specifically with Drupal, but it should help you get started. Having a better understanding of the basics will always help.</p>\n\n<p><strong>How should my mind be processing executable challenges. Should I be asking certain questions in order to determine if something goes into template.php, into a new module, or where its css goes? Should all that css be going into style.css? Can I break it out somehow?</strong></p>\n\n<p>I'm not entirely sure what you are asking for here. It is always best to have styles and javascripts outside of the HTML. It is also sometimes helpful to have PHP external as well, but this really only makes a difference in larger systems. Having these separated makes it easier to reuse. If you are changing the files based on conditions in the PHP, you might want to consider using multiple pages (Professional Development, Curriculum, etc...) and possibly even a framework.</p>\n\n<p>I hope this helps</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T21:38:31.883", "Id": "26715", "Score": "0", "body": "That is a beautiful review/answer giving me a lot of food for thought (Yay!). I'm going to have to go through this and let you know if I have any questions. Thank you for attacking this from a programming basics perspective. I feel like I understand the words, grammar, and sentence structure but am not able to \"speak\" eloquently and this will help!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T21:43:13.220", "Id": "26716", "Score": "0", "body": "So one question: I set these: $display_category_tab = TRUE;\n$display_location_tab = TRUE; outside of the loop so then I can use them outside of the loop, but now that you mention it, variables are \"trapped\" only inside functions and not loops, correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T13:14:02.293", "Id": "26743", "Score": "1", "body": "@SweetTomato: I'm not sure why this question was closed. Initially this seemed off topic, but with the code its better now. As to your question, you are correct, though defining a variable before using it in a loop is still good practice. For instance, if you try to append to an undefined variable from a loop you will get warnings and might accidentally be accessing a string instead. Or, if the array you are looping over is empty, it will just be skipped, meaning the variable wont get defined. So a default value is still a good thing to have." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-13T03:53:02.890", "Id": "31312", "Score": "0", "body": "@mseancole I'm not sure why this was closed either. I've voted to re-open." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T21:05:52.657", "Id": "16419", "ParentId": "16398", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T11:05:28.480", "Id": "16398", "Score": "3", "Tags": [ "php", "drupal" ], "Title": "Drupal: Placing Code (PHP) within the Drupal System (as well as css)" }
16398
<p>I'm using twitter mobile and I have a login-dialog. login-Dialog is a modal dialog. To call it the user calls <code>loginDialog.show();</code></p> <p>I'm not all that comfortable with the coding style I've adopted (i'm very much self schooled in JavaScript) and I'd be interested to hear peoples opinions on the code structure and process handling. For example I always seem to use expressive functions instead of function declarations. (some of the nitty gritty is ommitted for focus). </p> <pre><code>var loginDialog = (function($) { /** * Essentially the init function */ var show = function() { // This actually shows the dialog $("#login-dialog").modal({backdrop: "static", keyboard: false}); applyBindings(); } var hide = function() { $("#login-dialog").modal("hide"); } var applyBindings = function() { $("#login-dialog .btn-primary").click(onLoginClick); }; var onLoginClick = function() { // validate form, attempt login... // logginIn is a jQuery Deferred. var loggingIn = myApi.login(username, password); loggingIn.done( handleResponse ); loggingIn.fail( handleError ); }; var validate = function(username, password) { // simple form validation }; var handleResponse = function(json) { // check json psuedo code if (json != "Ok") { handleError(); } else { handleSuccess(); } }; var handleError = function(msg) { msg = msg || "There was a problem communicating with the server"; var tmpl = _.template($("#alert-tmpl").html(), { head: "Error", body: msg}); $("#login-dialog form").append(tmpl); $("#login-dialog .btn-primary").removeAttr("disabled"); }; var handleSuccess = function() { hide(); }; return { show: show, hide: hide } })(jQuery); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T13:47:14.673", "Id": "26682", "Score": "0", "body": "Can't recommend using \"brace on new line\" in JavaScript. JS interpreters will insert a semicolon at the end of a line, if it \"thinks\" it's missing. I see you don't have a newline between your final `return` and the following brace - if you did, the function would always return `undefined`. You probably know this, which is why you wrote it. Trouble is that the style then becomes inconsistent. But it's your call; just know that style can cause bugs in JS. Speaking of consistency, you might want to add some semis after the function declarations. There's one after `applyBindings` but it's random." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T14:06:27.370", "Id": "26685", "Score": "0", "body": "@Flambino. Your right my semi-colons are sloppy after functions and I do agree with you about the braces (but sadly this is just about the only convention I MUST follow at work). My real concern is the process, the way the dialog is wrapped and whether I should be using expressive functions or function declarations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T14:09:45.573", "Id": "26686", "Score": "0", "body": "Of course, just thought I'd mention it. You should really have a talk with your bosses, though, if they're forcing you to use brace-on-new-line in one of the few languages where it _can_ have serious side-effects, and isn't just a religious debate :)" } ]
[ { "body": "<p>First off, I'd retrieve all the elements right away, instead of running <code>$(...)</code> again and again:</p>\n\n<pre><code>var loginDialog = (function($) {\n var dialog, form, button, template;\n\n // Get the elements once, on page load\n $(function () {\n dialog = $(\"#login-dialog\");\n form = dialog.find(\"form\");\n button = dialog.find(\".btn-primary\");\n template = $(\"#alert-tmpl\");\n });\n\n function show() {\n dialog.modal({\n backdrop: \"static\",\n keyboard: false\n });\n }\n\n // ... et cetera ...\n\n})(jQuery);\n</code></pre>\n\n<p>As you can see, I've also put the variable declaration first. If you use expressive functions, you should do the same with all those variables too (which is why I usually prefer to use standard function declarations instead - fewer variables to declare).</p>\n\n<p>(oh, and, yes, I've moved the braces around, but we've covered that in the comments :)</p>\n\n<p>Generally, though, it seems quite fine, and well-structured. There are some functions that could be dropped, since they just call a different function - for instance <code>handleSuccess</code> which is basically an alias for <code>hide</code>. On the other hand it's nicely descriptive to have a <code>handleSuccess</code> function. And if you want to more on success than simply call <code>hide</code>, it's of course nice to have encapsulated.</p>\n\n<p>Lastly, in <code>handleError</code> you <code>.append</code> the error message to the form, so if there are more errors the form will keep growing. Don't know if that's by design, but I imagine you might want to only show one error at a time (and perhaps even remove it on success).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T14:23:32.140", "Id": "16402", "ParentId": "16399", "Score": "1" } } ]
{ "AcceptedAnswerId": "16402", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T11:13:38.057", "Id": "16399", "Score": "4", "Tags": [ "javascript", "jquery", "controller" ], "Title": "Code structure for a login modal dialog." }
16399
<p>As I was working with .NET, I started wondering how I would implement the LINQ methods syntax in Javascript. So here is my first try; is there a more elegant, or more performant, way to write this code?</p> <pre><code>// usage : the functions take a predicate function as input and modify the array accordingly var collection; (function() { "use strict"; var Collections = function(array) { this.array = array; }; Collections.prototype = { //The predicate should return a boolean value //Keeps all elements that match the given function where: function(predicate) { var newArray = []; this.each(function(index, item) { if (predicate(item)) { newArray.push(item); } }); this.array = newArray; return this; }, //The predicate should return a boolean value //Returns true if one element or more matches the predicate any: function(predicate) { var newArray = []; this.each(function(index, item) { if (predicate(item)) { newArray.push(item); } }); return newArray.length &gt; 0; }, //The predicate should return an object //Replaces all elements by the object generated by the predicate select: function(predicate) { var newArray = []; this.each(function(index, item) { newArray.push(predicate(item)); }); this.array = newArray; return this; }, //Returns the current (modified) array getArray: function() { return this.array; } }; collection = function(array) { return new Collections(array); }; } ()); </code></pre> <p>And here is an exemple of use:</p> <pre><code>var myArray = [{name: 'chicken', size: 1}, {name: 'cat', size: 2}, {name: 'dog', size: 3}, {name: 'horse', size: 4}, {name: 'skunk', size: 2}]; var newArray = collection(myArray) .where(function(animal){ return animal.size == 2 }) .select(function(animal){ return { animalName: animal.name, category: 'mammal', size: 'small' } }) .getArray() // new array : [{animalName: 'cat', category: 'mammal', size: 'small}, {animalName: 'skunk', // category: 'mammal', size: 'small'}] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T11:55:27.403", "Id": "26670", "Score": "0", "body": "So you're rewriting [underscore.js](http://underscorejs.org/)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T12:07:15.573", "Id": "26672", "Score": "0", "body": "Not the whole library obviously. I just wanted to work on something small to experiment with the code and try to improve my code style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T12:11:17.977", "Id": "26674", "Score": "0", "body": "Absolutely nothing wrong with that. Just keeping you from rewriting an existing library from scratch. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T14:42:02.553", "Id": "26687", "Score": "0", "body": "Why is Collections in plural? It is more common to find constructor names in singular (Array, String, Object)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T15:08:25.330", "Id": "26690", "Score": "0", "body": "@Eric: Good point, I didn't think about that. Neil: thank you then !" } ]
[ { "body": "<p>To clarify the use of your global variable \"collection\" as a namespace for your library, you should assign it directly to a value returned by your Immediately Invoked Function Expression:</p>\n\n<pre><code>var collection = (function(){\n ...\n\n function collection(array) {\n return new Collections(array);\n }\n\n return collection;\n}());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T15:08:54.893", "Id": "26691", "Score": "0", "body": "Alright, it does seem clearer that way." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T14:39:40.840", "Id": "16404", "ParentId": "16400", "Score": "2" } } ]
{ "AcceptedAnswerId": "16404", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T11:47:18.120", "Id": "16400", "Score": "4", "Tags": [ "javascript", "optimization", "library" ], "Title": "Code review for a collection manipulation tool in Javascript" }
16400
<p>I have just created my first jQuery plugin. I am looking to suggestions on how to improve it, leading to a code optimization.</p> <pre><code>(function($) { var plugin_name = 'W.jQuery.FieldEvents'; var name_space = 'wFieldEvents'; var methods = { init : function(options) { return this.each(function(){ var field = $(this); var settings = { 'edit_button' : '', 'submit_button':'', 'error_message':'value not found', callback:function(){ alert('no call back defined for'+field.attr('id')) } }; settings = $.extend(settings, options); var data = field.data(name_space); var edit_button = $(settings.edit_button); var submit_button = $(settings.submit_button); if (!data) { $(this).data(name_space, { submit_button : submit_button, edit_button :edit_button, callback:settings.callback, error_message:settings.error_message }); } methods.enable_submit.call(field); }); }, disable_edit: function(){ return this.each(function(){ var field = $(this); var data = field.data(name_space); //alert(data.edit_button.attr('id')); data.edit_button.attr('disabled','disabled').off('click.'+name_space).addClass('ui-state-disabled'); }); }, enable_submit : function() { return this.each(function(){ var field = $(this); var data = field.data(name_space); //alert('working'); //alert('enabled submit called for '+field.attr('id')); methods.disable_edit.call(field); field.removeAttr('disabled'); data.submit_button.removeAttr('disabled').removeClass('ui-state-disabled'); data.submit_button.on('click.'+name_space,function(){ methods.submit.call(field); }); field.focus(); }); }, enable_edit: function() { return this.each(function(){ var field = $(this); var data = field.data(name_space); field.attr('disabled','disabled'); data.edit_button.removeAttr('disabled').removeClass('ui-state-disabled'); data.edit_button.on('click.'+name_space,function(){ methods.enable_submit.call(field); }); }); }, disable_submit: function(){ return this.each(function(){ var field = $(this); var data = field.data(name_space); field.attr('disabled','disabled'); data.submit_button.attr('disabled','disabled').off('click.'+name_space).addClass('ui-state-disabled'); methods.enable_edit.call(field); }); }, show_error: function(){ return this.each(function(){ var field = $(this); var data = field.data(name_space); //alert(data.error_message); field.focus(); $(dialog_id).html(data.error_message); $(dialog_id).dialog('open'); }); }, submit:function(){ return this.each(function(){ //alert('submit called'); var field = $(this); var data = field.data(name_space); var value = field.val(); if(value != '') { methods.disable_submit.call(field); data.callback(); } else { methods.show_error.call(field); } }); }, destroy : function() { return this.each(function(){ var $this = $(this), data = $this.data(name_space); // Namespacing FTW $(window).W.jQuery.FieldEvents(name_space); data.wFieldEvents.remove(); $this.removeData(name_space); }); } }; $.fn.W_FieldEvents = function( method ) { // Method calling logic if ( methods[method] ) { return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on '+plugin_name ); return false; } }; })(jQuery); </code></pre> <p><strong>Usage example:</strong></p> <pre><code>$(document).ready(function(){ $('#po_number').W_FieldEvents({ 'submit_button' : '#po_number_submit', 'edit_button' : '#po_number_edit', 'error_message' : 'PO# number not found', callback : function(){ alert('submit done'); } }); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T03:06:54.430", "Id": "26727", "Score": "3", "body": "It's always useful to run the code through [jslint](http://jslint.org) or [jshint](http://www.jshint.com). For instance, both caught that `dialog_id` is not defined anywhere but used in `show_error()`. You also have an implicit global (`data` in `destroy()`) which neither jshint or jslint caught (I just spotted it by chance)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T15:04:24.167", "Id": "26749", "Score": "0", "body": "What about data management, am i doing it correctly? is this good approach to save data for each element in its jQuery data attribute. Is there a way to store elements data in a single datastore? I have also noticed that if i call this plugin twice on an element it will double map the events. i.e showing two error messages instead of one. i want to avoid it, is there any way out?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T16:10:16.427", "Id": "26750", "Score": "1", "body": "You could store everything in a closure, I suppose, but I see no reason to not use `.data()`. Seems pretty straightforward to me (disclaimer: I've never had to make a jQuery plugin, so perhaps someone with more experience has a different opinion). As for the double events, I'd suggest you check for existing data on the elements. If it's there, it's been set up before, _and_ you can merge the existing settings and the passed-in options, instead of merging with the default options. Then calling it twice on the same element won't double the event, but will update the settings." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T19:48:00.207", "Id": "26761", "Score": "1", "body": "Waqasalieee, you don't need `name_space` as well as `plugin_name`. Simply use the `plugin_name` as the namespace name, and start the supervisor with `$.fn[plugin_name] = function(method) {`. @Flambino, with this pattern, you can only store whole-plugin stuff in the closure; no closure within the pattern is scoped to be element-specific so data must be stored in the DOM with `.data()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T11:13:55.043", "Id": "26777", "Score": "0", "body": "Beetroot, if am using this plugin name ' W.jQuery.FieldEvents ' then it contains dots (.), i thought it will create problems in event binding code i.e : edit_button.on('click.'+name_space,function(){//code});" } ]
[ { "body": "<p>You can refactor the init function.</p>\n\n<pre><code>init : function(options) {\n var defaults = {\n 'edit_button' : '',\n 'submit_button':'',\n 'error_message':'value not found'\n };\n options = $.extend({}, defaults, options);\n return this.each(function(){\n var field = $(this);\n if (!options.hasOwnProperty('callback') ) {\n options.callback = function(){\n alert('no call back defined for'+field.attr('id'))\n }\n } \n var data = field.data(name_space);\n var edit_button = $(options.edit_button);\n var submit_button = $(options.submit_button);\n if (!data) {\n $(this).data(name_space, {\n submit_button : submit_button,\n edit_button :edit_button,\n callback:options.callback,\n error_message:options.error_message\n });\n }\n methods.enable_submit.call(field);\n });\n },\n</code></pre>\n\n<p>As Flambino mentioned run your code through <a href=\"http://www.jslint.com\" rel=\"nofollow\">JSlint</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T06:57:04.287", "Id": "16431", "ParentId": "16401", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T09:42:38.843", "Id": "16401", "Score": "6", "Tags": [ "javascript", "jquery", "form", "plugin" ], "Title": "jQuery plugIn to manage forms" }
16401
<p>I have the following code that unfortunately is really slow:</p> <pre><code>private void FilterSessionByDate() { SessionsFilteredByDate = BusinessClient.Instance.Tracker.GetAllMilestonesInSessionObjects().Where( i =&gt; i.CreatedDate &gt;= GetFromDate() &amp;&amp; i.CreatedDate &lt;= GetToDate()); } private void FilterSessionsByTrackerId() { SessionsFilteredByDateAndTrackerId = SessionsFilteredByDate.Where(i=&gt;i.TrackerId == CurrentItem.ID); } private void BindGrid(DateTime fromDate, DateTime toDate, int trackerId, int campaignId) { var result = BusinessClient.Instance.Tracker.GetReportForCampaign(trackerId, campaignId, fromDate, toDate); foreach (var trackerReport in result) { trackerReport.Errors = GetErrors(trackerReport); } StatisticsGrid.DataSource = result.Where(r =&gt; r.ParentMilestoneId == null); StatisticsGrid.DataBind(); } private int GetErrors(TrackerReport milestone) { int counter = 0; //var milestonesWithId = BusinessClient.Instance.Tracker.GetAllMilestonesInSessionWithTrackerId(CurrentItem.ID); //var sessionsWithDateRange = milestonesWithId.Where(i=&gt; i.CreatedDate &gt;= GetFromDate() &amp;&amp; i.CreatedDate &lt;= GetToDate()); var sessionsWithStatusError = SessionsFilteredByDateAndTrackerId.Where(i =&gt; i.StatusId == 0); foreach (var milestonesInSession in sessionsWithStatusError) { // Get all milestoneinsessions with this session MilestonesInSession session = milestonesInSession; var localPath = BusinessClient.Instance.Tracker.GetAllMilestonesInSessionObjects().Where( i =&gt; i.SessionId == session.SessionId).ToList(); var lastStep = localPath.Max(i =&gt; i.MilestoneId); var latestTime = localPath.Where(i =&gt; i.MilestoneId != lastStep).Max(i=&gt;i.CreatedDate); var milestoneWithLatestTime = localPath.First(x =&gt; x.CreatedDate == latestTime); if (milestonesInSession.MilestoneId != milestone.MilestoneId) { if (milestoneWithLatestTime.MilestoneId == milestone.MilestoneId &amp;&amp; milestoneWithLatestTime.CreatedDate.AddSeconds(2) &gt;= milestonesInSession.CreatedDate) counter++; } else { // It is the last milestone, we have to check if the milestone with // the latest time is close to this one, otherwise the error happened // at the last step if (milestonesInSession.CreatedDate &gt; milestoneWithLatestTime.CreatedDate.AddSeconds(2)) counter++; } } return counter; } </code></pre> <p>The <code>MilestonesInSessions</code> in the database are 2 millions, but I managed to optimize the queries, so that the retrieving of them are pretty fast. Anyway, having multiple nested <code>foreach</code> affects its speed, given that:</p> <ul> <li>The <code>result</code> variable is always with 10 entries. </li> <li>The <code>sessionStatusWithError</code> variable has generally around 100 entries. </li> <li>The <code>localpath</code> variable is always with 10 entries.</li> </ul> <p><strong><code>IQueryable</code></strong></p> <pre><code>[RequiresDataAccessSynchronized] public IQueryable&lt;MilestonesInSession&gt; GetAllMilestonesInSessionObjects() { var query = from m in _milestonesInSessionRepository.GetAll() select m; return query; } </code></pre> <p><strong><code>MilestonesInSession</code></strong></p> <pre><code>public class MilestonesInSession : DataAccessBase2, IDataOperations&lt;Model.Tracker.MilestonesInSession, Model.Tracker.MilestonesInSession&gt; { #region IDataOperations&lt;MilestonesInSession,int&gt; Members public IQueryable&lt;Model.Tracker.MilestonesInSession&gt; GetAll() { var query = from milestoneSession in _dataContext.Repository&lt;Linq.TrackerMilestonesInSession&gt;() select new Model.Tracker.MilestonesInSession { MilestoneId = milestoneSession.MilestoneId, CreatedDate = milestoneSession.CreatedDate, SessionId = milestoneSession.SessionId, ProductId = milestoneSession.ProductId, TrackerId = milestoneSession.TrackerId, StatusId = milestoneSession.StatusId, BankId = milestoneSession.BankId }; return query; } </code></pre> <h2>Ants Performance profiler screenshots:</h2> <p><img src="https://i.stack.imgur.com/Eozob.png" alt="Ants Performance profiler screenshot 01" title="Ants Performance profiler screenshot 01"></p> <p><img src="https://i.stack.imgur.com/rx1Yn.png" alt="Ants Performance profiler screenshot 02" title="Ants Performance profiler screenshot 02"></p> <p>Do you know how can I optimize it to get a instant/better result instead of waiting at least 10 seconds every time?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T15:36:20.747", "Id": "26693", "Score": "1", "body": "Is that method `.GetAllMilestonesInSessionObjects()` lazy-loading, or does it get **all** Milestones from the DB and then the `.Where()` filters them?" } ]
[ { "body": "<p>If BusinessClient.Instance.Tracker.GetAllMilestonesInSessionObjects() is not returning IQueryable, you will be loading up all results from that method before applying the Where filters - on each iteration through the for loop. If that method really does what it says, then you are talking about transmitting millions of records from the DB before filtering, over and over.</p>\n\n<p>On the other hand, if BusinessClient.Instance.Tracker.GetAllMilestonesInSessionObjects() is returning IQueryable, then are you sure the underlying table is indexed for a comparison on the SessionId field?</p>\n\n<p>Either way, the ANTS performance readout makes it clear that's the bottle-neck.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T08:27:03.570", "Id": "26732", "Score": "0", "body": "Hello, The GetAllMilestonesInSessionObjects() is returning an IQueryable and I have an index on the sessionId" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T13:32:29.070", "Id": "26744", "Score": "0", "body": "So, is BusinessClient.Instance.Tracker.GetAllMilestonesInSessionObjects and autogenerated Linq2SQL method? It might be worth looking at the contents of this method. How many records match a particular session id? Also, can session id be null (both in the table and in the parameter)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T13:51:46.703", "Id": "26745", "Score": "0", "body": "I posted the content of the GetAllMilestonesInSessionObjects method.\nA sessionId matches exactly 10 records. The sessionId cannot be null anywhere." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T14:11:59.463", "Id": "26746", "Score": "0", "body": "As straightforward as expected. The query should end up being \"select [columns] from milestoneSession where sessionId = @p0\" (executed with sp_executesql). What is the datatype of session id? is the code consistent with the database?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T14:28:53.143", "Id": "26747", "Score": "0", "body": "the datatype of the session Id is a long, and it is a autoincrement number, the code is consistent with the database. I don't know about the select operation you wrote..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T14:41:59.547", "Id": "26748", "Score": "0", "body": "I observe that the binding operation is also slow (2nd ants image). Is it possible that there is a connectivity problem between db and client? Nothing we've looked at so far seems to account for the slowness." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T17:58:19.293", "Id": "26753", "Score": "0", "body": "You can set the [`DataContext.Log`](http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.log.aspx) property to find out the real SQL statements that LINQ is generating." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T18:06:31.017", "Id": "16414", "ParentId": "16405", "Score": "6" } }, { "body": "<p>You may also want to look at the <a href=\"http://miniprofiler.com/\" rel=\"nofollow noreferrer\">MiniProfiler</a> as it may give you more insight at a view that is optimized for both ASP.Net and DB query level (with a wrapper for Linq2Sql or EF). It appears to be making several trips to the data source so any slowness there will be magnified and could be exposed with this tool.</p>\n\n<p>It was created originally for MVC but also works with <a href=\"https://stackoverflow.com/questions/6320103/mvc-mini-profiler-web-forms-cant-find-mini-profiler-results\">WebForms</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T17:54:57.383", "Id": "16447", "ParentId": "16405", "Score": "3" } }, { "body": "<p>This looks like a classic iterative query problem. </p>\n\n<p>Instead of thinking procedurally (<em>first do this, then do that</em>) instead try think of what you need to do altogether, or set-based (<em>count the items when this and that and the other then...</em>). SQL works much better when given set based queries.</p>\n\n<p>I don't want to rewrite your query for you, but it appears that you are attempting to <strong>count</strong> how many milestones <strong>with session errors</strong> (where their <strong>last time</strong> is not equal to their <strong>last step</strong>) were <strong>within two seconds</strong> of the given miltestone. You should be able to write that in a single SQL query, rather than retrieving items, counting them, sorting them, and repeating n times.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T06:32:09.373", "Id": "26766", "Score": "0", "body": "Hello, Thanks for your post, I thought about having a single query or a single linq query to achieve the same, but nothing concrete came to my mind, so I had to code it :\\" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T12:31:48.907", "Id": "26778", "Score": "0", "body": "You'll always have to 'code it' - just code it better." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T21:10:09.107", "Id": "16449", "ParentId": "16405", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T14:43:40.843", "Id": "16405", "Score": "7", "Tags": [ "c#", "performance", "sql", "linq", "asp.net" ], "Title": "Getting instant/better result instead of waiting at least 10 seconds every time" }
16405
<p>I've got a code that is working in my environment. Nevertheless it is pretty ugly.</p> <p>This is what I am trying to do. I get a selectbox from a side with a lot of city names. I filter some names and push them into an array and hide them. The other ones are also pushed into an array, but shown.</p> <p>Now I append two options to the end of the selectbox, one is displayed, the other one hidden.</p> <p>When someone clicks the option all, the options from the array otherCities are shown and defaultCities are hidden. the option all is hidden as well, less is shown.</p> <p>This behavior works the other way round, too.</p> <p>How can I simplify my code? Any help is welcome.</p> <pre><code>var otherCities = new Array(); var defaultCities = new Array(); var selectBoxCity = jQuery("select[name='city']"); if(selectBoxCity.size() != 0) { selectBoxCity.prepend('&lt;option value="" selected="selected"&gt;-- Please Select --&lt;/option&gt;'); otherCities = new Array(); defaultCities = new Array(); var cityArray = ['OE', 'MK', 'SI', 'BO', 'DO', 'BM', 'HER', 'GE', 'HH']; var options = jQuery("select[name='city'] option"); options.each(function() { var o = jQuery(this); if (jQuery.inArray(o.attr("value"), cityArray) == -1) { otherCities.push(o.hide()); } else { defaultCities.push(o.show()); } }); selectBoxCity.find("option").end().append("&lt;option value='all'&gt;+&lt;/option&gt;"); selectBoxCity.find("option").end().append("&lt;option value='less'&gt;-&lt;/option&gt;"); } var selectBoxCity = jQuery("select[name='city']"); selectBoxCity.find("option:first").attr("selected", true); $("select[name='city'] option[value='less']").hide(); if(selectBoxCity.val() == "all") { jQuery.each(otherCities,function() { $(this).show(); }); jQuery.each(defaultCities,function() { $(this).hide(); }); $("select[name='city'] option[value='all']").hide(); $("select[name='city'] option[value='less']").show(); } if(selectBoxCity.val() == "less") { jQuery.each(otherCities,function() { $(this).hide(); }); jQuery.each(defaultCities,function() { $(this).show(); }); $("select[name='city'] option[value='all']").show(); $("select[name='city'] option[value='less']").hide(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T15:20:31.733", "Id": "26692", "Score": "1", "body": "I suggest throwing your code at [JSLint](http://www.jslint.com/), and thinking about its suggestions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T16:20:27.353", "Id": "26699", "Score": "0", "body": "Thanks for the hint. The markup is OK. I was asking about the functions. Whether I could simplify them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T16:21:43.363", "Id": "26700", "Score": "1", "body": "It'd be better to have the default cities marked in the markup (e.g. give them a class like `default`). Then you only need to run some selectors to hide/show, and won't have duplication of city values in your JS. Probably, also a good idea to keep the \"please select\" option in the markup rather than prepending it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T16:36:21.620", "Id": "26701", "Score": "0", "body": "By the way, hiding/showing an `option` tag doesn't seem to have any effect here in Chrome" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T16:47:02.593", "Id": "26702", "Score": "0", "body": "Hi, I have no influence on the actual markup. I'm just manipulating it via jQuery. The code works fine here. I've just sent the snippets I wasn't sure about the simplicity, so it may not work in your environment." } ]
[ { "body": "<p>Here's something that seems to work OK (<a href=\"http://jsfiddle.net/5V3hX/\" rel=\"nofollow\">here's a demo</a>)</p>\n\n<pre><code>jQuery(function ($) {\n var select = $(\"select[name=city]\"),\n defaults = select.children(\".default\"),\n others = select.children(\":not(.default)\");\n\n others.remove();\n\n select.on(\"change\", function (event) {\n var value = select.val();\n if(value === \"more\") {\n defaults.remove();\n select.append(others);\n } else if(value === \"less\") {\n others.remove();\n select.append(defaults);\n }\n });\n});​\n</code></pre>\n\n<p>Everything else is stored in the markup, like so:</p>\n\n<pre><code>&lt;select name=\"city\"&gt;\n &lt;!-- default options --&gt;\n &lt;option class=\"default\"&gt;A&lt;/option&gt;\n &lt;option class=\"default\"&gt;B&lt;/option&gt;\n &lt;option class=\"default\"&gt;C&lt;/option&gt;\n &lt;option value=\"more\" class=\"default\"&gt;Show more&lt;/option&gt;\n\n &lt;!-- expanded options --&gt;\n &lt;option&gt;D&lt;/option&gt;\n &lt;option&gt;E&lt;/option&gt;\n &lt;option&gt;F&lt;/option&gt;\n &lt;option&gt;G&lt;/option&gt;\n &lt;option&gt;H&lt;/option&gt;\n &lt;option&gt;I&lt;/option&gt;\n &lt;option value=\"less\"&gt;Show less&lt;/option&gt;\n&lt;/select&gt;​\n</code></pre>\n\n<p>As I said in the comments, <code>.hide</code> and <code>.show</code> doesn't seem to have any effect on <code>&lt;option&gt;</code> elements. Neither does <code>visibility: hidden</code>. In either case, they all show up in the select dropdown. You can disable options, but then they're still there, just greyed out.<br>\nHence, this code forcibly removes/appends the options.</p>\n\n<p>Of course, it might make more sense to simply remove/append only the non-default options. To me it makes more sense that the default options are a subset of all the options, not an entirely different set of options.</p>\n\n<p>Furthermore, it might be good to let the more/less options be added by JS, so clients that don't support JS don't see them.</p>\n\n<p>Putting all that together, you get <strong><a href=\"http://jsfiddle.net/5V3hX/1/\" rel=\"nofollow\">this</a></strong>.<br>\nWithout JS, you'll just see a full list. With JS, you get the more/less options and all that jazz.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T17:09:11.800", "Id": "26703", "Score": "0", "body": "I know it's tricky, but the options A,B,C shouldn't be shown when selecting more :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T17:10:51.450", "Id": "26704", "Score": "0", "body": "Which is what the code here does. It's only the 2nd jsfiddle demo that keeps the defaults around when selecting \"more\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T16:46:16.417", "Id": "16411", "ParentId": "16407", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T14:53:33.687", "Id": "16407", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "hide/show options in selectbox" }
16407
<p>Writing my first ASP.NET Web API web service. Still learing the power of Linq as well. I feel like there is a more ideomatic way of doing this:</p> <pre><code>public class StylesController : ApiController { private Entities db = new Entities(); // GET api/Styles public IEnumerable&lt;Style&gt; GetStyles(int division = 0, int family = 0, int model = 0, int year = 0, string market = "ANY") { market = market.ToUpper(); // make sure market is upper case IEnumerable&lt;Style&gt; q = db.Styles; if (division &gt; 0) { q = q.Where(s =&gt; s.DivisionId == division); } if (family &gt; 0) { q = q.Where(s =&gt; s.FamilyId == family); } if (model &gt; 0) { q = q.Where(s =&gt; s.ModelId == model); } if (year &gt; 0) { q = q.Where(s =&gt; s.Year == year); } if (market != "ANY") { q = q.Where(s =&gt; s.MarketCode == market); } return q.Distinct().OrderBy(s =&gt; s.Id).ToList(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T17:20:31.490", "Id": "26705", "Score": "0", "body": "From what I can see of this code, you are doing an AND operation. i.e. division = 1 AND year = 2012. Am I correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T19:55:25.200", "Id": "26712", "Score": "0", "body": "Correct, but each part of the AND is optional." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T23:29:28.413", "Id": "26762", "Score": "0", "body": "Fine to return an IEnumerable but that first declaration should be IQueryable<Style> q =" } ]
[ { "body": "<p>Good layout and white space.</p>\n\n<p>Although the logic works, I think it is very confusing, and not overly obvious. At first glance, it the if statements are very confusing. I would also rename the variables to have an Id or Code to the end of them to keep naming consistent.</p>\n\n<p>I think this is a good place where you could incorporate the <a href=\"http://en.wikipedia.org/wiki/Specification_pattern\">Specification Pattern</a>.</p>\n\n<pre><code>public class StylesController : ApiController\n{\n private Entities db = new Entities();\n\n public IEnumerable&lt;Style&gt; GetStyles(int divisionId = 0, int familyId = 0, int modelId = 0, int year = 0, string marketCode = \"ANY\")\n {\n var divisionIsAMatch = new DivisionIsAMatchSpecification(divisionId);\n var familyIsAMatch = new FamilyIsAMatchSpecification(familyId);\n var modelIsAMatch = new ModelIsAMatchSpecification(modelId);\n var yearIsAMatch = new YearIsAMatchSpecification(year);\n var marketIsAMatch = new MarketIsAMatchSpecification(marketCode);\n\n var q = db.Styles\n\n return q.Where(\n divisionIsAMatch\n .And(familyIsAMatch)\n .And(modelIsAMatch)\n .And(yearIsAMatch)\n .And(marketIsAMatch).IsSatisfiedBy\n ).Distinct()\n .OrderBy(s =&gt; s.Id);\n }\n}\n</code></pre>\n\n<p>Where</p>\n\n<pre><code>internal class DivisionIsAMatchSpecification : Specification&lt;Style&gt;\n{\n private readonly int _divisionId;\n\n public DivisionIsAMatchSpecification(int divisionId)\n {\n _divisionId = divisionId;\n }\n\n public bool IsSatisfiedBy(Style style)\n {\n if (_divisionId == 0) \n {\n return true;\n }\n\n return style.DivisionId == _divisionId;\n }\n}\n</code></pre>\n\n<p>Just rinse and repeat for each of the specifications you need. Of course, you will have to create the base classes for them too.</p>\n\n<p>I haven't tested this, but I have used this pattern before, and it works really nicely.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-26T07:12:26.197", "Id": "365388", "Score": "0", "body": "I know it's an old answer, but I'm not happy with this approach. I'm not sure how that should be translated to database statements using LINQ." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T03:13:35.890", "Id": "16428", "ParentId": "16410", "Score": "6" } } ]
{ "AcceptedAnswerId": "16428", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T16:19:06.643", "Id": "16410", "Score": "4", "Tags": [ "c#", "asp.net", "web-services" ], "Title": "ASP.NET Web API HTTP GET with optional parameters" }
16410
<p>I have a STI table and want to be able to render a collection using </p> <pre><code>render @collection </code></pre> <p>with every elements of the collection using their own partial or, if they don't have one, the parent partial. You know, partial inheritance.</p> <p>So I added to my parent model :</p> <pre><code>def to_partial_path self.class._to_partial_path end protected # a little hack to get partial inheritance in views, check if the partial exist, if not # return the parent's one. Provide class level cache, be sure to restart your app when # adding/removing partials. def self._to_partial_path @_to_partial_path ||= begin element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(self)) collection = ActiveSupport::Inflector.tableize(self) if File.exists?(Rails.root.join('app', 'views', collection, "_#{element}.html.erb")) || self.superclass == ActiveRecord::Base "#{collection}/#{element}" else self.superclass._to_partial_path end end end </code></pre> <p>The original code is <a href="https://github.com/rails/rails/blob/0d3d9a150a4ba1084cf28fd26be2a154f4540952/activemodel/lib/active_model/conversion.rb#L57" rel="nofollow noreferrer">here</a>.</p> <p>This seems to work great so far but I want to have some opinions.</p> <p>Should I have gone another way?</p> <p>Are there any "gotchas" I might encounter doing it this way?</p> <p>Any way to refactor this?</p> <p><strong>edit</strong>: No problem whatsoever, it's working great for now. I'm looking for a way to achieve something similar with form (ie render form in new and edit views render the <code>child _form</code> partial if their is one, the parent one otherwise).</p>
[]
[ { "body": "<p>This actually looks pretty solid.</p>\n\n<p>Another approach would be to <strong>sub-class</strong> the <strong><a href=\"http://apidock.com/rails/ActionView/PartialRenderer\" rel=\"nofollow\">Renderer</a></strong> and make it responsible for retrieving the base classes' <code>to_partial_path</code>.</p>\n\n<p>For me this feels a bit cleaner because it is <strong>sub-classing versus monkey-patching</strong> and because the renderer is supposed to find and load the template anyway while the model class shouldn't case about the (non-)existence of the view at all.</p>\n\n<p>After looking at it for a while, I would the make sub-classes <strong><a href=\"http://apidock.com/rails/ActionView/PartialRenderer/partial_path\" rel=\"nofollow\">partial_path</a></strong> check if the template exists and find the template of the base class if it doesn't.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-07T22:36:56.897", "Id": "86476", "Score": "0", "body": "How would you let Rails know that it should use the `PartialRenderer` subclass? Is their a hook for that (I haven't found one)?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-22T19:25:58.013", "Id": "33092", "ParentId": "16415", "Score": "2" } } ]
{ "AcceptedAnswerId": "33092", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T18:18:57.233", "Id": "16415", "Score": "5", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Rails partial inheritance hack" }
16415
<p>Is there a cleaner way to do the following?</p> <pre><code>friend_ids = [1,2,3,4,5] friendIDsQuery = "" friend_ids.each_with_index do |friend_id, index| friendIDsQuery += "SELECT id FROM test WHERE user_id = #{friend_id}" if index != friend_ids.size - 1 friendIDsQuery += " INTERSECT " end end </code></pre> <p>Basically I'm passing in an array of IDs, and building a custom INTERSECT query.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T10:42:01.403", "Id": "26739", "Score": "2", "body": "you wrote Array#join by hand..." } ]
[ { "body": "<pre><code>query = friend_ids.map {|id| \"SELECT id FROM test WHERE user_id=#{id}\"}.join \" INTERSECT \"\n</code></pre>\n\n<p><em>Bam.</em></p>\n\n<p>Edit: Ok, well, not just <em>bam</em>. First of all, if you're using Rails, go with something like NewAlexandria's answer, because it doesn't involve raw string interpolation (which quickly leads to SQL injection vulnerabilities). To make the above a little more safe (and assuming the IDs are integers), you should probably do</p>\n\n<pre><code>query = friend_ids.map { |id|\n \"SELECT id FROM test WHERE user_id = #{id.to_i}\"\n}.join \" INTERSECT \"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T21:48:19.080", "Id": "16421", "ParentId": "16418", "Score": "4" } }, { "body": "<p>This would be the more <em>idiomatic</em> Rails form, without so much SQL.</p>\n\n<pre><code>friend_ids.\n map {|fid| Test.select(:id).where(:user_id =&gt; fid) }.\n reduce {|a,e| a = a &amp; e }\n</code></pre>\n\n<p>If you <em>really</em> need the sql, then append:</p>\n\n<p><code>.to_sql</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T17:57:28.983", "Id": "28102", "Score": "0", "body": "You're missing the intersection-part. As far as I can tell, OP isn't trying to find ids where `user_id IN (...)`, but the intersection of multiple selections." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T02:35:46.883", "Id": "28115", "Score": "0", "body": "@Flambino you're right. Here is the correct for with intersections. I do concede that leaving the intersects within the database may be more performant than to do *N* queries and then operate upon them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T16:24:49.057", "Id": "28151", "Score": "1", "body": "+1. I'd say your solution has the distinct advantage of not generating a query string \"by hand\". In my answer I'm assuming that the IDs are safe - otherwise, well, hello injection attacks (should probably note that in my answer). Meanwhile, you're assuming that it's Rails. Very probable, but OP doesn't say. As for performance, your guess is as good as mine - OP doesn't say mention anything about the number of queries." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T13:50:49.940", "Id": "28531", "Score": "1", "body": "the OP didn't specify whether ActiveRecord or Rails was being used. Anyway, refactor of the reduce: `reduce([], :&)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T13:53:15.883", "Id": "28532", "Score": "0", "body": "@tokland though *arcane*, that's hot" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T15:15:07.317", "Id": "17609", "ParentId": "16418", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T20:29:39.863", "Id": "16418", "Score": "2", "Tags": [ "ruby" ], "Title": "Cleaner Code for custom query" }
16418
<p>This code works, but I'm sure it isn't written according to "best practices" for closures. On the other hand, at least it's intuitive to me... </p> <p>the taskRunner object runs functions on setTimeout, so as not to block the UI for too long. I'm breaking this function into chunks and running one chunk at a time. I'm passing i into my function so it will be part of the closure, but I know I've seen this done more elegantly - I just can't wrap my head around how to do it right now.</p> <pre><code>var tr = new taskRunner(); //I'm sure there's a better way to do a closure, but works for(var i=0;i&lt;blocks;i++){ var blockFunc = (function(i){ var innerFunc = function(){ var blockLen=Math.min(32768,len-(i*32768)); stream.push(i==(blocks-1)?0x01:0x00); Array.prototype.push.apply(stream, blockLen.bytes16sw() ); Array.prototype.push.apply(stream, (~blockLen).bytes16sw() ); var id=imageData.slice(i*32768,i*32768+blockLen); Array.prototype.push.apply(stream, id ); } return innerFunc; }(i)); tr.AddTask(blockFunc); } </code></pre>
[]
[ { "body": "<p>You could just bind to <code>stream</code> with <code>i</code> as a passed parameter, Though Im wondering why you are using <code>Array.prototype.push</code> when you could just use <code>stream.push()</code>, unless I've infered wrong, and stream isn't an array:</p>\n\n<pre><code>var tr = new taskRunner();\nfor(var i=0;i&lt;blocks;i++){\n tr.AddTask((function (i) {\n var blockLen = Math.min(32768, len - (i*32768));\n this.push(i == (blocks - 1) ? 0x01 : 0x00);\n Array.prototype.push.apply(this, blockLen.bytes16sw() );\n Array.prototype.push.apply(this, (~blockLen).bytes16sw() );\n var id = imageData.slice(i*32768, i*32768 + blockLen);\n Array.prototype.push.apply(this, id );\n }).bind(stream,i));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T21:03:28.497", "Id": "26720", "Score": "0", "body": "Hmm... I don't know either - I'll have to look. I found this function and I'm making it asynchronous with a callback. (It's a javascript implementation of Canvas.toDataURL, since it isn't implemented on Android - but it was too slow to run synchronously)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T20:36:32.130", "Id": "16423", "ParentId": "16422", "Score": "0" } }, { "body": "<p>IMO, inlined functions add clutter. I think it's clearer and cleaner to use a named function.</p>\n\n<pre><code>function makeBlockFunc(i) {\n return function(){\n var blockLen=Math.min(32768,len-(i*32768));\n stream.push(i==(blocks-1)?0x01:0x00);\n Array.prototype.push.apply(stream, blockLen.bytes16sw() );\n Array.prototype.push.apply(stream, (~blockLen).bytes16sw() );\n var id=imageData.slice(i*32768,i*32768+blockLen);\n Array.prototype.push.apply(stream, id );\n };\n}\n</code></pre>\n\n<p>Then invoke the function in the loop, passing <code>i</code>.</p>\n\n<pre><code>var tr = new taskRunner();\n\nfor(var i=0;i&lt;blocks;i++){\n tr.AddTask(makeBlockFunc(i));\n}\n</code></pre>\n\n<p>Also, you didn't really need an inner and outer function. You could have done the <code>.AddTask()</code> directly. Here the returned function is added directly into the <code>tr</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T21:04:28.543", "Id": "26721", "Score": "0", "body": "Oh, that's much prettier at least. Though I don't think I want makeBlockFunc to be global in scope - but I do see now that it's not very clean to re-declare it in the loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T21:11:19.570", "Id": "26722", "Score": "0", "body": "@Aerik: It doesn't necessarily need to be global. It can be in the same scope where the rest of your code is, or you can add it to a namespace if you're using one. But nothing in the function itself relies on the surrounding variable scope. As long as you have access to it, you can create and store it anywhere." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T20:38:31.573", "Id": "16424", "ParentId": "16422", "Score": "3" } }, { "body": "<p>Try this :</p>\n\n<pre><code>function blockFunc(i) {\n var n = i * 32768;\n return function() {\n var blockLen = Math.min(32768, len - n);\n stream.push(\n i==(blocks-1) ? 0x01 : 0x00,\n blockLen.bytes16sw(),\n (~blockLen).bytes16sw(),\n imageData.slice(n, n + blockLen)\n );\n };\n}\n\nvar tr = new taskRunner();\nfor(var i=0; i&lt;blocks; i++){\n tr.AddTask(blockFunc(i));\n}\n</code></pre>\n\n<p>Notes :</p>\n\n<ul>\n<li>If <code>stream.push()</code> works, then there's no need to use <code>Array.prototype.push.apply(...)</code>.</li>\n<li>With multiple arguments, <code>.push()</code> will push each arg in turn.</li>\n<li>With <code>var n = i * 32768</code> in the outer function, the calculation is performed once per <code>i</code>.</li>\n<li>It may also be possible to move the <code>var blockLen = ...</code> calculation into the outer function, depending on whether or not <code>len</code> needs to be read \"live\" each time the task is run.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T06:13:10.987", "Id": "16430", "ParentId": "16422", "Score": "1" } } ]
{ "AcceptedAnswerId": "16424", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-10T20:26:28.593", "Id": "16422", "Score": "0", "Tags": [ "javascript", "image", "closure" ], "Title": "Processing image blocks using a task runner" }
16422
<p>I have created a simple array-based Stack class with some methods like the actual Stack in Java.</p> <p>I am testing this for mistakes, but since I am learning Java, my tests may not be as comprehensive as they should.</p> <pre><code>import java.util.*; public class SJUStack&lt;E&gt; { // Data Fields private E[] theData; private int topOfStack = -1; private static final int INITIAL_CAPACITY = 10; private int size = 0; private int capacity = 0; // Constructors public SJUStack(int initCapacity) { capacity = initCapacity; theData = (E[]) new Object[capacity]; } public SJUStack() { this(INITIAL_CAPACITY); } // Methods public E push(E e) { if(size == capacity) { reallocate(); } theData[size] = e; size++; topOfStack++; return e; } // End push(E e) method public E peek() { if(empty()) { throw new EmptyStackException(); } return theData[topOfStack]; } // End peek() method public E pop() { E result = peek(); theData[topOfStack] = null; size--; topOfStack--; if(size &lt;= (capacity/4) &amp;&amp; capacity &gt;= INITIAL_CAPACITY) { shrink(); } return result; } // End pop() method public boolean empty() { return size == 0; } // End empty() method private void reallocate() { capacity *= 2; theData = Arrays.copyOf(theData, capacity); } // End reallocate() method private void shrink() { capacity /= 2; theData = Arrays.copyOf(theData, capacity); } // End shrink() method public String toString() { return Arrays.toString(theData); } // End toString() method public int size() { return size; } // End size() method } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T21:35:43.623", "Id": "26803", "Score": "4", "body": "Other suggestion - try making this class actually implement the `Stack` interface." } ]
[ { "body": "<p><code>topOfStack</code> is always one less than size, so you don't need that variable. Just replace all instances with <code>size-1</code>. Similarly, <code>capacity</code> could be replaced with <code>theData.length</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T23:21:04.597", "Id": "16450", "ParentId": "16426", "Score": "6" } }, { "body": "<ol>\n<li><p>I suggest to use following method name: <code>isEmpty()</code> instead of <code>empty()</code> </p></li>\n<li><p>If your Java version > 1.5 you should use <code>@Override</code> for your <code>toString()</code> method.</p></li>\n<li><p>Do you really need the <code>the</code> article in class field name like <code>theData</code>?</p></li>\n<li><p>You don't need both <code>size</code> and <code>topOfStack</code> variables. <code>theData.size</code> is enough.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T11:40:31.453", "Id": "16463", "ParentId": "16426", "Score": "9" } }, { "body": "<p>I don't see any obvious logic mistakes, points for that. On the other hand some redundant and non-standard ways of coding in java.</p>\n\n<ol>\n<li>Drop either <code>size</code> or <code>topOfStack</code> members, (<code>topOfStack == size - 1</code>)</li>\n<li>Drop capacity <code>capacity</code> is same as <code>theData.length</code></li>\n<li>Method name: <code>isEmpty</code> (more concise with java standard collections)</li>\n<li>Use <code>data</code> instead of <code>theData</code></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T12:01:50.803", "Id": "16464", "ParentId": "16426", "Score": "7" } } ]
{ "AcceptedAnswerId": "16464", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T02:54:33.433", "Id": "16426", "Score": "8", "Tags": [ "java", "array", "homework", "stack" ], "Title": "Simple array-based Stack class in Java" }
16426
<p>How can I refactor this redundant code?</p> <pre><code>$("#txtShippingAddressFullName").change(function () { $("#txtBillingAddressFullName").val($(this).val()); }) $("#txtShippingAddress").change(function () { $("#txtBillingAddress").val($(this).val()); }) $("#txtShippingPostalCode").change(function () { $("#txtBillingPostalCode").val($(this).val()); }) $("#txtShippingPhoneNumber").change(function () { $("#txtBillingPhoneNumber").val($(this).val()); }) $("#ddlShippingCity").change(function () { $("#ddlBillingCity").val($(this).val()); }) </code></pre>
[]
[ { "body": "<p>Since I don't know your markup, I don't know for sure if this will work, but it might</p>\n\n<pre><code>$(\"input[id*=Shipping]\").change(function (event) {\n var billingId = this.id.replace('Shipping', 'Billing');\n $(\"#\" + billingId).val($(this).val());\n});\n</code></pre>\n\n<p>Basically, get every input with \"Shipping\" in its id, and when such an input changes, use its id to determine the corresponding billing-input.</p>\n\n<p><em>Edit: While this solution is a neat little demonstration of the attribute-value-contains selector, it is - as the other answers have pointed out - better to use a class or data-attribute</em></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T03:21:27.773", "Id": "16429", "ParentId": "16427", "Score": "5" } }, { "body": "<p>Improving Flambino's answer, I think you should create a class for these elements and select them by the class.</p>\n\n<pre><code>$(\".elements-to-replace\").change(function (event) {\n var billingId = this.id.replace('Shipping', 'Billing');\n $(\"#\" + billingId).val($(this).val());\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T07:57:13.770", "Id": "16435", "ParentId": "16427", "Score": "4" } }, { "body": "<p>The prettiest way to do it, would be with HTML 5 data attribute:</p>\n\n<pre><code>&lt;input id=\"txtShippingAddress\" data-syncwith-id=\"txtBillinAddress\"&gt;\n&lt;input id=\"txtShippingPostalCode\" data-syncwith-id=\"txtBillingPostalCode\"&gt;\n&lt;input id=\"txtShippingAddressFullName\" data-syncwith-id=\"txtBillinAddressFullName\"&gt;\n</code></pre>\n\n<p>Then in your javscript:</p>\n\n<pre><code>$(\"input[data-syncwith-id]\").change(function (event) {\n $(\"#\" + $(this).data(\"syncwith-id\")).val($(this).val());\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T13:15:50.977", "Id": "26780", "Score": "0", "body": "This solution is more flexible since it doesn't restrict a rule for the new name." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T17:57:14.753", "Id": "16448", "ParentId": "16427", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T03:11:40.310", "Id": "16427", "Score": "4", "Tags": [ "javascript", "jquery", "form" ], "Title": "Synchronizing billing fields with the corresponding shipping fields" }
16427
<p>The problem presented to me:</p> <blockquote> <p>Declare a two-dimensional array of ints in main. Write a method to read in the size of each dimension, allocate memory for the array and return it (DON'T DO THIS IN MAIN, BUT CALL THIS METHOD IN MAIN).<br> Write another method to initialize each element to the sum of its indices (for example, the element at 3, 4 would have the value 7) (DON'T DO THIS IN MAIN, BUT CALL THIS METHOD IN MAIN).<br> IF TIME, write a method to print the 2-dim. array (use enhanced for loop if you want). (DON'T DO THIS IN MAIN, BUT CALL THIS METHOD IN MAIN)</p> </blockquote> <p>The output generated by my code:</p> <p>This is the output which I think is what the above question was asking:</p> <blockquote> <pre><code>0 1 2 3 4 5 1 2 3 4 5 6 2 3 4 5 6 7 3 4 5 6 7 8 4 5 6 7 8 9 </code></pre> </blockquote> <p>I finished this program to print a 2D array. I got the right output, but I'm not sure if I did what was being asked in the problem below.</p> <p>Can someone please look at the question below and tell me if I miss any part of the question? The part where I got confused was when it said to read in the size of each dimension:</p> <pre><code>package twoDarray; import java.util.Scanner; public class TwoDarray { public static void main(String[] args) { int[][] array= getArray(); init_array(array); printArray(array); } public static int[][] getArray() { int[][] array = new int[5][6]; return array; } public static int[][] init_array(int[][] array) { for(int i = 0; i&lt; array.length;i++) for(int j =0; j&lt; array[i].length;j++) array[i][j]= i+j; return array; } public static void printArray(int[][] array) { for(int i = 0; i&lt; array.length;i++) for(int j =0; j&lt; array[i].length;j++) System.out.printf("%d\n",array[i][j]); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T07:53:12.153", "Id": "26730", "Score": "0", "body": "are you sure that this is the expected format for printing the array?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T21:37:46.727", "Id": "26804", "Score": "0", "body": "Why are you returning the array, when you're obviously using the original reference to the (modified) array?" } ]
[ { "body": "<p>You need to read input (from the command line) using the Scanner class for the dimensions of the array. In this line, you chose 5 and 6:</p>\n\n<pre><code>int[][] array = new int[5][6];\n</code></pre>\n\n<p>Everything looks good except for that method (<code>getArray</code>). In that method, you should read in two numbers from the command line, and use those numbers (instead of 5 and 6) as the dimensions of the array.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T07:40:17.387", "Id": "16433", "ParentId": "16432", "Score": "1" } }, { "body": "<h2>Naming</h2>\n\n<p>Consistent: <code>init_array</code> might look better if it becomes <code>initArray</code></p>\n\n<p>Accurate: perhaps <code>processArray</code> could be used instead of <code>initArray</code>, since init means some kind of a <strong>setup</strong>, while the method actually <strong>changes</strong> the array's values.</p>\n\n<p>In addition, perhaps the class' name could be changed from <code>TwoDarray</code> to <code>TwoDimArray</code>, which, at least in the aesthetic aspect (to my own eyes), looks better.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T07:53:06.537", "Id": "16434", "ParentId": "16432", "Score": "1" } }, { "body": "<p>Coding enhancement</p>\n\n<pre><code>public static int[][] getArray(){\n return new int[5][6]; // no need of intermediate object\n}\n</code></pre>\n\n<p>Optimizing speed : never have a computation or an evaluation at each loop, car be very heavy with great number</p>\n\n<pre><code> for(int i = 0, n = array.lenght; i &lt; n ; i++) { ..\n</code></pre>\n\n<p>as <code>init_array</code> return <code>array</code> you can write directly :</p>\n\n<pre><code>printArray(init_array(getArray()));\n</code></pre>\n\n<p>Use :</p>\n\n<ul>\n<li><code>System.getProperty(\"line.separator\");</code> for all OS</li>\n<li><code>StringBuilder</code> then print out :</li>\n</ul>\n\n<p>. </p>\n\n<pre><code>public static void printArray(int[][] array){\n String NEWLINE = System.getProperty(\"line.separator\"); // You can put it 'public static' elsewhere\n StringBuilder sb = new StringBuilder(); // you can give the size of it between ()\n for(int i = 0; i&lt; array.length;i++)\n for(int j =0; j&lt; array[i].length;j++)\n sb.append(array[i][j])\n sb.append(NEWLINE);\n }\n }\n System.out.println(sb.toString());\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T08:09:16.380", "Id": "16436", "ParentId": "16432", "Score": "2" } } ]
{ "AcceptedAnswerId": "16436", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T07:03:47.273", "Id": "16432", "Score": "5", "Tags": [ "java", "array", "homework" ], "Title": "Printing a 2D array" }
16432
<p>I am currently using this code, but I am pretty sure there is a better way of doing it:</p> <pre><code>private string ReturnEmployeeName(string userName) { try { // Username coming is RandomDomain\RandomLengthUsername.whatever string[] sAMAccountName = userName.Split('\\'); return sAMAccountName[1]; </code></pre> <p>How can I make this faster? I am not sure if my <code>try</code> block will catch any exceptions that may arise because of this line.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T09:36:33.510", "Id": "26734", "Score": "1", "body": "If you're talking about catching exceptions, you should also show us your `catch` block." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T09:46:50.830", "Id": "26735", "Score": "0", "body": "Its just a simple catch exception that logs \"exception ex\" to event receiver, however main concern is splitting string and getting what I want :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T10:15:10.523", "Id": "26736", "Score": "0", "body": "Including the catch block would also tell us what you return if you don't find a proper name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T10:26:54.103", "Id": "26737", "Score": "0", "body": "just passing back a Constant which is just a generic default user name address" } ]
[ { "body": "<p>\"Fast\" is not too relevant here, since it's such a simple method.<br>\nAnd the canned response also applies: if you want to improve the speed, first do some benchmarking to know where the bottlenecks <strong>really</strong> are.</p>\n\n<p>But here my proposal of a better way:</p>\n\n<pre><code>private const string DefaultEmployeeName = \"JDoe\";\n/// &lt;param name=\"userName\"&gt;Format expected: \"Domain\\Name\"&lt;/param&gt;\nprivate string ParseEmployeeName(string userName) {\n if (userName == null) {\n return DefaultEmployeeName;\n }\n // Username coming is \"RandomDomain\\RandomLengthUsername.whatever\"\n // Let's split by '\\', returning maximum 2 substrings.\n // The second (n) will contain everything from the first (n-1) separator onwards.\n string[] parts = userName.Split(new char[] { '\\\\' }, 2);\n if (parts.Length &lt; 2) {\n return DefaultEmployeeName;\n }\n // Let's remove whitespace, just in case.\n string name = parts[1].Trim();\n if (string.IsNullOrEmpty(name)) {\n return DefaultEmployeeName;\n }\n return name; // \"RandomLengthUsername.whatever\"\n}\n</code></pre>\n\n<hr>\n\n<p>The comment with <code>///</code> on top is a \"<a href=\"http://msdn.microsoft.com/en-us/library/5ast78ax%28v=vs.71%29.aspx\" rel=\"nofollow\">documentation comment</a>\".<br>\nThose will enrich the Intellisense view of the method, providing extra information.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T10:29:13.367", "Id": "26738", "Score": "0", "body": "looks good, can you add few comments on each line as whats happening as well please as I am bit confused with code lines as \"string[] parts = userName.Split(new char[] { '\\\\' }, 2);\" or \"string name = parts[1] ?? \"\";\" Cheers" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T11:57:52.707", "Id": "26740", "Score": "1", "body": "`??` is the [null-coalescing operator](http://msdn.microsoft.com/en-us/library/ms173224.aspx). Doing `string name = user.name ?? \"John Doe\"` will store in name the value in user.name, or \"John Doe\" if null. (You should be aware that an empty string is not null.) I removed it from my code in the answer, because string.Split will never return nulls. (Woops!)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T10:09:41.513", "Id": "16438", "ParentId": "16437", "Score": "4" } }, { "body": "<p>Personally, I think you would be better off moving this code into a separate class as it's probably logic you are going to want in multiple places in your application and is most likely violating SRP (Single Responsibility Principle) wherever it is at the moment.</p>\n\n<p>If we create a username class, we can encapsulate the logic in there and then re-use it from wherever we want in the application:</p>\n\n<pre><code>public class UserName\n{\n private UserName() {}\n public string AccountName { get; private set; }\n public string DomainName { get; private set; }\n\n public static UserName Parse(string userName)\n {\n if (userName == null)\n {\n throw new ArgumentNullException(\"userName\");\n }\n\n if (userName.Contains(@\"\\\"))\n {\n var parts = userName.Split('\\\\');\n\n return new UserName { DomainName = parts[0], AccountName = parts[1] };\n }\n\n if (userName.Contains(\"@\"))\n {\n var parts = userName.Split('@');\n\n return new UserName { DomainName = parts[1], AccountName = parts[0] };\n }\n\n return new UserName { AccountName = userName };\n }\n}\n</code></pre>\n\n<p>You can then test the logic for this class in isolation:</p>\n\n<pre><code>public class UserNameTests\n{\n public class WhenCallingParseWithANullUserName\n {\n [Fact]\n public void AnArgumentNullExceptionShouldBeThrown()\n {\n Assert.Throws&lt;ArgumentNullException&gt;(() =&gt; UserName.Parse(null));\n }\n }\n\n public class WhenCallingParseWithAUserNameWithNoDomainName\n {\n private UserName userName;\n\n public WhenCallingParseWithAUserNameWithNoDomainName()\n {\n userName = UserName.Parse(\"JohnSmith\");\n }\n\n [Fact]\n public void TheDomainNameShouldBeNull()\n {\n Assert.Null(userName.DomainName);\n }\n\n [Fact]\n public void TheUserNameShouldEqualTheWholeUserName()\n {\n Assert.Equal(\"JohnSmith\", userName.AccountName);\n }\n }\n\n public class WhenCallingParseWithDomainSlashUserName\n {\n private UserName userName;\n\n public WhenCallingParseWithDomainSlashUserName()\n {\n userName = UserName.Parse(@\"Domain\\JohnSmith\");\n }\n\n [Fact]\n public void TheDomainNameShouldBeSetToTheDomainName()\n {\n Assert.Equal(\"Domain\", userName.DomainName);\n }\n\n [Fact]\n public void TheUserNameShouldBeSetToTheUserName()\n {\n Assert.Equal(\"JohnSmith\", userName.AccountName);\n }\n }\n\n public class WhenCallingParseWithUserNameAtDomain\n {\n private UserName userName;\n\n public WhenCallingParseWithUserNameAtDomain()\n {\n userName = UserName.Parse(@\"JohnSmith@Domain\");\n }\n\n [Fact]\n public void TheDomainNameShouldBeSetToTheDomainName()\n {\n Assert.Equal(\"Domain\", userName.DomainName);\n }\n\n [Fact]\n public void TheUserNameShouldBeSetToTheUserName()\n {\n Assert.Equal(\"JohnSmith\", userName.AccountName);\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T12:08:21.007", "Id": "16440", "ParentId": "16437", "Score": "7" } } ]
{ "AcceptedAnswerId": "16438", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T08:32:07.163", "Id": "16437", "Score": "4", "Tags": [ "c#", "performance", "strings", "error-handling", "sharepoint" ], "Title": "Splitting a string of random length" }
16437
<p>I am trying to write a generic JavaScript subroutine to set the periodicity in the week:</p> <pre><code>var items = {"0": "none", "1":"Daily", "2": "Every weekday (Monday to Friday)", "3": "Weekly"}; </code></pre> <p>I would like to improve this to make it more generic and readable if possible.</p> <pre><code>var callback = selectDay(idValue);​ createSelect(items, idValue, callback); </code></pre> <p></p> <pre><code>var createSelect = function (items, idValue) { var selElem = document.createElement("select"); $.each(items, function (key, value) { var ov = document.createElement("option"); ov.value = key; ov.appendChild(document.createTextNode(value)); selElem.appendChild(ov); }); $(idValue).prepend(selElem); }; </code></pre> <p></p> <pre><code>var selectDay = function (idValue, element) { var element = $(idValue); var childElements = idValue + '_'; element.find('select').change(function () { if($(this).val() === '0') { element.find('label').hide(); $(this).closest('div').find('input').attr("checked", false); } if($(this).val() === '1') { element.find('label').hide(); $(this).closest('div').find('input').attr("checked", true); } if($(this).val() === '2') { element.find('label').show(); for (var i = 0; i &lt; 5; i += 1) { $(childElements + i).attr("checked", true); } for (var i = 5; i &lt; 7; i += 1) { $(childElements + i).attr("checked", false); } } if($(this).val() === '3') { element.find('label').show(); $(this).closest('div').find('input').attr("checked", false); $(childElements + (new Date()).getDay()).attr("checked", true); } }); }; </code></pre> <p></p> <pre><code>var items = {"0": "none", "1":"Daily", "2": "Every weekday (Monday to Friday)", "3": "Weekly"}; var idValue = '#contest_data_updatePeriodicity_days'; createSelect(items, idValue); selectDay(idValue);​ </code></pre> <p>My questions are:</p> <ol> <li>How can I ameliorate this piece of code? </li> <li>How can make a callback in order to make something like this?</li> </ol> <p><a href="http://jsfiddle.net/D2RLR/2634/" rel="nofollow">JSFiddle</a></p>
[]
[ { "body": "<ol>\n<li>Use <code>prop()</code> instead of <code>attr()</code>.</li>\n<li>See the first point.</li>\n<li>You're declaring <code>var selectDay = function(idValue, element)</code>, your <code>element</code> argument is probably a typo? You don't need it.</li>\n<li>See the first point.</li>\n<li>Use <code>switch</code> instead of all those <code>if</code>. Or at least cache the <code>$(this).val()</code> result.</li>\n<li>See the first point.</li>\n<li>You don't need <code>element.find()</code>, you could use the <em>context</em> (somehow cleaner).</li>\n</ol>\n\n<p>Overall, here is some code to give you the idea:</p>\n\n<pre><code>var selectDay = function (idValue) {\n $('select', idValue).change(function() {\n switch ($(this).val()) {\n case '0':\n $('label', idValue).hide();\n\n // Use prop(), not attr().\n $(this).closest('div').find('input').prop('checked', true);\n break;\n }\n });\n};\n</code></pre>\n\n<p>Now you may notice something: this doesn't have <em>exactly</em> the same behavior as your code. Guess why :-)</p>\n\n<p>A friend of mine says that whenever you use a switch case, you can actually use a mapping object. This might be another way to do it. The mapping object would be something like:</p>\n\n<pre><code>var mapping = {\n '0': {\n 'label': 'hide',\n 'checked': false\n },\n '1': {\n 'label': 'hide',\n 'checked': true\n }\n};\n</code></pre>\n\n<p>And then you code accordingly to this object.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T12:15:29.470", "Id": "16441", "ParentId": "16439", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T11:59:14.120", "Id": "16439", "Score": "5", "Tags": [ "javascript", "jquery", "datetime" ], "Title": "Setting periodicity in the week in Google Calendar" }
16439
<p>I've spent a few days making the transition from WinForms to WPF, and do not have much time for tutorials as the work needs to be done quickly. I was wondering if anyone could take a look at a sample of my code and point out any conventions that I'm missing (and that are commonplace in modern WPF usage). I've picked a random sample of some XAML code which I've written:</p> <pre><code>&lt;Window x:Class="" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="300" Height="300"&gt; &lt;Window.Resources&gt; &lt;Style x:Key="buttonsStyle" TargetType="Button"&gt; &lt;Setter Property="Height" Value="25"/&gt; &lt;Setter Property="Width" Value="80"/&gt; &lt;/Style&gt; &lt;Style x:Key="componentsStyle" TargetType="Control"&gt; &lt;Setter Property="Height" Value="20"/&gt; &lt;Setter Property="Width" Value="190"/&gt; &lt;/Style&gt; &lt;Style x:Key="labelStyle" TargetType="Label"&gt; &lt;Setter Property="VerticalAlignment" Value="Center"/&gt; &lt;/Style&gt; &lt;/Window.Resources&gt; &lt;StackPanel Orientation="Vertical"&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition&gt; &lt;/RowDefinition&gt; &lt;RowDefinition&gt; &lt;/RowDefinition&gt; &lt;RowDefinition&gt; &lt;/RowDefinition&gt; &lt;RowDefinition&gt; &lt;/RowDefinition&gt; &lt;RowDefinition&gt; &lt;/RowDefinition&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="70"&gt; &lt;/ColumnDefinition&gt; &lt;ColumnDefinition Width="200"&gt; &lt;/ColumnDefinition&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Label Grid.Column="0" Grid.Row="0" Style="{StaticResource labelStyle}"&gt;Server:&lt;/Label&gt; &lt;ComboBox Grid.Column="1" Grid.Row="0" Name="cmbServer" Style="{StaticResource componentsStyle}"/&gt; &lt;CheckBox Name="chkWindowsAuthentication" Grid.Column="0" Grid.Row="1" IsChecked="False"/&gt; &lt;Label Grid.Column="1" Grid.Row="1" Style="{StaticResource labelStyle}"&gt;Use Windows Authentication&lt;/Label&gt; &lt;Label Grid.Column="0" Grid.Row="2" Style="{StaticResource labelStyle}"&gt;Username:&lt;/Label&gt; &lt;TextBox Grid.Column="1" Grid.Row="2" Name="txtUsername" Style="{StaticResource componentsStyle}"/&gt; &lt;Label Grid.Column="0" Grid.Row="3" Style="{StaticResource labelStyle}"&gt;Password:&lt;/Label&gt; &lt;PasswordBox Grid.Column="1" Grid.Row="3" Name="txtPassword" Style="{StaticResource componentsStyle}"/&gt; &lt;Label Grid.Column="0" Grid.Row="4" Style="{StaticResource labelStyle}"&gt;Database:&lt;/Label&gt; &lt;ComboBox Grid.Column="1" Grid.Row="4" Name="cmbDatabase" Style="{StaticResource componentsStyle}"/&gt; &lt;/Grid&gt; &lt;StackPanel Orientation="Horizontal" Margin="10,30,10,10"&gt; &lt;Button Margin="0,0,10,0" Style="{StaticResource buttonsStyle}"&gt;Connect&lt;/Button&gt; &lt;Button Style="{StaticResource buttonsStyle}"&gt;Reset&lt;/Button&gt; &lt;/StackPanel&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p>The code is functional and displays the proper result, however I am worried that I am not using the right techniques. Any input at all is greatly appreciated.</p>
[]
[ { "body": "<p>All in all, your code is quite well-structured. Here are a couple of suggestions for improvement:</p>\n\n<ol>\n<li><p>Consider moving your styles to a <em><a href=\"http://www.codeproject.com/Articles/35346/Using-a-Resource-Dictionary-in-WPF\">resource dictionary</a></em>:</p>\n\n<pre><code>&lt;Window.Resources&gt;\n &lt;ResourceDictionary Source=\"Resources.xaml\" /&gt;\n&lt;/Window.Resources&gt;\n</code></pre>\n\n<p>This will de-clutter your file and allow you to re-use the styles in other windows. </p></li>\n<li><p>Collapse empty tags (use the self-closing syntax):</p>\n\n<pre><code>&lt;Grid.RowDefinitions&gt;\n &lt;RowDefinition /&gt;\n &lt;RowDefinition /&gt;\n &lt;RowDefinition /&gt;\n &lt;RowDefinition /&gt;\n &lt;RowDefinition /&gt;\n&lt;/Grid.RowDefinitions&gt;\n</code></pre>\n\n<p><sup>(the same goes for the ColumnDefinitions and any other empty tags)</sup></p></li>\n<li><p>Declare styles that affect all controls of one type <em>without a key</em>:</p>\n\n<pre><code>&lt;Style TargetType=\"Button\"&gt; ... &lt;/Style&gt;\n&lt;Style TargetType=\"Label\"&gt; ... &lt;/Style&gt;\n</code></pre>\n\n<p>That way, you don't seperately have to set all the labels to <code>labelStyle</code> and all the buttons to <code>buttonsStyle</code>, just remove all occurences of the following two attributes:</p>\n\n<pre><code>Style=\"{StaticResource labelStyle}\"\nStyle=\"{StaticResource buttonsStyle}\"\n</code></pre></li>\n<li><p>The default value of <code>Grid.Column</code> and <code>Grid.Row</code> is <code>0</code>, you can get away without setting it explicitly. And <code>CheckBox.Checked</code> is <code>false</code> by default. So you can remove all occurences of the following:</p>\n\n<pre><code>Grid.Column=\"0\" \nGrid.Row=\"0\" \nIsChecked=\"False\"\n</code></pre></li>\n<li><p>Generally, in WPF, widths and heights are not explicitly stated. You should try to use relative and automatic dimensions where possible (which often requires choosing the correct container).\nFor instance, you could use relative sizing for your grid columns:</p>\n\n<pre><code>&lt;Grid.ColumnDefinitions&gt;\n &lt;ColumnDefinition Width=\"0.35*\" /&gt;\n &lt;ColumnDefinition Width=\"*\" /&gt;\n&lt;/Grid.ColumnDefinitions&gt;\n</code></pre>\n\n<p>In other situations, working with <code>Margin</code> can be a replacement for explicit pixel sizes. Remember that hard-coded sizes are an obstacle to localization (where long words in foreign languages are cropped) and less flexible.</p></li>\n</ol>\n\n<p>These suggestions shrink your Window <code>.xaml</code> file from 54 to 37 lines (<code>Resources.xaml</code> has 14).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T17:57:05.040", "Id": "26752", "Score": "0", "body": "Thank you very much for the detailed reply. So if I basically had to replace widths and heights with margin values, that would solve the last problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T17:59:34.690", "Id": "26754", "Score": "0", "body": "You don't *have* to, but yes, margins are normally used where possible instead of heights and widths." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T18:16:30.563", "Id": "26756", "Score": "0", "body": "If I may also ask, what would be the convention for setting the window's height and width? (since I should try to avoid explicitly specifying them)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T18:18:11.610", "Id": "26757", "Score": "1", "body": "Personally, I wouldn't remove all instances of `Grid.Column=\"0\"`, because I like to have the code regular. But it makes sense to omit it if you have a grid with only one column." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T18:30:40.080", "Id": "26758", "Score": "0", "body": "@DotNET it's fine to specify an explicit width and height since the window can be resized by the user (unless you disable that)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T18:31:06.570", "Id": "26759", "Score": "0", "body": "@svick it's a trade-off between conciseness and being explicit. Both are valid approaches. In fact, that's why I used the fishy words `you can get away with...` ;)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T17:50:26.933", "Id": "16446", "ParentId": "16445", "Score": "16" } } ]
{ "AcceptedAnswerId": "16446", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T17:19:37.943", "Id": "16445", "Score": "11", "Tags": [ "c#", ".net", "wpf", "xaml" ], "Title": "Grid UI layout for a database" }
16445
<p>A question was asked over at math.SE (<a href="https://math.stackexchange.com/questions/200835">here</a>) about whether or not there are infinitely many superpalindromes. I'm going to rephrase the definition to a more suitable one for coding purposes:</p> <blockquote> <p><strong>Definition</strong>: A <em>superpalindrome</em> is a product of primes p(1) * p(2) * ... * p(k), where p(i)&lt;=p(i+1) for 1&lt;=i&lt;=k-1, such that p(1) * p(2) * ... * p(r) is a palindrome for all 1 &lt;= r &lt;= k.</p> </blockquote> <p>A natural question to ask, is whether or not there's an infinite number of superpalindromes with all of its prime factors &lt;=N. Thus, we can use a depth-first search.</p> <p>Here is my implementation in C using <a href="http://gmplib.org/" rel="nofollow noreferrer">GMP</a>, but I'm wondering if there is some ways to give non-trivial run-time improvements.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;gmp.h&gt; // search for superpalindromes containing prime factors in {2,3,...,q} // where q is the MAX_NR_PRIMES-th prime #define MAX_NR_PRIMES 20000 #define MAX_SEARCH_DEPTH 100 #define MAX_NR_DIGITS 10000 // start backtracking at the (STARTING_PRIME_ID+1)-th prime #define STARTING_PRIME_ID 0 mpz_t list_of_small_primes[MAX_NR_PRIMES]; mpz_t n_new[MAX_SEARCH_DEPTH]; int max_depth_reached=0; mpz_t nr_superpalindromes_found[MAX_SEARCH_DEPTH]; // checks if n is a palindrome // idea "borrowed" from http://gmplib.org/list-archives/gmp-discuss/2012-February/004876.html int is_palindrome(mpz_t n) { char m[MAX_NR_DIGITS]; int len=gmp_sprintf(m,"%Zd",n); for(int i=0;i&lt;len;i++) { if(m[i]!=m[len-i-1]) return 0; } return 1; } // depth-first search for superpalindromes // searches for a prime p:=list_of_small_primes[i_new], with i_new&gt;=i // such that n*p is a palindrome; continues searching if one is found int extend_superpalindrome_backtracking_algorithm(mpz_t n,int i,int depth) { for(int i_new=i;i_new&lt;MAX_NR_PRIMES;i_new++) { // n_new[depth]:=n*p mpz_mul(n_new[depth],n,list_of_small_primes[i_new]); if(is_palindrome(n_new[depth])) { // increment count of number of superpalindromes with depth+1 prime factors mpz_add_ui(nr_superpalindromes_found[depth],nr_superpalindromes_found[depth],1); // print out the first superpalindrome found with &gt;depth+1 prime factors if(depth&gt;max_depth_reached) { max_depth_reached=depth; gmp_printf("superpalindrome found: %Zd at depth %d: ",n_new[depth],depth+1); mpz_t primes[MAX_SEARCH_DEPTH]; for(int i=0;i&lt;MAX_SEARCH_DEPTH;i++) mpz_init(primes[i]); mpz_set(primes[0],n_new[0]); for(int i=1;i&lt;=depth;i++) mpz_divexact(primes[i],n_new[i],n_new[i-1]); for(int i=0;i&lt;=depth;i++) gmp_printf("%Zd ",primes[i]); printf("\n"); for(int i=0;i&lt;MAX_SEARCH_DEPTH;i++) mpz_clear(primes[i]); } // continue the depth-first search if superpalindrome found extend_superpalindrome_backtracking_algorithm(n_new[depth],i_new,depth+1); } } } int main() { mpz_t n,p; mpz_init_set_ui(n,1); mpz_init_set(p,list_of_small_primes[STARTING_PRIME_ID]); for(int i=0;i&lt;MAX_SEARCH_DEPTH;i++) mpz_init(n_new[i]); for(int i=0;i&lt;MAX_SEARCH_DEPTH;i++) mpz_init(nr_superpalindromes_found[i]); for(int i=0;i&lt;MAX_NR_PRIMES;i++) mpz_init(list_of_small_primes[i]); // pre-compute small primes mpz_set_ui(list_of_small_primes[0],2); for(int i=1;i&lt;MAX_NR_PRIMES;i++) mpz_nextprime(list_of_small_primes[i],list_of_small_primes[i-1]); extend_superpalindrome_backtracking_algorithm(n,STARTING_PRIME_ID,0); // output results gmp_printf("\nfound all superpalindromes with prime factors in {2,3,...,%Zd}\n",list_of_small_primes[MAX_NR_PRIMES-1]); mpz_t total_nr_superpalindromes; mpz_init_set_ui(total_nr_superpalindromes,0); for(int i=0;i&lt;=max_depth_reached;i++) { mpz_add(total_nr_superpalindromes,total_nr_superpalindromes,nr_superpalindromes_found[i]); gmp_printf("nr superpalindromes with %d prime factors: %Zd\n",i+1,nr_superpalindromes_found[i]); } gmp_printf("total nr superpalindromes: %Zd\n",total_nr_superpalindromes); mpz_clear(total_nr_superpalindromes); for(int i=0;i&lt;MAX_SEARCH_DEPTH;i++) mpz_clear(n_new[i]); for(int i=0;i&lt;MAX_NR_PRIMES;i++) mpz_clear(list_of_small_primes[i]); mpz_clear(n); mpz_clear(p); return 0; } </code></pre> <p>Here's the output:</p> <pre><code>superpalindrome found: 4 at depth 2: 2 2 superpalindrome found: 8 at depth 3: 2 2 2 superpalindrome found: 88 at depth 4: 2 2 2 11 superpalindrome found: 2552 at depth 5: 2 2 2 11 29 superpalindrome found: 257752 at depth 6: 2 2 2 11 29 101 superpalindrome found: 67788776 at depth 7: 2 2 2 11 29 101 263 superpalindrome found: 616267762616 at depth 8: 2 2 2 11 29 101 263 9091 superpalindrome found: 6101667117661016 at depth 9: 2 2 2 11 29 101 263 9091 9901 superpalindrome found: 20302629368699686392620302 at depth 10: 2 11 11 11 101 9091 9091 9091 9901 10151 superpalindrome found: 1001004004006006004004001001 at depth 11: 7 11 13 101 101 101 101 9901 9901 9901 9901 found all superpalindromes with prime factors in {2,3,...,224737} nr superpalindromes with 1 prime factors: 113 nr superpalindromes with 2 prime factors: 428 nr superpalindromes with 3 prime factors: 1022 nr superpalindromes with 4 prime factors: 1539 nr superpalindromes with 5 prime factors: 1603 nr superpalindromes with 6 prime factors: 1137 nr superpalindromes with 7 prime factors: 565 nr superpalindromes with 8 prime factors: 217 nr superpalindromes with 9 prime factors: 50 nr superpalindromes with 10 prime factors: 13 nr superpalindromes with 11 prime factors: 1 total nr superpalindromes: 6688 </code></pre> <p>Currently, I'm mostly concerned about the efficiency of <code>is_palindrome(mpz_t n)</code> since it feels like a "two-pass" method: (a) copy the number to a string, (b) check if the string is a palindrome. But please highlight any other areas I might not be concerned about but should be.</p> <p>Most of the numbers encountered by <code>is_palindrome(mpz_t n)</code> will not be palindromes, but my attempt at checking only the first and last digits was thwarted by <code>mpz_sizeinbase</code> not giving the exact number of digits in base 10 (and it added too much overhead to add a "check if the number of digits is correct" function).</p>
[]
[ { "body": "<h1>Things you did well</h1>\n\n<ul>\n<li><p>You defined <code>i</code> within your <code>for</code> loops, and abided by the <a href=\"https://en.wikipedia.org/wiki/C99\" rel=\"nofollow\">C99 standards</a>.</p></li>\n<li><p>You used an external library instead of writing your (more likely inefficient) own methods, and thus avoided unnecessarily <a href=\"/questions/tagged/reinventing-the-wheel\" class=\"post-tag\" title=\"show questions tagged &#39;reinventing-the-wheel&#39;\" rel=\"tag\">reinventing-the-wheel</a>.</p></li>\n</ul>\n\n<h1>Things you could improve on:</h1>\n\n<h3>Efficiency:</h3>\n\n<ul>\n<li><p>Copying a whole number into a external array with <code>gmp_sprintf()</code> in your <code>is_palindrome()</code> method is very time consuming, as you suspected.</p>\n\n<blockquote>\n<pre><code>int is_palindrome(mpz_t n) {\n char m[MAX_NR_DIGITS];\n int len=gmp_sprintf(m,\"%Zd\",n);\n for(int i=0;i&lt;len;i++) {\n if(m[i]!=m[len-i-1]) return 0;\n }\n return 1;\n}\n</code></pre>\n</blockquote>\n\n<p>Is it reasonable to assume that most numbers will be non-palindromes? If not, I would suggest something like this:</p>\n\n<ol>\n<li><p>Determine the approximate number of digits in your number <em>a</em> using\n<code>mpz_sizeinbase()</code> and call this number \\$ n \\$.</p></li>\n<li><p>Compute \\$ \\dfrac{a}{d^{(n-30)}} \\$, then compute \\$ a \\bmod d^{30} \\$. Print both in base \\$ d \\$ and compare. If they are unequal, reject as non-palindrome.</p>\n\n<p>Computing \\$ \\dfrac{a}{d^{(n-30)}} \\$ will be fast using <code>mpz_tdiv_q()</code>.\nUnfortunately, computing \\$ d^{30} \\$ is not fast. Perhaps a rough approximation of that would also increase efficiency.</p></li>\n</ol></li>\n<li><p>Using a <a href=\"https://en.wikipedia.org/wiki/Sieve\" rel=\"nofollow\">sieve</a> for an early exit would increase efficiency.</p></li>\n<li><p>Combine some of your <code>for</code> loops. </p>\n\n<blockquote>\n<pre><code>for(int i=0;i&lt;MAX_SEARCH_DEPTH;i++) mpz_init(n_new[i]);\nfor(int i=0;i&lt;MAX_SEARCH_DEPTH;i++) mpz_init(nr_superpalindromes_found[i]);\n...\nfor(int i=1;i&lt;=depth;i++) mpz_divexact(primes[i],n_new[i],n_new[i-1]);\nfor(int i=0;i&lt;=depth;i++) gmp_printf(\"%Zd \",primes[i]);\n...\nfor(int i=0;i&lt;MAX_SEARCH_DEPTH;i++) mpz_init(primes[i]);\nfor(int i=0;i&lt;MAX_SEARCH_DEPTH;i++) mpz_clear(primes[i]);\n</code></pre>\n</blockquote>\n\n<p>These loops are very similar, and many iterations (<a href=\"https://en.wikipedia.org/wiki/Busy_waiting\" rel=\"nofollow\">even for simple loops</a>) can take more time than you think. Combining them will increase efficiency.</p></li>\n<li><p>Try to avoid putting statements that print data to the console inside of a loop.</p>\n\n<blockquote>\n<pre><code>for(int i=0;i&lt;=depth;i++) gmp_printf(\"%Zd \",primes[i]);\n</code></pre>\n</blockquote>\n\n<p><code>gmp_printf()</code> (and all <code>printf()</code>-esque statements) can be very taxing on a system. Extracting them to the outside of the loop will increase efficiency.</p></li>\n</ul>\n\n<h3>Style:</h3>\n\n<ul>\n<li><p>Your code is very compact.</p>\n\n<blockquote>\n<pre><code>for(int i=0;i&lt;MAX_SEARCH_DEPTH;i++) mpz_init(primes[i]);\nmpz_set(primes[0],n_new[0]);\nfor(int i=1;i&lt;=depth;i++) mpz_divexact(primes[i],n_new[i],n_new[i-1]);\nfor(int i=0;i&lt;=depth;i++) gmp_printf(\"%Zd \",primes[i]);\nprintf(\"\\n\");\nfor(int i=0;i&lt;MAX_SEARCH_DEPTH;i++) mpz_clear(primes[i]);\n</code></pre>\n</blockquote>\n\n<p>I'm all for compact code, but you still want your code to be readable. Let it <em>breathe</em> a bit. Use spaces after commas and semi-colons, use an empty line to separate and organize code.</p></li>\n<li><p>You sometimes write a loop with braces, and sometimes without braces, even though they both have one statement in them.</p>\n\n<blockquote>\n<pre><code>for(int i=0;i&lt;len;i++) {\n if(m[i]!=m[len-i-1]) return 0;\n}\n...\nfor(int i=0;i&lt;MAX_SEARCH_DEPTH;i++) mpz_init(primes[i]);\n</code></pre>\n</blockquote>\n\n<p>Choose one way and stick with it. Consistency is very important.</p></li>\n</ul>\n\n<h3>Syntax</h3>\n\n<ul>\n<li><p>If you don't accept any parameters into a function, they should be declared <code>void</code>.</p>\n\n<pre><code>int main(void)\n</code></pre></li>\n</ul>\n\n<h3>Comments:</h3>\n\n<ul>\n<li><p>You have some obsolete comments that can be removed (old lines of code). </p>\n\n<blockquote>\n<pre><code>// n_new[depth]:=n*p\n</code></pre>\n</blockquote></li>\n<li><p>Use more comments to describe what you are doing. Since you are making more calls to an external library, this means that you will need <em>more</em> comments to explain why you are doing things the way you are, and how you accomplish that. You may also need to include comments on what the external functions purpose is.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-25T04:28:12.547", "Id": "42729", "ParentId": "16451", "Score": "12" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-11T23:56:45.323", "Id": "16451", "Score": "12", "Tags": [ "optimization", "c", "primes", "palindrome", "depth-first-search" ], "Title": "Depth-first search method for searching for all \"superpalindromes\" whose prime factors are all <=N" }
16451
<p>I have two choices of implementing a method, the first one is a generic type where the client code does not have to cast</p> <pre><code> public T GetControl&lt;T&gt;(string controlName) where T : Control { return (T)ControlManager.GetControl( controlName); //I simplify the logic here, in my case this is a bit //complicated than this, but the object we get is of the Type Control } </code></pre> <p>client code: </p> <pre><code>MyControl control = GetControl&lt;MyControl&gt;("foo"); </code></pre> <p>The second choice is the non-generic one. Here the client code will have to cast</p> <pre><code> public Control GetControl(string controlName) { return ControlManager.GetControl(controlName); // I simplify the logic here, in my case this is a bit // complicated than this, but the object we get is of the Type Control } </code></pre> <p>client code:</p> <pre><code> MyControl control = (MyControl)GetControl("foo"); </code></pre> <p>Is one of them better than the other? At first I thought first one is better, because casting (which I think is a bit dirty) is refactored in one method, and don't have to be repeated in all client codes. But since the generic type has to be specified by the client code anyway (<a href="https://stackoverflow.com/questions/3203643/generic-methods-in-net-cannot-have-their-return-types-inferred-why">generic methods can't infer return type</a>), basically the client code only shift <code>(MyControl)</code> in front to <code>&lt;MyControl&gt;</code> in the generic parameter, so it's probably not better anyway.</p> <p>What is your opinion?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T08:31:33.890", "Id": "26770", "Score": "2", "body": "I personally prefer the first but I've also often had a tendency to over-use generics (got a little excited when I first started using them) and have at times caused myself more grief than it was worth it." } ]
[ { "body": "<p>In my opinion the generic method is better for two reasons. First, it's cleaner, both for the client calling it because they don't have to cast and for the process of casting because it is only done in one place. Secondly, the client that's asking for the control knows the type of the control in this instance so it's very sensible, and good practice, to have the client specify that rather than sending back an object just so the client has to cast it. That's why generics exist. </p>\n\n<p>However, I recommend in your code in the method you use the <strong>as</strong> operator rather than a cast because even though the client calling you specified the type, the as operator will simply return null instead of throwing an exception. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T08:49:01.947", "Id": "26772", "Score": "1", "body": "Isn't returning null a bad practice (I remember reading this somewhere)? And in my case, if the cast failed, the client cannot do anything anyway, then isn't it better that the exception reads \"cast failure\" instead of a nasty nullreference exception?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T09:36:02.090", "Id": "26775", "Score": "5", "body": "I would strongly advise against using `as` here. If there is a mistake, you want to know about it as soon as possible and you want to know what exactly is the mistake. Cast does that: it immediately throws an `InvalidCastException` that explains what happened. Using `as` would mean you will most likely get `NullReferenceException` sometime after calling this method, that's confusing (which object exactly is `null`?) and too late." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T12:17:21.777", "Id": "28524", "Score": "0", "body": "@svick, duly noted, that is something I'll consider in my future endeavors as well. Thanks!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T07:38:53.740", "Id": "16458", "ParentId": "16452", "Score": "5" } }, { "body": "<p>I think using generics here is slightly better, because it means if you decide to change the code in a way that requires knowledge of the type that's being asked for, you can.</p>\n\n<p>The change could be as simple as logging the type, or something much more complicated. For example, it would allow you to have controls with the same name, but different types, if you wanted to do that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T09:40:41.587", "Id": "16461", "ParentId": "16452", "Score": "3" } }, { "body": "<p>Consider this, suppose you wanted to get the control and invoke some method on it but didn't necessarily want to declare a variable for it. Well a \"pre-casted\" return type will be much better than casting yourself. Which would you prefer?</p>\n\n<pre><code>GetControl&lt;MyControl&gt;(\"MyControlName\").MyMethod();\n\n((MyControl)GetControl(\"MyControlName\")).MyMethod();\n</code></pre>\n\n<p>I <em>hope</em> you'd say the generic version is better. With a cast, you are required to wrap in parentheses due to the lower precedence.</p>\n\n<p>If you have the opportunity to return the most appropriate type (statically or generically), try to make it happen. Having to perform a cast on the result of a method call is a sign of a problem nowadays IMHO. It's almost as bad as returning type <code>object</code>.</p>\n\n<p>Casting is ugly. This is one of the reasons I'd imagine why there are extension methods on existing objects that does something similar. <a href=\"http://msdn.microsoft.com/en-us/library/system.data.datarowextensions.field.aspx\" rel=\"nofollow\"><code>DataRow.Field&lt;T&gt;()</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/system.data.datarowextensions.setfield.aspx\" rel=\"nofollow\"><code>DataRow.SetField&lt;T&gt;()</code></a> come to mind which allows you to read or write a column in a data row.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T15:48:10.763", "Id": "26792", "Score": "0", "body": "I think the `Field()` method is there mostly to deal with `DBNull`. But that's part of the reason why use generics in cases like this: you can do more complicated things with the type internally." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T14:38:27.993", "Id": "16471", "ParentId": "16452", "Score": "1" } } ]
{ "AcceptedAnswerId": "16461", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T03:11:14.510", "Id": "16452", "Score": "10", "Tags": [ "c#", "casting", "generics" ], "Title": "Cast inside the method or let the client code cast, which one is better?" }
16452
<p>I'm currently writing some code in PyQt4 that takes a value and a control and binds the value to the control. Once the user saves the form it will unbind all the values and save it back to a custom object (in this case <a href="http://www.qgis.org/api/classQgsFeature.html" rel="nofollow">QgsFeature</a>).</p> <p>At the moment, I have the bind and unbind code which uses <code>if</code>/<code>elif</code> statements to work out the control type and then use the correct methods to bind the value, like so:</p> <pre><code>def bindValueToControl(self, control, value): """ Binds a control to the supplied value. Raises BindingError() if control is not supported. control - QWidget based control that takes the new value value - A QVariant holding the value """ if isinstance(control, QCalendarWidget): control.setSelectedDate(QDate.fromString(value.toString(), Qt.ISODate)) elif isinstance(control, QListWidget): items = control.findItems(value.toString(), Qt.MatchExactly) try: control.setCurrentItem(items[0]) control.currentItemChanged.emit(None, items[0]) except IndexError: pass elif isinstance(control, QLineEdit) or isinstance(control, QTextEdit): control.setText(value.toString()) elif isinstance(control, QCheckBox) or isinstance(control, QGroupBox): control.setChecked(value.toBool()) elif isinstance(control, QPlainTextEdit): control.setPlainText(value.toString()) elif isinstance(control, QComboBox): # Add items stored in the database query = QSqlQuery() query.prepare("SELECT value FROM ComboBoxItems WHERE control = :contorl") query.bindValue(":control", control.objectName()) query.exec_() while query.next(): newvalue = query.value(0).toString() if not newvalue.isEmpty(): control.addItem(newvalue) itemindex = control.findText(value.toString()) if itemindex == -1: control.insertItem(0,value.toString()) control.setCurrentIndex(0) else: control.setCurrentIndex(itemindex) elif isinstance(control, QDoubleSpinBox): double, passed = value.toDouble() control.setValue(double) elif isinstance(control, QSpinBox): integer, passed = value.toInt() control.setValue(integer) else: raise BindingError(control, value.toString(), "Unsupported widget %s" % control) </code></pre> <p>for unbind:</p> <pre><code>def unbindFeature(self, qgsfeature): """ Unbinds the feature from the form saving the values back to the QgsFeature. """ for index, control in self.fieldtocontrol.items(): value = None if isinstance(control, QLineEdit): value = control.text() elif isinstance(control, QTextEdit) or isinstance(control, QPlainTextEdit): value = control.toPlainText() elif isinstance(control, QCalendarWidget): value = control.selectedDate().toString(Qt.ISODate) elif isinstance(control, QCheckBox) or isinstance(control, QGroupBox): value = 0 if control.isChecked(): value = 1 elif isinstance(control, QComboBox): value = control.currentText() if control.isEditable(): self.saveComboValues(control, value) elif isinstance(control, QDoubleSpinBox) or isinstance(control, QSpinBox): value = control.value() elif isinstance(control, QDateTimeEdit): value = control.dateTime().toString(Qt.ISODate) elif isinstance(control, QListWidget): item = control.currentItem() if item: value = item.text() else: return QString("") </code></pre> <p>I can't help but feel this is a little dirty looking. Is there a nicer, more maintainable, way to handle something like this.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T04:46:50.070", "Id": "62825", "Score": "0", "body": "This post might help you [Pythonic way to avoid a mountain of if…else statements](http://stackoverflow.com/questions/5640598/pythonic-way-to-avoid-a-mountain-of-if-else-statements) The concept of [dispatch table](http://stackoverflow.com/questions/715457/how-do-you-implement-a-dispatch-table-in-your-language-of-choice) is also a good way of handling large if-else or switch block." } ]
[ { "body": "<p>To expand a little further on part of sky py's answer, you could try something like the following</p>\n\n<pre><code>class BaseControlHandler:\n def __init__( self, control ):\n self.control = control\n def bind( self, value ): \n raise SuitableException()\n def unbind( self ):\n raise SuitableException()\n\nclass LineEditHandler( BaseControlHandler ):\n def __init__( self, control ):\n BaseControlHandler.__init__( self, control )\n def bind( self, value ):\n self.control.setText(value.toString())\n def unbind( self ):\n return self.control.text()\n\nclass CheckBoxHandler( BaseContolHandler ):\n # etc\n</code></pre>\n\n<p>You could then set up a dictionary mapping the control type to the appropriate handler:</p>\n\n<pre><code>handlers = { QtLineEdit: LineEditHandler, QtCheckBox: CheckBoxHandler, ... }\n</code></pre>\n\n<p>So your main block of if..elif.. becomes</p>\n\n<pre><code>for ctltype in handlers:\n if isinstance( control, ctltype ):\n ctl = handlers[ctltype]( control )\n ctl.bind( value ) # or unbind\n break\n</code></pre>\n\n<p>You'll unfortunately need to keep the <code>handlers=</code> line and the subclasses in step together.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T08:00:46.570", "Id": "16459", "ParentId": "16454", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T04:37:55.293", "Id": "16454", "Score": "5", "Tags": [ "python", "pyqt" ], "Title": "Binding a value to a control" }
16454
<p>I don't like how this config has so much duplication. Any suggestions on how to at least shorten it somewhat? Normally we only have one server block as the staging server is separate from production, but the client has gotten their own server so we'll need to stage on that.</p> <pre><code>upstream upgrade-release{ server 127.0.0.1:8000; } upstream upgrade-staging{ server 127.0.0.1:8010; } server { listen 80; server_name www.upgrade.sg upgrade.sg; access_log /var/log/nginx/upgrade.access.log; error_log /var/log/nginx/upgrade.error.log; root /home/upgrade/npcec/release/src/npcec; location /media/ { expires max; access_log off; } location /static/ { expires max; access_log off; } location /robots.txt { alias /home/upgrade/npcec/release/src/npcec/static/robots.txt; access_log off; } location /favicon.ico { alias /home/upgrade/npcec/release/src/npcec/static/favicon.ico; expires max; access_log off; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://upgrade-release; } } server { listen 80; server_name staging.upgrade.sg; access_log /var/log/nginx/upgrade.access.log; error_log /var/log/nginx/upgrade.error.log; root /home/upgrade/npcec/staging/src/npcec; location /media/ { expires max; access_log off; } location /static/ { expires max; access_log off; } location /robots.txt { alias /home/upgrade/npcec/staging/src/npcec/static/robots.txt; access_log off; } location /favicon.ico { alias /home/upgrade/npcec/staging/src/npcec/static/favicon.ico; expires max; access_log off; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://upgrade-staging; } } </code></pre>
[]
[ { "body": "<p>My little attempt basically takes items that are repeated and puts them into their own separate conf files and just include them into the main conf files. On my servers, I structure them as such:</p>\n\n<pre><code>global\n include1.conf\n include2.conf\n include3.conf\nsites-available\n site1.conf\n site2.conf\n</code></pre>\n\n<p>And the includes are included in the SA conf files. Not good for performance, but negligible.</p>\n\n<p>Anyways, here's an idea:</p>\n\n<pre><code>upstream upgrade-release{\n server 127.0.0.1:8000;\n}\n\nupstream upgrade-staging{\n server 127.0.0.1:8010;\n}\n\nserver {\n listen 80;\n server_name www.upgrade.sg upgrade.sg;\n\n access_log /var/log/nginx/upgrade.access.log;\n error_log /var/log/nginx/upgrade.error.log;\n\n root /home/upgrade/npcec/release/src/npcec;\n\n include media_static.conf;\n\n location /robots.txt {\n alias /home/upgrade/npcec/release/src/npcec/static/robots.txt;\n access_log off;\n }\n\n location /favicon.ico {\n alias /home/upgrade/npcec/release/src/npcec/static/favicon.ico;\n expires max;\n access_log off;\n }\n\n location / {\n include proxy.conf;\n proxy_pass http://upgrade-release;\n }\n}\n\nserver {\n listen 80;\n server_name staging.upgrade.sg;\n\n access_log /var/log/nginx/upgrade.access.log;\n error_log /var/log/nginx/upgrade.error.log;\n\n root /home/upgrade/npcec/staging/src/npcec;\n\n include media_static.conf;\n\n location /robots.txt {\n alias /home/upgrade/npcec/staging/src/npcec/static/robots.txt;\n access_log off;\n }\n\n location /favicon.ico {\n alias /home/upgrade/npcec/staging/src/npcec/static/favicon.ico;\n expires max;\n access_log off;\n }\n\n location / {\n include proxy.conf;\n proxy_pass http://upgrade-staging;\n }\n}\n</code></pre>\n\n<p>In media_static.conf: </p>\n\n<pre><code>location /media/ {\n expires max;\n access_log off;\n}\n\nlocation /static/ {\n expires max;\n access_log off;\n}\n</code></pre>\n\n<p>In proxy.conf:</p>\n\n<pre><code>proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\nproxy_set_header Host $http_host;\nproxy_redirect off;\n</code></pre>\n\n<p>Also, instead of <code>proxy_pass http://</code> perhaps consider using <code>proxy_pass $scheme</code>. Perhaps someone with more experience with Nginx confs will follow up with a way to store certain bits and pieces in variables or will offer a better solution than mine (I for one would love to know a better way of doing things)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T13:45:28.470", "Id": "29494", "Score": "1", "body": "+1 for seperating into multiple files - you can find something to compare to in the [h5bp server config project](https://github.com/h5bp/server-configs/tree/master/nginx)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-12T16:57:06.860", "Id": "29506", "Score": "0", "body": "That is an absolute treasure trove of conf files @AD7six! Downloaded them and will be implementing many in my servers. Thanks for sharing that resource!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T17:22:45.583", "Id": "16477", "ParentId": "16457", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T05:54:30.730", "Id": "16457", "Score": "2", "Tags": [ "nginx" ], "Title": "Staging/release nginx config" }
16457
<p>I've read a lot about using MVC in game development and it seems to be a good way (speaking of testing, code reusing, etc ...)</p> <p>I created a XNA project and tried to implement MVC. But I'm not sure if I'm doing it right.</p> <p>I seperated the game into three blocks:</p> <ul> <li>Renderers (the "View")</li> <li>GameObjects and GameLogic (the "Model")</li> <li>Controllers</li> </ul> <p>On top of these components is a <code>GameEngine</code> object (created by the XNA game class) which instantiates all of the components and handles the draw and update methods (game class calls <code>GameEngine.Draw</code> and <code>GameEngine.Update</code>).</p> <pre><code>public class GameEngine { private readonly HUDRenderer m_HUDRenderer; private readonly Game m_game; private readonly List&lt;IRenderer&gt; m_lstRenderer = new List&lt;IRenderer&gt;(); private readonly Player m_player; private readonly PlayerRenderer m_playerRenderer; private readonly World m_world; private readonly WorldController m_worldController; private readonly WorldRenderer m_worldRenderer; public GameEngine(Game game) { m_game = game; m_player = new Player(); m_world = new World(m_player); // Controller m_worldController = new WorldController(m_world); // Views m_worldRenderer = new WorldRenderer(m_world); m_lstRenderer.Add(m_worldRenderer); m_playerRenderer = new PlayerRenderer(m_world); m_lstRenderer.Add(m_playerRenderer); m_HUDRenderer = new HUDRenderer(m_world); m_lstRenderer.Add(m_HUDRenderer); } public void Update(GameTime gameTime) { m_worldController.Update(gameTime); } public void Draw(GameTime gameTime, DrawContext drawContext) { drawContext.Begin(); // ########## ADD ALL DRAW METHODS ########## foreach (IRenderer renderer in m_lstRenderer) { renderer.Render(gameTime, drawContext); } // ########## END OF ADD ALL DRAW METHODS ########## drawContext.End(); } /// &lt;summary&gt; /// Loads all the content /// &lt;/summary&gt; /// &lt;param name="content"&gt; &lt;/param&gt; public void LoadContent(ContentManager content) { } } </code></pre> <p>Additionally, <code>GameEngine</code> creates the Player object and a World object. All <code>GameObjects</code> are POCOs. The <code>World</code> holds the Player, the "obstacles" and "enemies".</p> <pre><code>public class World { public List&lt;List&lt;Entity&gt;&gt; WorldGrid; public World(Player player) { Player = player; FPSCounter = new FPSCounter("0", new Vector2(16, 16), Color.White); } public FPSCounter FPSCounter { get; private set; } public Player Player { get; private set; } } </code></pre> <p>The <code>World</code> is passed as an argument to the <code>Renderers</code> so they have access to the object they need to draw and the world (if the objects need to visually interact with the world).</p> <pre><code>public class HUDRenderer : IRenderer { private readonly World m_world; public HUDRenderer(World world) { m_world = world; } #region IRenderer Members public void Render(GameTime gameTime, DrawContext drawContext) { m_world.FPSCounter.FrameCount += 1; if (m_world.FPSCounter.Font != null) { drawContext.SpriteBatch.DrawString(m_world.FPSCounter.Font, m_world.FPSCounter.Text, m_world.FPSCounter.Position, m_world.FPSCounter.Color); } else { drawContext.SpriteBatch.DrawString(drawContext.DefaultFont, m_world.FPSCounter.Text, m_world.FPSCounter.Position, m_world.FPSCounter.Color); } } #endregion } </code></pre> <p>The <code>Controller</code> receives input and changes the model by using the <code>GameLogic</code>.</p> <pre><code>public class WorldController { private readonly World m_world; private KeyboardState m_keyboardState; private MouseState m_mouseState; public WorldController(World world) { m_world = world; } public void Update(GameTime gameTime) { m_keyboardState = Keyboard.GetState(); m_mouseState = Mouse.GetState(); var hudLogic = new HudGLO(); hudLogic.CalculateFPS(gameTime, m_world.FPSCounter); } } </code></pre> <p>And the <code>Views</code> render everything.</p> <pre><code>public class HUDRenderer : IRenderer { private readonly World m_world; public HUDRenderer(World world) { m_world = world; } #region IRenderer Members public void Render(GameTime gameTime, DrawContext drawContext) { m_world.FPSCounter.FrameCount += 1; if (m_world.FPSCounter.Font != null) { drawContext.SpriteBatch.DrawString(m_world.FPSCounter.Font, m_world.FPSCounter.Text, m_world.FPSCounter.Position, m_world.FPSCounter.Color); } else { drawContext.SpriteBatch.DrawString(drawContext.DefaultFont, m_world.FPSCounter.Text, m_world.FPSCounter.Position, m_world.FPSCounter.Color); } } #endregion } </code></pre> <p>I'm passing the <code>World</code> object in most of the other objects. Does this make sense? Should it be static somewhere?</p> <p>Am I even getting close to the MVC principle?</p> <p>Where do you put logic concerning an object (like player movement). Does it reside in the object itself or is it "outsourced" in the game logic? OOP vs. MVC?</p> <p>If you want to see the complete code you can find the project <a href="https://github.com/bux578/XNA-MVC-Template" rel="noreferrer">here</a>.</p> <p>If it's somehow helpful to you, feel free to extend, fork or copy it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T09:22:08.147", "Id": "26773", "Score": "2", "body": "Please include code in the question. \"This site is for code reviews, which are hard to do when the code is behind a link somewhere out there on the internet. If you want a code review, you must post the relevant snippets of code in your question. It is fine to post a \"see more\" link (though, do be careful — very few reviewers will be willing to click through and read thousands of lines of your code), but the most important parts of the code must be placed directly in the question.\" (from the FAQ)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T10:17:24.537", "Id": "26776", "Score": "2", "body": "@palacsint I added the code to the question. Thank you for the hint." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-16T14:25:52.537", "Id": "29799", "Score": "0", "body": "Why `GameLogic` is a model? Logic is something that controls another \"something\", thus it is more controller than model." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T19:05:24.107", "Id": "31172", "Score": "1", "body": "This is a good question, and it's a pity that it has not received a good and thorough answer - or at least some discussion. I added a bounty. Hopefully this will spark good attention and discussion, and even renew the asker's interest in the community. :)" } ]
[ { "body": "<p>To answer your questions, 1) I would make the World a singleton, therefore both eliminating the need for quite a few params and the need to put it as a static field somewhere. However, make sure that retrieving the instance is a lightweight method, because it will happen a lot.\n As for the game logic, I would say it depends. For objects which have only one or three instances, I would put the logic in the class, but for more numerous things, put that in a seperate object.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-10T18:34:23.503", "Id": "19469", "ParentId": "16460", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T08:14:06.903", "Id": "16460", "Score": "22", "Tags": [ "c#", "game", "mvc", "xna" ], "Title": "MVC in XNA game development - rudimentary MVC GameEngine" }
16460
<p>I've written the following function to parse a configuration file. I did my best to make it simple, but it's still over 30 lines and has too much indentation caused by a series of <code>if</code> statements.</p> <p>Any suggestions make it easier to read are welcome.</p> <pre><code>int parse_config (FILE * conf_file, module_initializer_t init) { char *line; /* Current line */ char *type; /* Type of current module */ char *name; /* Name of current module */ char *envz; size_t envz_len; size_t lineno = 0; line = type = name = envz = NULL; while (getline (&amp;line, NULL, conf_file) != EOF) { lineno++ ; if (!is_comment(line)) if (line[0] == '[') if (update_header(line, &amp;type, &amp;name)) { if (type) if ((*init)(type, name, envz, envz_len)) { fprintf("failed to initialize module %s with name %s", type, name); return 1; } clear_envz(&amp;envz, &amp;envz_len); } else { fprint("syntax error on line %d", lineno); return 1; } else argz_add(&amp;envz, &amp;envz_len, line); } if ((*init)(type, name, envz, envz_len)) { fprintf("failed to initialize module %s with name %s", type, name); return 1; } } </code></pre> <p>It parses a configuration file with the following syntax: </p> <pre><code> #comment and empty lines ignored [module-type]{module-name} var1=val1 #comment var2=val2 [another-type]{another-name} var3=val3 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T14:15:52.463", "Id": "26784", "Score": "0", "body": "Does it work? What is it supposed to do? Note that you have `init` called with `envz` and `envz_len` uninitialized, and the function falls off the end without a return value. Also, which `if` is the `else argz_add` supposed to belong to?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T04:01:38.857", "Id": "26817", "Score": "0", "body": "Why uninitialized? NULL and 0 are valid.\nAccording standard and indentation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T04:26:53.510", "Id": "26821", "Score": "0", "body": "Does fprintf not need a file stream as first argument? http://www.cplusplus.com/reference/clibrary/cstdio/fprintf/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T04:41:39.493", "Id": "26822", "Score": "0", "body": "Yes, you are right. But that's not the point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T15:02:14.387", "Id": "26842", "Score": "0", "body": "Sorry, I didn't notice envz is set to NULL. GCC will warn you of the ambiguous 'else'. According to the indentation, argz_add() is called for comments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T00:08:35.500", "Id": "27854", "Score": "0", "body": "Small suggestion: In your example it looks like `if (type) { if (init /* ... */) { } }` could be replaced with `if (type && init(/* ... */)) { }` - though from squinting at it, it looks like that's the only two `if` blocks that can be trivially collapsed into one like that." } ]
[ { "body": "<p>Rather than 'removing' <code>if</code>s, it may be better to move them around!</p>\n\n<p>But <em>please</em>, put <code>{}</code> for every <code>if</code>, even if it has only one statement (another if). It makes it a lot easier to read.</p>\n\n<ol>\n<li><p>Treat the <code>!is_comment</code> as a precondition for the loop contents. It's right at the start, so it's obvious that you're doing something 'special' with it. Maybe even change the <code>while</code> to a <code>for</code> to push it further up.</p>\n\n<pre><code>for ( lineno = 1; getline(&amp;line, NULL, conf_file) != EOF; lineno++ ) \n{\n /* skip over comments */\n if ( is_comment( line ) ) { continue; }\n</code></pre></li>\n<li><p>Put your \"header processing\" part into another function, since it performs a single task. It's a little awkward with the number of parameters even so, but you're removing three levels of indentation while reading it.</p></li>\n</ol>\n\n<p>You'll be left with the following (if I've got it right); it's longer, but may be more readable.</p>\n\n<pre><code>#define PARSE_FAILURE 1\n#define SUCCESS 0\n\nint parse_module_header( module_initializer_t init, char* line, int lineno, char** penvz, size_t* penvz_len )\n{\n char *type; /* Type of current module */\n char *name; /* Name of current module */\n\n type = name = NULL;\n if ( update_header( line, &amp;type, &amp;name ) ) {\n\n if ( type ) {\n\n if ( (*init)( type, name, *penvz, *penvz_len ) ) {\n\n fprintf(\"failed to initialize module %s with name %s\", type, name);\n return PARSE_FAILURE;\n }\n }\n clear_envz( penvz, penvz_len );\n }\n else {\n\n fprint( \"syntax error on line %d\", lineno );\n return PARSE_FAILURE;\n }\n return SUCCESS;\n}\n\nint\nparse_config (FILE * conf_file, module_initializer_t init)\n{\n char *line; /* Current line */\n char *envz;\n size_t envz_len;\n size_t lineno = 0;\n\n line = envz = NULL;\n for ( lineno = 1; getline( &amp;line, NULL, conf_file ) != EOF; lineno++ ) \n {\n /* skip over comments */\n if ( is_comment( line ) ) { continue; }\n\n if (line[0] == '[') {\n\n /* begin a new module section */\n int err;\n err = parse_module_header( init, line, lineno, &amp;envz, &amp;envz_len );\n if ( err != SUCCESS ) {\n\n return err;\n }\n }\n else {\n\n /* set a config variable for the current module */\n argz_add( &amp;envz, &amp;envz_len, line );\n }\n }\n return SUCCESS;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T04:05:49.430", "Id": "26820", "Score": "0", "body": "You too missed memory leak. But idea of moving `lineno` to `for` is awesome. Thanks! And, also, \nI do not like this braces." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T13:18:02.863", "Id": "16469", "ParentId": "16462", "Score": "1" } }, { "body": "<p>You can pack together single line if sentences, but remember to put an empty line after the last one:</p>\n\n<pre><code>if (cond1) continue;\nif (cond2) {printMessage(); continue;}\n\n// Put empty line after last if block!\ndoRealWork();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T15:50:31.760", "Id": "26793", "Score": "0", "body": "Why is the empty line so important?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T18:09:47.757", "Id": "26799", "Score": "0", "body": "Not loving single line `if statements`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T15:12:55.583", "Id": "16475", "ParentId": "16462", "Score": "1" } }, { "body": "<p>I would do some re-arranging:<br>\nUse the quick exit pattern.</p>\n\n<p>This is basically if it fails the useful criteria exit (or in this case start the next loop). Basically you test for conditions that don't satisfy your working conditions. If the data does not match then you move on.</p>\n\n<pre><code>int\nparse_config (FILE * conf_file, module_initializer_t init)\n{\n char *line; /* Current line */\n char *type; /* Type of current module */\n char *name; /* Name of current module */\n char *envz;\n size_t envz_len;\n size_t lineno = 0;\n\n line = type = name = envz = NULL;\n while (getline (&amp;line, NULL, conf_file) != EOF) \n {\n lineno++ ;\n if (is_comment(line))\n { continue; // Ignore comments;\n }\n\n if (line[0] != '[')\n {\n argz_add(&amp;envz, &amp;envz_len, line);\n continue; // Processes arguments and continue\n }\n\n if (!update_header(line, &amp;type, &amp;name))\n {\n fprint(\"syntax error on line %d\", lineno);\n return 1; // Not an argument and not a header\n // must be an error.\n }\n\n // Processes a header\n if (type)\n {\n if ((*init)(type, name, envz, envz_len))\n {\n fprintf(\"failed to initialize module %s with name %s\", type, name);\n return 1;\n }\n clear_envz(&amp;envz, &amp;envz_len);\n } \n }\n\n if ((*init)(type, name, envz, envz_len)) {\n fprintf(\"failed to initialize module %s with name %s\", type, name);\n return 1;\n }\n\n // You should also return a value here.\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T04:02:07.327", "Id": "26818", "Score": "0", "body": "Your code leaks memory. If i do not need to free memory, things would be much easier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T14:32:01.817", "Id": "26840", "Score": "0", "body": "Not sure how my code differs from yours (apart from looking nicer) :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T07:25:50.297", "Id": "27861", "Score": "0", "body": "Yeah. My bad. I forgot `free` too. =)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T21:40:22.643", "Id": "16487", "ParentId": "16462", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T10:07:21.707", "Id": "16462", "Score": "2", "Tags": [ "c", "parsing" ], "Title": "Parsing a configuration file in C" }
16462
<p>It's common pattern when you need to assign a variable inside a block</p> <pre><code>def query(sql) logger.debug "Db: Executing query #{sql}" result = nil ts = Benchmark.realtime do result = @db.exec sql end logger.debug "Db: Query completed in #{ts}" result end </code></pre> <p>Is there a more elegant way to rewrite this snippet?</p>
[]
[ { "body": "<p>I am afraid your code cannot be simplified further due to the imperative nature of <code>Benchmark.realtime</code> (it would have been better if it also returned the result of the block). Anyway, I think the best solution is to abstract it and write a wrapper method. For example:</p>\n\n<pre><code>def benchmark(msg)\n logger.debug(msg)\n result = nil\n ts = Benchmark.realtime(&amp;block) { result = yield }\n logger.debug(\"Completed in #{ts} seconds\")\n result\nend\n\ndef query(sql)\n benchmark(\"DB: Executing query #{sql}\") do\n @db.exec(sql)\n end\nend\n</code></pre>\n\n<p>Now, if your question was on a more generic plane, let's say, that you have lots of methods that work like <code>realtime</code> which force you write a lot of boilerplate, I'd propose this generic <code>Object#capture</code> wrapper:</p>\n\n<pre><code>class Object\n def capture(method, *args)\n result2 = nil\n result1 = send(method, *args) { |*bargs| result2 = yield(*bargs) }\n [result1, result2]\n end\nend\n\nrealtime_output, block_output = Benchmark.capture(:realtime) do\n \"my output\"\nend #=&gt; [7.263e-06, \"my output\"]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T13:39:59.497", "Id": "26781", "Score": "0", "body": "Yeah, I was asking about the generic pattern, the Benchmark.realtime is of course wrapped" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T14:37:36.897", "Id": "28097", "Score": "0", "body": "@synapse: I updated the answer, see the second snippet." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T13:09:37.737", "Id": "16467", "ParentId": "16465", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T12:56:52.293", "Id": "16465", "Score": "2", "Tags": [ "ruby" ], "Title": "Assigning variables in a block" }
16465
<p>I'm binding a handler to the keyup event of all input and textareas in a document:</p> <pre><code>$(document).on('keyup','input,textarea',$.debounce(600, editor.handleGlobalChange)); </code></pre> <p>I don't want the handler to fire on a specific input field. So I want to unbind the keyup event:</p> <pre><code>$('#afield').off('keyup'); </code></pre> <p>However this does not unbind the keyup event, the handler is still called. I assume this is because there is no keyup event bound to the <code>$('#afield')</code> element, the event is just bubbling up to the <code>$(document)</code> where the actual handler is bound.</p> <p>So to stop it triggering I can do the following:</p> <pre><code>$('#afield').on('keyup',function(e) { e.stopImmediatePropagation(); }); </code></pre> <p>This works, but it feels grim, setting a handler to stop another.</p> <p>Is this acceptable or should I just no bind the event in the first place?</p> <p>I could ignore certain classes or a custom data-nokeyup attribute:</p> <pre><code>$(document).on('keyup','input,textarea,not([data-nokeyup]',$.debounce(600, editor.handleGlobalChange)); </code></pre> <p>I have to use a delegated event handler because my inputs and textareas are created after the initialisation code is run. <code>$('input,textarea').keyup(...)</code> would return no elements. <code>$(document).on('keyup','input,textarea',...)</code> catches all keyup events and inspects the event's target element.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T05:33:55.667", "Id": "26824", "Score": "1", "body": "Note that for the data-nokeyup solution the selector string should be `input:not([data-keyup]), textarea:not([data-keyup])`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T11:51:41.693", "Id": "27869", "Score": "1", "body": "Gah, I just realized I also wrote it wrong. It should _really_ be `input:not([data-nokeyup]), textarea:not([data-nokeyup])` :)" } ]
[ { "body": "<p>I'm still not 100% on JQuery yet, but why are you selecting the entire document? Just select the textareas and inputs, then use <code>not()</code> to remove the desired field from the selectors.</p>\n\n<pre><code>$fields = $( 'input' ).add( 'textarea' ).not( '#afield' );\n$fields.on( 'keyup', $.debounce( 600, editor.handleGlobalChange ) );\n</code></pre>\n\n<p><strong>Edit</strong></p>\n\n<p>And apparently there's a <code>keyup()</code> function too, so...</p>\n\n<pre><code>$fields.keyup( $.debounce( 600, editor.handleGlobalChange ) );\n</code></pre>\n\n<p>Also, I'm assuming <code>#afield</code> is an input or textarea, if not, you can skip the not as it should then not be necessary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T14:50:28.373", "Id": "26786", "Score": "1", "body": "FYI, your first line can be shortened to `$('input, textarea').not(...` - jQuery has no probs with multiple selectors" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T14:53:02.153", "Id": "26787", "Score": "0", "body": "Well damn... that makes life so much easier... Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T15:08:03.520", "Id": "26788", "Score": "0", "body": "Because im using a delegate. $('input,textarea') will only bind to elements available at initialization of my code, i'm basically using the updated \"delegate\" function http://api.jquery.com/delegate/ \"bind\", \"live\", \"delegate\" are all rolled into \"on\" now, I have input,textareas that can be created at any point after initial event binding." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T15:17:37.430", "Id": "26790", "Score": "0", "body": "I see, and I see I still have a lot to learn here myself... I'm still using live. Thank you for teaching me something new." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T15:18:30.413", "Id": "26791", "Score": "0", "body": "No problem at all, appreciate your input, I think I may move to using \"not\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-17T00:52:18.487", "Id": "170716", "Score": "0", "body": "Also I believe this would end up adding (potentially) lots of individual handlers, one for each matched element, whereas the delegated model would only add one...if I understand it right." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T14:39:25.400", "Id": "16472", "ParentId": "16466", "Score": "0" } }, { "body": "<p>Well, as far as I can tell, there are 3 ways to deal with this; you've mentioned 2 of them already:</p>\n\n<ol>\n<li>Pre-empt the event for a specific element by adding another handler,</li>\n<li>Scope the event handler differently to exclude a specific element, or</li>\n<li>Do the filtering in the common handler</li>\n</ol>\n\n<p><em>(Edit: All of this is assuming you really want to keep the document-level, event bubble handler, rather than go with mseancole's straightforward solution)</em></p>\n\n<p>The 3rd option would look something like:</p>\n\n<pre><code>$(document).on('keyup','input,textarea', function (event) {\n if( event.type === 'sometype' &amp;&amp; this === someElement ) {\n return;\n }\n $.debounce(600, editor.handleGlobalChange).call(this, event);\n});\n</code></pre>\n\n<p>... which isn't pretty either. Of course you could make it fancier by maintaining a list of event type/element combos to be ignored, rather than hardcoding it, but... eh, seems like a lot of work.</p>\n\n<p>I'd say go with option 1, but perhaps wrap that bit of logic in a function or plugin. I.e. something that would let you say:</p>\n\n<pre><code>$(document).on('keyup','input,textarea',$.debounce(600, editor.handleGlobalChange));\n$('#afield').ignore('keyup');\n</code></pre>\n\n<p><code>.ignore()</code> would then set the event handler that kills the event in its tracks. In your case, you can use <code>stopPropagation</code> instead of <code>stopImmediatePropagation</code>. That way, you can still attach other handlers to that specific element, without <code>ignore</code> eating the event.</p>\n\n<p><em>Edit: Now that I think about it, <code>ignore</code> is a bad name. Too strong a word. <code>dontBubble</code> is accurate, but I'm a stickler for using proper apostrophes, and <code>doNotBubble</code> sounds too aggressive. Maybe <code>popBubble</code>? Too cutesy? Maybe just something like <code>halt</code>? <code>debubble</code>? Yessss, I'm thinking way too much about this :)</em></p>\n\n<p><a href=\"http://jsfiddle.net/R8dyD/3/\" rel=\"nofollow\">Here's a demo</a>. It's in CoffeeScript, because... well, because I like CoffeeScript. The general idea should be clear enough though. Here's the code in case jsfiddle implodes</p>\n\n<pre><code>makeNoise = -&gt;\n $('pre').append \"You typed!&lt;br&gt;\"\n\n# 4-line jQuery plugin\n$.fn.ignore = (eventType) -&gt;\n $(this).each -&gt;\n $(this).on eventType, (event) -&gt;\n event.stopPropagation();\n\n$ -&gt;\n # General event handler for all inputs\n $(document).on 'keyup', 'input', makeNoise\n\n # Exempt a specific element\n $('#quiet').ignore 'keyup'\n\n # Handlers added *directly* to the #quiet element\n # are still called, only the bubbling is silenced.\n $('#quiet').on 'keyup', -&gt;\n alert \"Shhhh!\"\n ​\n</code></pre>\n\n<p>None of this is any different from what you're already doing. It's just wrapped up for convenience.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T15:14:54.883", "Id": "26789", "Score": "0", "body": "As my comment above, I have inputs & textareas dynamically created at any point, None of them are in the dom for the initial binding, so $('input,textarea') will match no elements, I have to use a delegate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T05:28:46.310", "Id": "26823", "Score": "0", "body": "@Rob Not sure if you're clarifying your point and confirming the assumption I made, or if you're thinking I'm using `$('input,textarea')` somewhere. If it's the latter, I'm not: This is all using a delegate. For this to work, though, you have to be able to call `.ignore()` on the elements you add dynamically, when you add them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T11:44:52.637", "Id": "27867", "Score": "0", "body": "I was just clarifying why I'm using a delegate as I missed it form my original question. I'm torn between your example using an `ignore` function or just scoping to ignore in the first place, im inclined to go with your option1, which means im not clustering the initial binding with various specifics. Thanks for your advise" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T14:47:25.147", "Id": "16473", "ParentId": "16466", "Score": "4" } } ]
{ "AcceptedAnswerId": "16473", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T12:59:32.387", "Id": "16466", "Score": "7", "Tags": [ "javascript", "jquery" ], "Title": "Removing jQuery event handler from single element bound by delegate" }
16466
<p>I am trying to get into C stuff, and I thought it would be a good idea to try and implement a circular buffer.</p> <p>I have defined my struct like this:</p> <pre><code>typedef struct { int8_t* buffer; int8_t* buffer_end; int8_t* data_start; int8_t* data_end; int64_t count; int64_t size; } ring_buffer; </code></pre> <p>And the functions:</p> <pre><code>void RB_init(ring_buffer* rb, int64_t size) { rb-&gt;buffer = malloc(sizeof(int8_t) * size); rb-&gt;buffer_end = rb-&gt;buffer + size; rb-&gt;size = size; rb-&gt;data_start = rb-&gt;buffer; rb-&gt;data_end = rb-&gt;buffer; rb-&gt;count = 0; } void RB_free(ring_buffer* rb) { free(rb-&gt;buffer); } bool RB_push(ring_buffer* rb, int8_t data) { if (rb == NULL || rb-&gt;buffer == NULL) return false; *rb-&gt;data_end = data; rb-&gt;data_end++; if (rb-&gt;data_end == rb-&gt;buffer_end) rb-&gt;data_end = rb-&gt;buffer; if (RB_full(rb)) { if ((rb-&gt;data_start + 1) == rb-&gt;buffer_end) rb-&gt;data_start = rb-&gt;buffer; else rb-&gt;data_start++; } else { rb-&gt;count++; } return true; } int8_t RB_pop(ring_buffer* rb) { if (rb == NULL || rb-&gt;buffer == NULL) return false; int8_t data = *rb-&gt;data_start; rb-&gt;data_start++; if (rb-&gt;data_start == rb-&gt;buffer_end) rb-&gt;data_start = rb-&gt;buffer; rb-&gt;count--; return data; } bool RB_full(ring_buffer* rb) { return rb-&gt;count == rb-&gt;size; } </code></pre> <p>I did some testing and it seems to work well. Can you suggest some improvements ?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T14:24:16.930", "Id": "26785", "Score": "0", "body": "`RB_pop` does not check for an empty buffer and has no way of indicating that the buffer is empty." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-27T07:11:36.737", "Id": "28675", "Score": "0", "body": "I would consider it better style to use `size_t` instead of `int64_t` for all sizes and counts of in-memory objects." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-30T12:48:46.760", "Id": "376314", "Score": "0", "body": "Nice example - with the recommend (small) changes provide by SKi and Jamel and some minor tweeking, I used to this create a ring buffer to manage bytes being written to flash. Nice and easy to read." } ]
[ { "body": "<p>This looks nice. It is very readable and is probably fast.</p>\n\n<p>Sometimes ring buffer wrap is implemented by using the following kind of remainder stuff and offsets:</p>\n\n<pre><code>end_offset = (end_offset + 1) % size;\n</code></pre>\n\n<p>But I like your way of doing it without offsets and division.</p>\n\n<p>Some minor findings:</p>\n\n<ol>\n<li><p><code>NULL</code> pointer checks in <code>RB_pop</code> prevents segfaults, but the caller will get a return value of zero. So the caller won't know if zero is an error or a success result.</p>\n\n<pre><code>int8_t RB_pop(ring_buffer* rb)\n{\n if (rb == NULL || rb-&gt;buffer == NULL)\n return false;\n</code></pre></li>\n<li><p><code>RB_pop</code> and <code>RB_push</code> both do the check: <code>rb == NULL</code>. Maybe other functions should do it too.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-14T18:29:36.240", "Id": "20517", "ParentId": "16468", "Score": "7" } }, { "body": "<p>I agree with @User1 about <code>RB_pop()</code> and would like to add on to it:</p>\n\n<p>In order to prevent the function from returning an unexpected return value of <code>false</code>, you should make the function <code>void</code> and have a second parameter <code>data</code>. This will also allow you to <code>return</code> early if the first conditional statement is <code>false</code>.</p>\n\n<pre><code>void RB_pop(ring_buffer* rb, int8_t* data)\n{\n if (rb == NULL || rb-&gt;buffer == NULL)\n return;\n\n // update data parameter...\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-12T00:01:21.477", "Id": "46977", "ParentId": "16468", "Score": "7" } }, { "body": "<p>you didn't check count in pop function. if buffer is empty you will return garbage and also count will now be negative.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T12:01:54.157", "Id": "402888", "Score": "2", "body": "We prefer answers that make new observations; your answer merely duplicates parts of existing answers, and doesn't add any value here. Please find something else within the code that can be improved!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-28T11:53:52.620", "Id": "208603", "ParentId": "16468", "Score": "0" } } ]
{ "AcceptedAnswerId": "20517", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T13:13:02.070", "Id": "16468", "Score": "12", "Tags": [ "c", "circular-list" ], "Title": "Circular RingBuffer" }
16468
<p>I'm trying to reproduce the Google Schemer (schemer.com) effect they use with their buttons for indicating a user wanting to do something/already doing something. I more or less got it replicated but it seems like the amount of code is a bit much.</p> <p><a href="http://jsfiddle.net/m0nd/YzEAu/" rel="nofollow">JSFiddle</a></p> <p>Does it seem like too much code for something that seems to be so "simple"?</p> <pre><code>// WTD object var userWTD = { numTimesWtd: 0, numTimesAdt: 0, wantsToDoIt: false, alreadyDidIt: false, }; // Update WTD text when user clicks the button/link $('.btn-wtd').on('click', function() { // User wants to undo their WTD if ($(this).hasClass('btn-wtd-active')) { $(this).removeClass('btn-wtd-active btn-info'); // Decrement # times user wants to do it if (userWTD.numTimesWtd &gt; 0)--userWTD.numTimesWtd; else userWTD.numTimesWtd = 0; // user has not wanted to do it if (userWTD.numTimesWtd == 0) { // ...and already did it once if (userWTD.numTimesAdt == 1) { $('.btn-adt').addClass('btn-adt-active'); $('.want-again-text, .adt-text').show(); $('.unwant-text, .want-text, .done-it-text, .done-again-text').hide(); } // ...and user has not done it else { $('.btn-adt').removeClass('btn-adt-active'); $('.want-text, .adt-text').show(); $('.unwant-text, .want-again-text, .done-it-text, .done-again-text').hide(); } } // user wanted to do it once else if (userWTD.numTimesWtd == 1) { // ...and has not already done it if (userWTD.numTimesAdt == 0) { $('.btn-adt').removeClass('btn-adt-active'); $('.want-text, .done-it-text').show(); $('.want-again-text, .unwant-text, .adt-text, .done-again-text').hide(); } // ...and has done it at least once else { $('.btn-adt').addClass('btn-adt-active'); $('.want-again-text').show(); $('.want-text, .unwant-text, .adt-text').hide(); // user already did it once if (userWTD.numTimesAdt == 1) { $('.done-it-text').show(); $('.done-again-text').hide(); } // user already did it &gt; once else { $('.done-again-text').show(); $('.done-it-text').hide(); } } } // user wanted to do it &gt; once else { $('.btn-adt').addClass('btn-adt-active'); $('.want-again-text').show(); $('.want-text, .unwant-text, .adt-text').hide(); // ...and already did it once if (userWTD.numTimesWtd == 2 &amp;&amp; userWTD.numTimesAdt == 1) { $('.done-it-text').show(); $('.done-again-text').hide(); } // ...and already did it &gt; once else { $('.done-again-text').show(); $('.done-it-text').hide(); } } } else { // User wants to do something // Increment # times user wants to do it ++userWTD.numTimesWtd; // ADT button was previously clicked // i.e. this button is now 'Want to do it *again*' if ($('.btn-adt').hasClass('btn-adt-active')) { $(this).addClass('btn-wtd-active btn-info'); $('.btn-adt').removeClass('btn-adt-active'); // user has done it at least once if (userWTD.numTimesWtd &gt; 0) { // user only wanted to do it once if (userWTD.numTimesWtd == 1) { // user already did it once if (userWTD.numTimesAdt &gt; 0) { $('.want-again-text, .done-again-text').show(); $('.want-text, .adt-text, .done-it-text').hide(); } // user already did it else { $('.want-again-text, .done-it-text').show(); $('.want-text, .adt-text, .done-again-text').hide(); } } else { // user wanted to do it more than once $('.want-again-text, .done-again-text').show(); $('.want-text, .adt-text, .done-it-text').hide(); } } } else { // ADT button was NOT previously clicked $(this).addClass('btn-wtd-active btn-info'); // user wanted to do it once and has not already done it if (userWTD.numTimesWtd == 1 &amp;&amp; userWTD.numTimesAdt == 0) { $('.want-text, .done-it-text').show(); $('.want-again-text, .adt-text, .done-again-text').hide(); } // user wanted to do it &gt; once and has already done it else if (userWTD.numTimesWtd &gt; 1 &amp;&amp; userWTD.numTimesAdt &gt; 0) { $('.want-again-text, .done-again-text').show(); $('.want-text, .adt-text, .done-it-text').hide(); } } } console.dir(userWTD); }); // Update ADT (Already Did This) text when user clicks the button $('.btn-adt').on('click', function() { // User wants to Undo their 'already done this' if ($(this).hasClass('btn-adt-active')) { // Adjust WTD object properties if (userWTD.numTimesAdt &gt; 0)--userWTD.numTimesAdt; else userWTD.numTimesAdt = 0; $(this).removeClass('btn-adt-active'); // user has not yet done it if (userWTD.numTimesAdt == 0) { // ...and user has wanted to do it once if (userWTD.numTimesWtd == 1) { $('.btn-wtd').addClass('btn-wtd-active btn-info'); $('.want-text, .done-it-text').show(); $('.want-again-text, .unwant-text, .adt-text, .done-again-text').hide(); } // ...and user has not wanted to do it else { $('.btn-wtd').removeClass('btn-wtd-active btn-info'); $('.want-text, .adt-text').show(); $('.want-again-text, .unwant-text, .done-it-text, .done-again-text').hide(); } } // user already did it once else if (userWTD.numTimesAdt == 1) { // ...and wanted to do it once if (userWTD.numTimesWtd &gt;= 1) { $('.btn-wtd').addClass('btn-wtd-active btn-info'); $('.want-again-text, .done-again-text').show(); $('.want-text, .adt-text, .done-it-text').hide(); } } // user already did it &gt; once else if (userWTD.numTimesAdt &gt; 1) { $('.btn-wtd').addClass('btn-wtd-active btn-info'); $('.want-again-text, .done-again-text').show(); $('.want-text, .unwant-text, .adt-text, .done-it-text').hide(); // ...and wanted to do it at least once } } // User (already) did it else { // Increment # times user did it ++userWTD.numTimesAdt; userWTD.alreadyDidIt = true; $(this).addClass('btn-adt-active'); if ($('.btn-wtd').hasClass('btn-wtd-active')) { $('.btn-wtd').removeClass('btn-wtd-active btn-info'); } // User has done it at least once if (userWTD.numTimesAdt &gt; 0) { // user did it exactly once if (userWTD.numTimesAdt == 1) { $('.want-again-text').show(); $('.want-text, .done-again-text').hide(); // user has not wanted to do it if (userWTD.numTimesWtd == 0) { $('.adt-text').show(); $('.done-it-text').hide(); } // user has wanted to do it once else if (userWTD.numTimesWtd == 1) { $('.done-it-text').show(); $('.adt-text').hide(); } } else { // user did it more than once $('.want-again-text, .done-again-text').show(); $('.want-text, .adt-text, .done-it-text').hide(); } } $(this).prop('title', 'Undo'); } //$(this).toggleClass('btn-adt-active'); console.dir(userWTD); }); $('.btn-wtd').hover(function() { // user indicated they wtd something if ($(this).hasClass('btn-wtd-active')) { if ((userWTD.numTimesWtd &gt; 0 &amp;&amp; userWTD.numTimesAdt &gt; 0) || (userWTD.numTimesAdt &gt; 0 &amp;&amp; userWTD.numTimesWtd &gt;= 0)) $('.want-again-text').hide(); else $('.want-text').hide(); $('.unwant-text').show(); } }, function() { $('.unwant-text').hide(); if ((userWTD.numTimesWtd &gt; 0 &amp;&amp; userWTD.numTimesAdt &gt; 0) || (userWTD.numTimesAdt &gt; 0 &amp;&amp; userWTD.numTimesWtd &gt;= 0)) $('.want-again-text').show(); else $('.want-text').show(); }) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T17:05:54.463", "Id": "26794", "Score": "0", "body": "The HTML and CSS seem fine at first glance, but the JS is indeed far too long and needs to be refactored and improved." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T17:14:13.860", "Id": "26795", "Score": "0", "body": "Please always post your code inline in the question *as stated in the [faq]*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T17:25:44.377", "Id": "26797", "Score": "0", "body": "Ok thanks, and I also added the code inline." } ]
[ { "body": "<p>If we consider these two buttons a state machine, we see that there are six simple states (not including hover).</p>\n\n<ol>\n<li>\"want\" / \"did\"</li>\n<li>\"want again\" / \"did\" (active)</li>\n<li>\"want\" (active) / \"done\"</li>\n<li>\"want again\" / \"done\" (active)</li>\n<li>\"want again\" (active) / \"done again\"</li>\n<li>\"want again\" / \"done again\" (active)</li>\n</ol>\n\n<p>The path is one of these two options. In the first path, done is clicked first. In the other, want is clicked first.</p>\n\n<pre><code>1--2-----5--6\n1--3--4--5--6\n</code></pre>\n\n<p>Acknowledging the state machine, look at the \"want\"/\"want again\" button. The text will always say <strong>\"I want to do it again\"</strong> after the done button has clicked. Essentially we can boil it down to this:</p>\n\n<pre><code>$('.want-text').toggle(done &lt;= 0)\n$('.want-again-text').toggle(done &gt; 0)\n</code></pre>\n\n<p>Moving on to the \"did\"/\"done\"/\"done again\" button is a little trickier. <strong>\"I already did it\"</strong> will be visible so long as the want count is 0, and <strong>\"Done it again!\"</strong> will be visible after the want count is 2 or greater, but \"Done it!\" is more complex since it only shows up on one of the state machine paths (step 3/4). It turns out it is visible when the want count is 1 <em>and</em> we did not click the done button first <em>and</em> the done count is 0 or 1. This all leads to this block of code:</p>\n\n<pre><code> var didText = false, doneText = false, againText = false\n if(want &lt;= 0) \n didText = true\n else if (want === 1 &amp;&amp; !doneFirst &amp;&amp; done &lt;= 1) \n doneText = true\n else \n againText = true \n\n $('.adt-text').toggle(didText)\n $('.done-it-text').toggle(doneText)\n $('.done-again-text').toggle(againText)\n</code></pre>\n\n<p>Finally, we have to consider when to make each button active. If we clicked the done button first, then done will be active when the done count is greater than the want count. The opposite is true if the want button was clicked first. As a special case, no button is active if the\nwant count and done count are zero.</p>\n\n<pre><code> var wantActive, doneActive;\n if (want === 0 &amp;&amp; done === 0){\n wantActive = doneActive = false\n } else {\n doneActive = (doneFirst ? done &gt; want : done === want)\n wantActive = !doneActive\n }\n $('.btn-wtd').toggleClass('btn-wtd-active btn-info', wantActive)\n $('.btn-adt').toggleClass('btn-adt-active', doneActive)\n .prop('title', doneActive ? 'Undo' : '');\n</code></pre>\n\n<p>Once we have all of that, we can rip out the entirety of the click functions, replacing them a simple <code>redraw</code> function (containing the previous code blocks). Since we are now concerned about clicking the done button first, a little code is needed to set that variable.</p>\n\n<p>One final note: the <code>userWTD</code> object was not needed, so I removed it and renamed the <code>numTimesWtd</code>/<code>numTimesAdt</code> variables.</p>\n\n<p>Working Fiddle: <a href=\"http://jsfiddle.net/danthegoodman/nXseg/\" rel=\"nofollow\">http://jsfiddle.net/danthegoodman/nXseg/</a></p>\n\n<pre><code>$(function() {\n var want = 0\n var done = 0\n var doneFirst = false\n\n $('.btn-wtd').on('click', function() {\n if ( $(this).hasClass('btn-wtd-active') ){\n want -= 1;\n if (want &lt;= 0) want = 0;\n } else {\n want += 1;\n }\n\n redraw();\n });\n\n $('.btn-adt').on('click', function() {\n if ( $(this).hasClass('btn-adt-active') ){\n done -= 1;\n if (done &lt; 0) done = 0;\n if (want === 0 &amp;&amp; done === 0) doneFirst = false;\n } else {\n if(want === 0 &amp;&amp; done === 0) doneFirst = true;\n done += 1;\n }\n\n redraw();\n });\n\n $('.btn-wtd').hover(function() {\n // user indicated they wtd something\n if ($(this).hasClass('btn-wtd-active')) {\n $('.want-again-text').hide();\n $('.want-text').hide();\n $('.unwant-text').show();\n }\n }, function() {\n redrawWantText()\n })\n\n function redraw(){\n var wantActive, doneActive;\n\n if (want === 0 &amp;&amp; done === 0){\n wantActive = doneActive = false\n } else {\n doneActive = (doneFirst ? done &gt; want : done === want)\n wantActive = !doneActive\n }\n $('.btn-wtd').toggleClass('btn-wtd-active btn-info', wantActive)\n $('.btn-adt').toggleClass('btn-adt-active', doneActive)\n .prop('title', doneActive ? 'Undo' : '');\n\n redrawWantText()\n redrawDoneText()\n }\n\n function redrawWantText(){\n $('.unwant-text').hide();\n $('.want-text').toggle(done &lt;= 0)\n $('.want-again-text').toggle(done &gt; 0)\n }\n\n function redrawDoneText(){\n var didText = false, doneText = false, againText = false\n\n if(want &lt;= 0) didText = true\n else if (want === 1 &amp;&amp; !doneFirst &amp;&amp; done &lt;= 1) doneText = true\n else againText = true \n\n $('.adt-text').toggle(didText)\n $('.done-it-text').toggle(doneText)\n $('.done-again-text').toggle(againText)\n }\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T03:30:10.953", "Id": "27906", "Score": "0", "body": "wow, your insight on this was seriously great, some of the points you mentioned I kind of touched on a bit but I didn't go as deep as you did, thanks so much, this really opened up my mind to the problem some more. As a side note I think I may also add a counter text next to the 'want' button to provide a reminder of where you're at in terms of wanting/doing." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T23:19:09.590", "Id": "16490", "ParentId": "16476", "Score": "1" } } ]
{ "AcceptedAnswerId": "16490", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T16:49:25.777", "Id": "16476", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Reproducing Google Schemer buttons effect" }
16476
<p>For questions about cryptographic concepts and protocols that do not involve a code review, consult <a href="https://crypto.stackexchange.com/help/on-topic">Cryptography SE</a>.</p> <p>For trivial ciphers, <a href="/questions/tagged/caesar-cipher" class="post-tag" title="show questions tagged &#39;caesar-cipher&#39;" rel="tag">caesar-cipher</a> may be a more appropriate tag.</p> <hr> <p>Cryptography (from the Greek for "secret/hidden writing") is the practice and study of techniques for secure communication and processing in the presence of third parties. There are general three properties that we associate with secure communication:</p> <ul> <li><strong>Confidentiality:</strong> some information must be stored or transferred without permitting unauthorized entities to read it;</li> <li><strong>Integrity:</strong> some information must be stored or transferred without allowing any alteration by an unauthorized entity to go unnoticed;</li> <li><strong>Authenticity:</strong> some information must be stored or transferred in such a way that the originator of the information can be verified, in a way which unauthorized entities cannot falsify.</li> </ul> <p>"Entities" are persons, roles or systems which are supposed to be distinct from each other according to some definition. Cryptography operates in the logical world of computers, from which the physical world is out of reach; anybody can buy a PC, so what distinguishes one user on a network from another (as seen through a network or any other communication protocol) is what that user knows. Cryptography calls such knowledge a <em>secret</em> or <em>key</em>: this is a piece of secret data, which is used as parameter to a cryptographic algorithm that implements a cryptographic property with regards to the key.</p> <p>For instance, <em>symmetric encryption</em> is about transforming some data (possibly a huge file), using a (normally short) key, into an encrypted form which shows no readable structure anymore, but such that the transformation can be reversed (recovering the original data from the encrypted form) if the encryption key is known. In a way, symmetric encryption <em>concentrates</em> confidentiality into the key, which can be short enough to be manageable (e.g. the key might be memorized by a human being, in which case it is called a <em>password</em>).</p> <p>The cryptographic algorithms themselves are public, if only because nobody can really tell "how much" a given algorithm is secret, since algorithms are often implemented as software or hardware systems which are duplicated into many instances, and the cost of reverse engineering is hard to estimate. A <em>cryptosystem</em> (combination of an algorithm and its key) is then split into the algorithm, which is embodied as an implementation, and a key, for which security can be quantified (e.g. by counting the number of possible keys of a given length).</p> <p>Cryptography covers the science of designing cryptographic algorithms (<em>cryptology</em>) and of trying to break them (<em>cryptanalysis</em>); it also encompasses the techniques used to apply the algorithms in various situations, in particular implementation as software, and the related subjects (such as performance issues). Some algorithms consist in the assembly of several sub-algorithms in order to obtain higher level properties (e.g. "a bidirectional tunnel for confidential data with verified integrity and mutual authentication"); they are then called <em>protocols</em>.</p> <p>Commonly used cryptographic algorithms and protocols include, among others:</p> <ul> <li><strong>Symmetric encryption:</strong> <a href="https://en.wikipedia.org/wiki/Triple_DES" rel="nofollow">3DES</a>, <a href="/questions/tagged/aes" class="post-tag" title="show questions tagged &#39;aes&#39;" rel="tag">aes</a>, <a href="https://en.wikipedia.org/wiki/RC4" rel="nofollow">RC4</a>, <a href="https://en.wikipedia.org/wiki/Blowfish_%28cipher%29" rel="nofollow">Blowfish</a></li> <li><strong>Hash functions:</strong> <a href="https://en.wikipedia.org/wiki/MD5" rel="nofollow">MD5</a>, <a href="https://en.wikipedia.org/wiki/SHA-1" rel="nofollow">SHA-1</a>, <a href="https://en.wikipedia.org/wiki/SHA-2" rel="nofollow">SHA-2</a> (includes SHA-256 and SHA-512)</li> <li><strong>Asymmetric encryption:</strong> <a href="https://en.wikipedia.org/wiki/RSA" rel="nofollow">RSA</a></li> <li><strong>Digital signatures:</strong> <a href="https://en.wikipedia.org/wiki/RSA" rel="nofollow">RSA</a> (similar, but not identical to, the RSA for encryption), <a href="https://en.wikipedia.org/wiki/Digital_Signature_Algorithm" rel="nofollow">DSA</a> (as part of the "DSS" standard), <a href="https://en.wikipedia.org/wiki/Elliptic_Curve_DSA" rel="nofollow">ECDSA</a></li> <li><strong>Data tunneling:</strong> <a href="https://tools.ietf.org/html/rfc5246" rel="nofollow">TLS</a> (formerly known as <a href="/questions/tagged/ssl" class="post-tag" title="show questions tagged &#39;ssl&#39;" rel="tag">ssl</a>; when used to convey HTTP requests, the result is known as <a href="/questions/tagged/https" class="post-tag" title="show questions tagged &#39;https&#39;" rel="tag">https</a>), <a href="/questions/tagged/ssh" class="post-tag" title="show questions tagged &#39;ssh&#39;" rel="tag">ssh</a>, <a href="https://en.wikipedia.org/wiki/IPsec" rel="nofollow">IPsec</a></li> <li><strong>Encrypted and/or signed emails:</strong> <a href="https://tools.ietf.org/html/rfc4880" rel="nofollow">OpenPGP</a> (standard protocol derived from the original <a href="https://en.wikipedia.org/wiki/Pretty_Good_Privacy" rel="nofollow">PGP</a> software), <a href="https://en.wikipedia.org/wiki/S/MIME" rel="nofollow">S/MIME</a></li> <li><strong>Certificates:</strong> <a href="https://tools.ietf.org/html/rfc5280" rel="nofollow">X.509</a>, <a href="https://tools.ietf.org/html/rfc4880" rel="nofollow">OpenPGP</a> (certificates are about binding identities to public keys, which are themselves used in asymmetric encryption and digital signatures)</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T17:24:16.733", "Id": "16478", "Score": "0", "Tags": null, "Title": null }
16478
Questions relating to cryptographic topics such as encryption/decryption and hashing. (Not for use with trivial ciphers.)
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T17:24:16.733", "Id": "16479", "Score": "0", "Tags": null, "Title": null }
16479
<p>I have this class that has these two methods that are so closely related to the each other. I do not want to pass the flags so I kept them separate. I was wondering if there is a way to rewrite it so that I do not have to repeat so closely!</p> <pre><code> class Test extends Controller { public static function nonFormattedData($param) { $arr = array(); if (is_array($param)) { $i = 0; $sql = " select * from table1 where "; if (isset($param['startDate'])) { $sql .= " date_created between ? AND ?"; $arr[] = $param['startDate']; $arr[] = $param['endDate']; $i++; } if (isset($param['amount']) &amp;&amp; !empty($param['amount'])) { if ($i &gt; 0) $sql .= " AND "; $sql .= " balance= ?"; $arr[] = $param['amount']; $i++; } if (isset($param) &amp;&amp; !empty($param['amount'])) { if ($i &gt; 0) $sql .= " AND "; $sql .= " balance= ?"; $arr[] = $param['amount']; $i++; } if (isset($param['createdBy']) &amp;&amp; !empty($param['createdBy'])) { if ($i &gt; 0) $sql .= " AND "; $sql .= " column2 like '%Created By: " . $param['createdBy'] . "%'"; } $sql .= ' group by id.table1 '; $rs = Query::RunQuery($sql, $arr); foreach ($rs as $row) { $records = new Account(); $results[] = $records; } return $results; } } public static function formattedData($serArray, $orderBy = "giftcardaccount_id desc", $offset = 0, $limit = 10) { $arr = array(); if (is_array($param)) { $i = 0; $sql = " select * from table1 where "; if (isset($param['startDate'])) { $sql .= " date_created between ? AND ?"; $arr[] = $param['startDate']; $arr[] = $param['endDate']; $i++; } if (isset($param['amount']) &amp;&amp; !empty($param['amount'])) { if ($i &gt; 0) $sql .= " AND "; $sql .= " balance= ?"; $arr[] = $param['amount']; $i++; } if (isset($param) &amp;&amp; !empty($param['amount'])) { if ($i &gt; 0) $sql .= " AND "; $sql .= " balance= ?"; $arr[] = $param['amount']; $i++; } if (isset($param['createdBy']) &amp;&amp; !empty($param['createdBy'])) { if ($i &gt; 0) $sql .= " AND "; $sql .= " column2 like '%Created By: " . $param['createdBy'] . "%'"; } $sql .= ' group by id.table1 '; $rs = Query::RunQuery($sql, $arr); return array("data" =&gt; $rs); } } } </code></pre>
[]
[ { "body": "<p>You have two methods, one is nonFormattedData and other one is formattedData.\nI don't see the arguments for formattedData are being used. </p>\n\n<p>The difference between these two methods are how the result is returned. formatdata method returns <code>array(\"data\" => $rs)</code> and nonFormatData does a foreach on the <code>$rs</code> and returns array of results </p>\n\n<p><code></p>\n\n<pre><code>foreach ($rs as $row) {\n $records = new Account();\n $results[] = $records;\n}\n</code></pre>\n\n<p></code></p>\n\n<p>If this is the only difference then there is no point of duplicating the code. One option is to make client code deal with how it wants data or create a separate method which will take query result set and formats the required output.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T18:03:24.567", "Id": "16481", "ParentId": "16480", "Score": "2" } }, { "body": "<p>Just judging by the size you can tell that this one method is doing entirely too much. The Single Responsibility Principle states that a method/function should be responsible for one thing to the exclusion of all others. It can request other methods/functions to help it, but it should only be concerned with its purpose, which should be evident by its name.</p>\n\n<p>So, the first thing I would say to do is break this up into even more methods first. The how should be pretty obvious in most cases. In this case, however, it may not be, so let's take a look at what you are doing to get an idea of how we should break this up.</p>\n\n<p>Each if statement sets up an additional part of this growing SQL statement. If you look closely at each of these blocks, you may begin to notice a pattern. When a pattern arises we know that we can apply the \"Don't Repeat Yourself\" (DRY) Principle to it so that it can be reused. So our pattern here is to append a SQL statement, add to an array, and finally increment a counter. Sounds simple enough.</p>\n\n<pre><code>private\n $sql = '',\n $arr = array()\n;\n\n//constructor, etc...\n\nprivate function append( $sql, $params ) {\n if( strlen( $this-&gt;sql ) ) {\n $sql = ' AND ' . $sql;\n }\n\n $this-&gt;sql .= $sql;\n $this-&gt;arr = array_merge( $this-&gt;arr, $params );\n}\n</code></pre>\n\n<p>So, you may notice that we are doing a few things differently here. First, we add some new properties to our class. The <code>$sql</code> and <code>$arr</code> properties take the place of their respective variables. This is so that our new methods can communicate with each other. Next, we removed the counter <code>$i</code>. The counter is pretty much useless, even in its current form. If we remove the initial value of <code>$sql</code> then we can just check the string's length. If it is empty then of course we don't prepend an <code>AND</code>, but if it isn't then we should. Don't worry, we'll prepend the initial value when we are done. The last thing we do is merge our arrays. Since we are using a standard sequential array there should be no problems here, we just have to be sure to append everything in the right order, which we've just done. So, now to use it.</p>\n\n<pre><code>public function nonFormattedData( $param ) {\n if( ! is_array( $param ) ) {\n return FALSE;\n }\n\n if( isset( $param[ 'startDate' ] ) ) {\n $this-&gt;append( ' date_created between ? AND ?', array(\n $param[ 'startDate' ],\n $param[ 'endDate' ]\n ) );\n }\n\n //etc...\n\n $this-&gt;sql = '\n select *\n from table1\n where\n ' . $this-&gt;sql . '\n group by id.table 1 '\n ;\n\n //etc...\n}\n</code></pre>\n\n<p>So, there's a few new things to cover here as well. The first is the removal of the static keyword. Static methods and properties are counter to OOP. For the most part you will probably never need them. But specifically in this case they prevent us from using our new method and properties. There are ways around this, but again, that is counter to OOP. The next thing I did was reversed your initial if statement and returned early. This is a good habit to get in to. First it reduces the amount of indentation, meaning we are no longer violating the Arrow Anti-Pattern (even as slight as the violation was), and second it reduces the amount of processing necessary for PHP to determine that it doesn't need to do anything. Not much mind, but still more efficient. The next if statement should look pretty familiar, its exactly the same, but the inner block is different. Here we are using the new method we just created. This should be pretty self-explanatory. Add the custom SQL and pass in the appropriate parameters. Repeat for each if statement. Finally we come to our new SQL statement. I promised you we'd get back to that initial value. Well, here it is, combined with appending the final value, resulting in our complete SQL statement, ready to use. The rest is the same.</p>\n\n<p>Now, we've cleaned up this first method and, as you've already mentioned, the second method is pretty similar. If we apply the above to it it will be better, but we can still do more. As sky py has pointed out, the only difference is that foreach loop in the first method. The second method returns the results the first uses to loop over, or something VERY similar. So the obvious move here would be to call the second method from the first, and use the return to loop from. So our new first method should look like this.</p>\n\n<pre><code>public function nonFormattedData( $param ) {\n $results = array();\n\n $rs = $this-&gt;formattedData( $param );\n foreach( $rs[ 'data' ] AS $row ) {\n $records = new Account();\n $results[] = $records;\n }\n\n return $results;\n}\n</code></pre>\n\n<p>The only thing new here is that I initialized the <code>$results</code> array, which you should always do before trying to manipulate it. There's a couple of reasons for this. The first, and most obvious, is what happens if <code>$rs[ 'data' ]</code> is empty? The loop never happens and <code>$results</code> is never defined. Resulting in an undefined error and a potential crash. The not so obvious is what would happen if <code>$results</code> was accidentally set somewhere previously, or god forbid, is a global. If that variable happens to be an array you'll just get some funny results. But if it happens to be a string you will be modifying the string using string-array notation, which will definitely cause problems.</p>\n\n<p>So this answers your question, but still isn't as efficient as it could be. To be the most efficient we will want to limit how many times we query the server. Assuming that we always call the second method before the first, then we can have the second method save its results as a new property and access that property in the first method instead of querying the server again. Following that logic we can do the same thing to the first method and then use getters to return the appropriate property instead of calling those methods again and again.</p>\n\n<p>I hope this helps. If you have any questions or need some clarification, don't hesitate to ask.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T19:39:51.703", "Id": "16482", "ParentId": "16480", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T17:27:45.357", "Id": "16480", "Score": "2", "Tags": [ "php", "php5", "cakephp" ], "Title": "methods in the class so close in what they do" }
16480
<p>I'm pretty new to JQuery, maybe a week's worth of experience, but I'm having a lot of fun so far. One of the things I thought I would give a shot is attempting to implement a custom CMS for my current project. And it's going fairly well. So well in fact, that I thought I would start adding some nifty little features and finalizing it. I mean, why not, I'm learning anyways and what better way than to apply it to an actual project that might benefit from it.</p> <p>One of the features I thought I'd add would be a dynamic edit toolbar. It uses a delegate to perform event functions on a specific div. Specifically, when the <code>#edit</code>able section is in focus it will show the toolbar, and on blur it will hide it.</p> <pre><code>$( '#content' ).on( { focus : function() { if( $( this ).prop( 'contentEditable' ) ) { $( '#toolbar' ).show(); //thinking there might be a way to reuse $( '#toolbar' ) below //within this pseudo scope } }, blur : function() { $( '#toolbar' ).hide(); } }, '#edit' ); </code></pre> <p>Pretty neat. I just found this syntax and have been playing with it for a few hours now. Beats having to manually type out a new delegate each time.</p> <p>This second one does something pretty similar, but it focuses on a single event where the functionality will vary depending on which element is clicked. For instance, if <code>addImage</code> is clicked I want it to add an image, if <code>bold</code> I want it to bold, etc... It's a little more complex than that, but this gets the idea across. As you can see, the syntax is different (it's all one function and uses a switch), and no amount of tweaking or searching has helped me to discover if a better way actually exists, or if this is the best already.</p> <pre><code>$( '#toolbar' ).on( 'click', 'a', function() { switch( $( this ).parent().prop( 'id' ) ) { case 'addImage' : addImage(); break; case 'bold' : bold(); break; case 'italics' : italics(); break; case 'underline' : underline(); break; } return false; } ); </code></pre> <p>I do have an alternative, but I find the one above a little more attractive. Mostly just because there is less indentation, though I guess I could fix that...</p> <pre><code>$( '#toolbar' ).on( { click : function() { //import above switch statement here } }, 'a' ); </code></pre> <p>Here are my questions:</p> <ul> <li>Is there a better way to do this?</li> <li>Am I abusing the selectors/delegates?</li> <li>Any other general observations or improvements would be appreciated as well.</li> </ul> <p><strong>UPDATE</strong></p> <p>Thank you Flambino. Your first example reminded me of something we call variable-functions in PHP. In case you are unfamiliar with the term, these are variables that serve as a textual representation of a function and can be used to call that function by adding parenthesis. Example:</p> <pre><code>function test1() { echo 'test1'; } function test2() { echo 'test2'; } $test1 = 'test2'; $test2 = 'test1'; $test1();//variable-function calling test2() $test2();//variable-function calling test1() </code></pre> <p>They are not well liked in the PHP community due to their lack of legibility and potential security risk. I know JS isn't going to be as concerned with the security bit, seeing as its front-end and completely visible and manipulable client-side, but lack of legibility looks like it might still be a potential problem. Though, because of the object clarifying this purpose, this does not appear to be as big an issue either. Are these not equally disliked in JS?</p> <p>Here is my implementation using custom events.</p> <pre><code>var $toolbar = $( '#toolbar' ); $toolbar.on( 'click', 'a', function() { var method = $( this ).parent().prop( 'id' ); $toolbar.trigger( method ); return false; } ); $toolbar.on( { addImage : function() { addImage(); }, bold : function() { bold(); }, //etc... } ); </code></pre> <p>When implementing custom events I noticed that you are namespacing them with <code>format:</code>. In my implementation you may have noticed that I neglected to add this. This is because namespacing in this manner would prevent me from using an event object. I played around with this and determined that I could use <code>format_</code> instead, but this just seemed awkward. Is this violating good practice or something? I can see the benefit, but if they are bound to a specific container, why would namespacing be necessary?</p> <p>I tried combining the two <code>.on()</code> blocks, but because the first uses the "a" classifier it limits those events to the anchor tags, which means I would have to explicitly trigger the events like this:</p> <pre><code>$( '#toolbar &gt; a' ).trigger( method ); </code></pre> <p>Is there a way around this? I'm still toying with this, but haven't found any promising leads yet. I understand from your suggestion about semantics this won't be an issue here anymore, but I've also been applying this to other areas, and in those this looks like its still an issue.</p> <p>Finally, I am still looking in to your <code>data-*</code> suggestion. It looks promising, not just here, but in other places as well.</p> <p>BTW: why are you using <code>.attr()</code>? Wasn't that deprecated as of 1.6 in favor of <code>.prop()</code>? Or is there some reason it should be used here over <code>prop()</code>?</p>
[]
[ { "body": "<p>I'd probably make an object with the various formatting functions, like:</p>\n\n<pre><code>var formatting = {\n addImage: function () { ... },\n bold: function () { ... },\n ...\n};\n</code></pre>\n\n<p>And then have an event handler like:</p>\n\n<pre><code>$( '#toolbar' ).on( 'click', 'a', function() {\n var method = $(this).parent().prop('id');\n if( method in formatting ) {\n formatting[method](); // call the formatting method\n }\n return false;\n});\n</code></pre>\n\n<p>Then you can add/remove formatting methods without having to manually change a <code>switch</code> statement each time.</p>\n\n<p>I'd probably also use a <code>data-*</code> attribute instead of <code>id</code> to store the name of the formatting method to call. It's a bit of extra markup, but it's more clear, I think:</p>\n\n<pre><code>&lt;a href=\"#\" id=\"boldButton\" data-formatting=\"bold\"&gt;Bold&lt;/a&gt;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>var method = $(this).parent().attr('data-formatting');\n</code></pre>\n\n<p>That way, the ID can be whatever without tripping up the actual function of the link. (You can also use <code>.data('formatting')</code>, but I prefer being explicit about it being an attribute, whereas <code>.data</code> doesn't necessarily refer to markup).</p>\n\n<p>Alternatively, you could make some custom events:</p>\n\n<pre><code>var toolbar = $('#toolbar');\ntoolbar.on( 'click', 'a', function() {\n var method = $(this).parent().attr('data-formatting');\n toolbar.trigger('format:' + method);\n return false;\n});\n</code></pre>\n\n<p>Then you can listen for those events elsewhere</p>\n\n<pre><code>$('#toolbar').on('format:bold', function () {\n // make stuff bold\n});\n</code></pre>\n\n<p>It's a bit of a roundabout way of doing it, but you get the flexibility of being able to add/remove event handlers as you please. (By the way, it might make more sense semantically to trigger the event on the editable element instead of the toolbar).</p>\n\n<hr>\n\n<p><strong>Update</strong></p>\n\n<p>In response to the updated question:</p>\n\n<blockquote>\n <p>Your first example reminded me of something we call variable-functions in PHP [...] Are these not equally disliked in JS?</p>\n</blockquote>\n\n<p>Nope - as you say, the security considerations aren't the same. Besides, where variable-functions in PHP do seem kinda hack'y and going against the grain, JS has always had a different concept of what a \"function\" is - namely that a function is itself an object and thus a property/variable. In some ways it's like if you were using <code>createFunction()</code> and <code>callUserFuncArray()</code> for everything in PHP and passing functions around (not a great comparison, but those features are PHP's attempt to mimic some of what you find in a language like JS).<br>\nThe second part of the equation is JS's way of providing access to object properties, namely that you can use either the dot-notation, or the bracket notation. These are all the same:</p>\n\n<pre><code>window.alert(\"Hello, world\");\nwindow[\"alert\"](\"Hello, world\");\nvar name = \"alert\";\nwindow[name](\"Hello, world\");\n\n// window is the global obj, and thus implicit, so you can also do:\nalert(\"Hello, world\");\n// but, due to the vagaries of the syntax, you can't do\n[\"alert\"](\"hello, world\");\n// because [\"alert\"] is interpreted as an array literal\n</code></pre>\n\n<blockquote>\n <p>When implementing custom events I noticed that you are namespacing them with <code>format:</code>. In my implementation you may have noticed that I neglected to add this. This is because namespacing in this manner would prevent me from using an event object</p>\n</blockquote>\n\n<p>Actually, no. Because of the bracket notation, properties can in fact have otherwise \"illegal\" names - and a function is a property too. I.e. you can declare things like:</p>\n\n<pre><code>var obj = {\n \"say hello!\": function () {...}\n};\nobj[\"say bye!\"] = function () {...}\n</code></pre>\n\n<p>And call it with <code>obj[\"say hello\"]()</code>. You may notice that this looks like JSON, with its quoted keys, and yup, it does. While JSON can't/won't encode functions, the <code>\"key\": value</code> syntax is designed to be compatible with JavaScript's object literal notation - in fact, it's the same as JavaScript's object literal notation.</p>\n\n<p>I your case, that means you could do:</p>\n\n<pre><code>var handlers = {\n \"format:bold\": function () { ... }\n};\n</code></pre>\n\n<p>Which makes it's possible to namespace your events, regardless of how you attach your handlers. Namespacing them is A Good Idea™, if only because it makes the event's meaning more explicit, e.g. <code>format:bold</code>, <code>insert:image</code>, <code>insert:table</code> etc.. Of course, it also makes it clear that it's not a native event.</p>\n\n<blockquote>\n <p>I tried combining the two <code>.on()</code> blocks, but [that made it more complex]</p>\n</blockquote>\n\n<p>I'd say don't combine them. Sure, it might make the code more terse, but I see it more as the <code>a#onclick</code> handler is in charge of \"translating\" the click event to a custom event. Handling those custom events is a separate concern that can be taken care of (or just ignored) elsewhere. Decoupling, basically. Likewise, I'd probably declare the object with the custom event handlers separately, and then attach it with <code>.on</code> afterwards. It adds a bit of flexibility (and readability, imho) to have the object \"by itself\" instead of inlining it. For instance, you can add and remove methods (handlers) in the object at any point in time, because you'll have a reference to the object (which you wouldn't if it's inlined).</p>\n\n<blockquote>\n <p>Finally, I am still looking in to your <code>data-*</code> suggestion. It looks promising, not just here, but in other places as well.</p>\n</blockquote>\n\n<p>It is. It came about because people (myself included) were overloading the <code>class</code> attribute with all kinds of stuff that weren't actually class names, but random keywords used by JS instead. <code>data-*</code> is very welcome addition to HTML.</p>\n\n<blockquote>\n <p>BTW: why are you using <code>.attr()</code>?</p>\n</blockquote>\n\n<p>Because old habits die hard :)<br>\nBut also because <code>.prop()</code> is more general; \"retrieve a property\" whether it's in the markup as an attribute or not. However, in this case, we're explicitly looking for an attribute, and personally I like using <code>attr</code> in those cases, but either one will work (I see I've been inconsistent about it though, since I use <code>prop(\"id\")</code> elsewhere - apologies for the confusion). You could also use <code>.data(\"formatting\")</code> to get the value actually - there's a good case for using that instead. You're spoiled for choice really :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T16:00:48.540", "Id": "27962", "Score": "0", "body": "Thank you for this detailed answer. I've learned quite a bit. I decided to go with your second suggestion. I see a few benefits of choosing this over the other. First, it is a bit more coherent (imho); Second, I can apply an event object like I did in my first code sample, making both blocks similar in syntax; And third, I can reuse events with alternate triggers, such as key sequences (Ctrl+B to bold). I've updated my question with the new code and added a few more questions pertaining to this new implementation if you have time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T21:38:55.880", "Id": "27978", "Score": "0", "body": "@mseancole Cool. And yes, I had some time (read: the stuff I was supposed to be doing was boring), so I've updated my answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T14:02:53.233", "Id": "28009", "Score": "0", "body": "Awesome, wish I could upvote again, but I guess you'll have to settle for accepted instead. Interestingly enough, I tried the `'format:bold' : function() {` method first, but it didn't work. As you've probably guessed, it was because I was using single quotes. When it didn't work, I just assumed that it wouldn't and didn't think to try different quotes. Thank you for clearing that up :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T14:31:43.307", "Id": "28011", "Score": "0", "body": "@mseancole Happy to help. But, oddly, single quotes shouldn't cause any trouble - JS doesn't treat single quotes different from double quotes (unlike PHP and other languages, JS doesn't have string interpolation, so quoting style makes no difference). Weird." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T14:43:28.160", "Id": "28013", "Score": "0", "body": "I know, I didn't think it would matter either, which is why I didn't try it again until you said it should work. I just implemented this and tested it again. With double quotes it works fine, but the single quotes seem to be tripping it up. Looking in Firebug I don't see any warnings or errors, so I don't know why its failing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T16:08:33.330", "Id": "28021", "Score": "0", "body": "@mseancole Straaaange... I'm using Chrome, and it doesn't complain. If it were an object as a JSON _string_, then yes, property names in the string must be double quoted, but for straight interpreted javascript, it shouldn't matter (AFAIK). [Here's a jsfiddle test-page](http://jsfiddle.net/flambino/xud3y/) that seems to work just fine in both Chrome and Firefox (dunno about IE - I'm on a Mac)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T17:26:48.690", "Id": "28033", "Score": "0", "body": "Figured it out. When first testing this I was using the \"hotkeys\" to trigger the event and it worked just fine. Upon changing the code and reloading the page, my hand was on the mouse so I naturally used the onclick event instead, resulting in failure. Turns out I forgot to change `format_` to `format:` in the onclick event. Oddly enough, the \"hotkeys\" are triggering the onclick event, as I implemented these before the custom events, so they shouldn't work either. Hmmm.... Anyways, it all works with single or double quotes now, just that one quirk that still has me scratching my head. Thanks" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T00:48:26.517", "Id": "16494", "ParentId": "16483", "Score": "2" } } ]
{ "AcceptedAnswerId": "16494", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T21:04:50.230", "Id": "16483", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "Multi-Functional Event Delegate" }
16483
<p>I have the following code: </p> <ol> <li>The HTML part consist of two containers. Both containers have a list of hour and day weeks.</li> <li>This code is used to manage these lists of inputs.</li> </ol> <p>The JavaScript code works but I am wondering if it is possible to improve it, because the JavaScript code consists of around about 230 lines of codes. </p> <p>This is maybe too much considering I am using jQuery and Underscore library. Any hints to improve/clean/slim the code?</p> <p><a href="http://jsfiddle.net/D2RLR/2677/" rel="nofollow">Demo</a> and <a href="http://jsfiddle.net/D2RLR/2677/show" rel="nofollow">show</a></p> <pre><code>/*global jQuery, window */ (function ($, _, window) { 'use strict'; var $body = $('body'); var translator = window.ExposeTranslation; var copyValues, hasSameValues, checkInputs, createToggleButton; var selector = { updateContest: $('.update-contest'), reminderContest: $('.reminder-contest'), periodicityDaysClassName: '.data-periodicity-days', periodicityHoursClassName: '.data-periodicity-hours', btnToggleReminderClassName: '.btn-toggle-reminders' }; var DAYS_MAP = { daily: {0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true}, // daily weekday: {0: true, 1: true, 2: true, 3: true, 4: true, 5: false, 6: false}, // weekdays every_mon_wed_fri: {0: true, 1: false, 2: true, 3: false, 4: true, 5: false, 6: false}, // every_mon_wed_fri every_tue_thu: {0: false, 1: true, 2: false, 3: true, 4: false, 5: false, 6: false} // every_tue_thu }; var HOURS_RANGE = _.extend({}, _.map(_.range(24), function (i) { return (i === 18); })); var createSelectElement = function (items, parentElement, callback) { var selectElement = $('&lt;select&gt;'), optionElement; $.each(items, function (key, value) { optionElement = $('&lt;option&gt;').val(key).text(value); selectElement.append(optionElement); }); parentElement.prepend(selectElement); if (callback) { selectElement .on('change', callback) .on('change', function () { // it sets the same value in the select of Reminder section if ($(selector.btnToggleReminderClassName).hasClass('active')) { $(selector.periodicityDaysClassName + ' select').val($(this).val()); copyValues(); } }); } }; var selectDay = function () { var $this = $(this), labels = $(selector.periodicityDaysClassName).find('label'), inputs = labels.find('input'), value = $this.val(), setProp; setProp = function (dayRange) { $.each(dayRange, function (i, val) { $(inputs[i]).prop("checked", val); }); labels.hide(); }; if (value === 'daily') { labels.hide(); inputs.prop('checked', true); } else if (value === 'weekday') { setProp(DAYS_MAP[value]); } else if (value === 'weekly') { labels.show(); labels.find('input').prop('checked', false); $(inputs[(new Date()).getDay()]).prop('checked', true); } else if (value === 'every_mon_wed_fri') { setProp(DAYS_MAP[value]); } else if (value === 'every_tue_thu') { setProp(DAYS_MAP[value]); } }; var selectHours = function () { var value = $(this).val(), labels = $(selector.periodicityHoursClassName).find('label'), inputs = labels.find('input'); if (value === 'customize') { labels.show(); } else { $(inputs).prop('checked', false); $(inputs[value]).prop('checked', true); labels.hide(); } }; checkInputs = function () { // it set the select on the right place on load document var setSelectDayValue = function (contest) { var periodicityDaysInputs = contest.find(selector.periodicityDaysClassName + ' input'), currentDaysRange = {}; $.each(periodicityDaysInputs, function (i, v) { currentDaysRange[i] = $(v).prop('checked'); }); // it sets the default value of days select to weekly contest.find(selector.periodicityDaysClassName + ' select').val('weekly'); $.each(DAYS_MAP, function (index, dayRange) { if (_.isEqual(dayRange, currentDaysRange)) { contest.find(selector.periodicityDaysClassName + ' select').val(index); contest.find(selector.periodicityDaysClassName + ' label').hide(); return 0; } }); }; var setSelectHourValue = function (contest) { var periodicityHoursInputs = contest.find(selector.periodicityHoursClassName + ' input'), currentHoursRange = {}; $.each(periodicityHoursInputs, function (i, v) { currentHoursRange[i] = $(v).prop('checked'); }); // it sets the default value of 'hour select element' to customize contest.find(selector.periodicityHoursClassName + ' select').val('customize'); if (_.isEqual(currentHoursRange, HOURS_RANGE)) { contest.find(selector.periodicityHoursClassName + ' select').val(18); contest.find(selector.periodicityHoursClassName + ' label').hide(); } }; setSelectDayValue(selector.updateContest); setSelectDayValue(selector.reminderContest); setSelectHourValue(selector.updateContest); setSelectHourValue(selector.reminderContest); if (hasSameValues()) { $(selector.btnToggleReminderClassName).click(); } }; createToggleButton = function (parentElement) { var buttonElement = $('&lt;button&gt;'), isVisible; buttonElement.text('copy update periodicity'); buttonElement.attr({ 'class': 'btn ' + selector.btnToggleReminderClassName.substring(1), 'type': 'button', 'data-toggle': 'button', 'data-complete-text': 'customize' }); parentElement.prepend(buttonElement); buttonElement.on('click', function (event) { // TODO it works but it is triggered two times, I should have a container of these two elements $(event.currentTarget).parent('.reminder-contest').find('.control-group').toggle(function () { isVisible = $(this).is(':visible'); buttonElement.button(isVisible ? 'reset' : 'complete'); if (!isVisible) { selector.reminderContest.find('.form-help-block').show(); } else { selector.reminderContest.find('.form-help-block').hide(); } }); }); }; copyValues = function () { var container1 = selector.updateContest.find('input:checkbox'); var container2 = selector.reminderContest.find('input:checkbox'); var updateDaysSelect = selector.updateContest.find('select'); var reminderDaysSelect = selector.reminderContest.find('select'); container2.each(function (i) { $(this).prop('checked', $(container1[i]).prop('checked')); }); reminderDaysSelect.val(updateDaysSelect.val()); }; hasSameValues = function () { var result = true, updateInputs = selector.updateContest.find('input:checkbox'), reminderInputs = selector.reminderContest.find('input:checkbox'); reminderInputs.each(function (i) { if ($(this).prop('checked') !== $(updateInputs[i]).prop('checked')) { result = false; return false; } }); return result; }; $(function () { var ITEM_DAYS = { daily: 'daily', weekday: 'weekday', weekly: 'weekly', every_mon_wed_fri: 'every_mon_wed_fri', every_tue_thu: 'every_tue_thu' }; var ITEMS_HOURS = { 18: 'at 18 pm', customize: 'customize' }; // it creates select for Days and Hours labels $.each($(selector.periodicityHoursClassName), function (i, element) { createSelectElement(ITEMS_HOURS, $(element), selectHours); }); $.each($(selector.periodicityDaysClassName), function (i, element) { createSelectElement(ITEM_DAYS, $(element), selectDay); }); // it creates the button for copy the "Update Periodicity" into "Reminder Periodicity" createToggleButton(selector.reminderContest); // it checks the initial values in order to set properly the select and button elements values checkInputs(); $body.on('click', selector.updateContest.find('input:checkbox'), function () { var copyUpdatePeriodicityBtn = $(selector.btnToggleReminderClassName); if (copyUpdatePeriodicityBtn.hasClass('active')) { copyValues(); } }); selector.updateContest.closest('.control-group').addClass('periodicity-fields-container'); selector.reminderContest.closest('.control-group').addClass('periodicity-fields-container'); selector.reminderContest.prepend('&lt;div class="form-help-block"&gt;'+'messages:contest.help.customize_periodicity' + '&lt;/div&gt;'); }); }(jQuery, window._, window)); </code></pre>
[]
[ { "body": "<p>Considering the complexity of your GUI I'd say your code is already quite trim. If you wish to cut it down I'd go about simplifying the user interface, personally I found it confusing - but then again I am using it out of context.</p>\n\n<p>Whilst it's great from a code view point to reuse interfaces (i.e the duplication between update and reminder sections) - from a user POV this can be confusing when the repetition appears constantly.</p>\n\n<p>If it were me I'd take your generalised code for handling your date, repeat and time fields and abstract it away behind your own form widget, something like:</p>\n\n\n\n<pre class=\"lang-none prettyprint-override\"><code> +------------------+\n Summary text about repeat date and time | click to change |\n +------------------+ \n</code></pre>\n\n<p>With this kind of widget you could rework your interface:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> Updates:\n +------------------+\n Repeats weekly, every Tuesday, at 18:00 and 20:00 | click to change |\n +------------------+\n Reminders:\n +--------------+\n /no reminders set/ | click to set |\n +--------------+\n\n [ ] tick to synchronize Reminders with Updates\n</code></pre>\n\n\n\n<p>Once you have that kind of layout, you'd just need to rework your code so that using either widget calls into existence your generalised GUI for setting a date, frequency and time - you could use a popover, or a new admin screen. By tidying this code away in a reusable widget you'd probably find places where you could abstract and cut down code (i.e. not having to be specific with class names or input synchronisation).</p>\n\n<p>Also, if you developed a interpretable and generalised way of describing a repeat \nevent, like:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>{repeats:'weekly',every:'tuesday','at':[18:00,20:00]}\n</code></pre>\n\n<p>This could be stored in a hidden field or attribute along with the widget once used. With this, syncronising the information between widgets suddenly becomes quite easy, wouldn't require specific fields to be constantly harmonised, and any harmonising work could be done in a simple function outside of all the widget code.</p>\n\n<p>Doing things in the manner above would also help with extensibility, if you ever needed to add an extra type of event &mdash; or wanted to allow the user to define multiple update events. You would be able to add a new widget easily.</p>\n\n<p>Anyway, apologies if this wasn't the answer you were looking for, as I said the code to me looks pretty good for what you have &mdash; it's more the approach that could improve things.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T07:42:56.730", "Id": "27863", "Score": "0", "body": "+1 thanks very much for having a look at my code. Your comments are greatly appreciated." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T23:37:30.897", "Id": "17511", "ParentId": "16492", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T23:40:37.390", "Id": "16492", "Score": "1", "Tags": [ "javascript", "jquery", "datetime", "underscore.js" ], "Title": "Code to manage weekdays and hours" }
16492
<p>I wrote a class that uses RestSharp to access Rest and HTTP API web services. I tested it and it works however I was wondering if any changes could be made to it to make it better.</p> <pre><code>public class RequestHandler { //Client to translate Rest Request intot HTTP request and process the result. private RestClient client; //this property stores the base URL const string baseUrl = ""; //stores the account id and secret key if they will be needed for any authentication processes. readonly string account_id; readonly string secretKey; //this property stores the API key readonly string accessKey = ""; //This constructor contains the account id and secret key that will be used for authorization when connecting to the API public RequestHandler(string account_id,string secretKey) { client = new RestClient(baseUrl); this.account_id = account_id; this.secretKey = secretKey; } //The default constructor public RequestHandler() { client = new RestClient(baseUrl); } public void Execute&lt;T&gt;(int id,Action&lt;T&gt; Success, Action&lt;string&gt; Failure) where T:new() { RestRequest request = new RestRequest(); request.RequestFormat = DataFormat.Json; request.AddParameter("id",id,ParameterType.GetOrPost); client.ExecuteAsync&lt;T&gt;(request,(response) =&gt; { if(response.ResponseStatus == ResponseStatus.Error) { Failure(response.ErrorMessage); } else { Success(response.Data); } }); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T01:04:42.273", "Id": "26812", "Score": "1", "body": "I don't see where secret key and account id are used other than assigning them to read only fields in the class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T18:52:35.100", "Id": "26843", "Score": "0", "body": "I would probably consider at least chaining your constructors so only one of them will actually do the work. In this case I would probably make your parameterless constructor call the other i.e. RequestHandler() : this(string.Empty, string.Empty)" } ]
[ { "body": "<p>Depend on the <code>IRestClient</code> interface rather than the <code>RestClient</code> implementation and make the field <code>readonly</code> as it is only set via the constructor:</p>\n\n<pre><code>private readonly IRestClient client;\n</code></pre>\n\n<p>Invert your dependancy on <code>RestClient</code>, if you are not using an IOC container, at least implement poor mans injection so that the class is testable (e.g. you can supply a mock <code>IRestClient</code> to test <code>RestHandler</code>.</p>\n\n<pre><code>public RequestHandler() // If you are using an IOC container, remove the default constructor.\n : this(new RestClient(baseUrl))\n{\n}\n\npublic RequestHandler(IRestClient restClient)\n{\n this.client = restClient;\n}\n</code></pre>\n\n<p>As Ron mentioned above, you don't appear to be using secret key and account id so either remove them if they are not needed or use them.</p>\n\n<p>Making the base url a constant inside the class makes it difficult to re-use, I would move that into the application configuration.</p>\n\n<p>If you do need <code>account_id</code>, remove the underscore and camel case it <code>accountId</code> to adhere to the standard naming conventions.</p>\n\n<p>Adding a property for the <code>DataFormat</code> will make the class more re-usable if you want to call a web service which doesn't support Json:</p>\n\n<pre><code>public DataFormat DataFormat { get; set; }\n\n// Default to Json in the constructor\nthis.client = restClient\nthis.DataForma = DataFormat.Json;\n</code></pre>\n\n<p><code>ExecuteAsync</code> returns a <code>RestRequestAsyncHandle</code> which allows the request to be aborted, it might be worth looking at whether you need the ability to abort requests or not. You could update your <code>Execute</code> to return the wait handle.</p>\n\n<p>The error checking here doesn't account for any of the other reasons for failure such as a timeout or abort.</p>\n\n<pre><code>if (response.ResponseStatus == ResponseStatus.Error)\n</code></pre>\n\n<p>Update it to something like this:</p>\n\n<pre><code>switch (response.ResponseStatus)\n{\n ResponseStatus.Completed:\n Success(response.Data);\n break;\n\n ResponseStatus.Error:\n ResponseStatus.TimedOut:\n Failure(response.ErrorMessage);\n break;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-13T11:26:10.213", "Id": "108080", "Score": "0", "body": "Should we also use IRestRequest?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T21:50:33.860", "Id": "17534", "ParentId": "16493", "Score": "4" } } ]
{ "AcceptedAnswerId": "17534", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T23:56:09.163", "Id": "16493", "Score": "3", "Tags": [ "c#", "generics" ], "Title": "Review of a generic request handler class (RestSharp)" }
16493
<p>This is a CodeEval challenge taken from <a href="https://www.codeeval.com/public_sc/41/" rel="nofollow">here</a>:</p> <blockquote> <p><strong>Challenge description:</strong></p> <p>Imagine we have an immutable array of size N which we know to be filled with integers ranging from 0 to N-2, inclusive. Suppose we know that the array contains exactly one duplicated entry and that duplicate appears exactly twice. Find the duplicated entry. (For bonus points, ensure your solution has constant space and time proportional to N)</p> <p><strong>Input sample:</strong></p> <p>Your program should accept as its first argument a path to a filename. Each line in this file is one test case. Ignore all empty lines. Each line begins with a positive integer(N) i.e. the size of the array, then a semicolon followed by a comma separated list of positive numbers ranging from 0 to N-2, inclusive):</p> <pre><code>1 2 5;0,1,2,3,0 20;0,1,10,3,2,4,5,7,6,8,11,9,15,12,13,4,16,18,17,14 </code></pre> <p><strong>Output sample:</strong></p> <p>Print out the duplicated entry, each one on a new line:</p> <pre><code>1 2 0 4 </code></pre> </blockquote> <p>I've written this code:</p> <pre><code>import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.StringTokenizer; /** * * @author Mohammad Faisal */ public class ArrayAbsurdity { public static void main(String[] args) throws FileNotFoundException { Scanner input = new Scanner(new FileInputStream("E:\\java\\temp\\abc.txt")); while(input.hasNextLine()){ String str = input.nextLine(); if(str.equals("")){ continue; } String[] in = str.split(";"); int i=0; int[] a = new int[Integer.parseInt(in[0])]; StringTokenizer token = new StringTokenizer(in[1], ","); while(token.hasMoreTokens()){ a[i]=Integer.parseInt(token.nextToken()); i++; } boolean success=false; for(i=0; i&lt;a.length-1; i++){ for(int j=i+1; j&lt;a.length; j++){ if(a[i] == a[j]){ System.out.println(a[i]); success=true; break; } } if(success){ break; } } } } } </code></pre> <p>Can anybody review it and help me in improving the space and time complexity as per the problem?</p>
[]
[ { "body": "<p>Apparently according to this post <a href=\"https://stackoverflow.com/questions/5965767/performance-of-stringtokenizer-class-vs-split-method-in-java\">String tokeniser performance</a> using indexOf is alot quicker (I personally have no idea on that front). So taking what the chap posted in his solution you might be able to do something like:</p>\n\n<pre><code>String[] in = str.split(\";\");\n\n// I assumed that in alot of the cases we will find the duplicate with at least n / 2 checks\nint initialCapacity = Integer.parseInt(in[0]);\n\nHashMap&lt;String,Boolean&gt; items = new HashMap&lt;String,Boolean&gt;(initialCapacity / 2);\n\nint pos = 0, end;\nString sample = in[1];\nboolean foundDuplicate = false;\n\nwhile ((end = sample.indexOf(',', pos)) &gt;= 0) {\n // assuming uniform data with no extra spaces etc do we even need to parse\n // the value to an integer?\n String item = sample.substring(pos, end);\n\n if(items.containsKey(item)) {\n System.out.println(item);\n foundDuplicate = true;\n break;\n } else {\n items.put(item, true);\n }\n\n pos = end + 1;\n}\n\nif(!foundDuplicate) {\n System.out.println(sample.substring(pos)); // must be the last item\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T07:40:35.260", "Id": "16499", "ParentId": "16497", "Score": "2" } }, { "body": "<p>I don't have a comment on how you parse the input. I just give a solution which runs in O(1) space and O(N) time.</p>\n\n<p>Problem says that all integers are in range 0..N-2 and there's only one integer duplicated. Consider you hadn't that duplicated element, so sum of all input numbers would be <code>(n-2)*(n-1)/2</code> (sum of integers from 0 to n-2). So now you can read all N integers and calculate their sum. Then if you subtract <code>(n-2)*(n-1)/2</code> from this sum, the value of your duplicated element would come out.</p>\n\n<p>The code would be:</p>\n\n<pre><code>int sum = 0;\nint n = a.length;\nfor(i=0; i&lt;n; i++)\n sum += a[i];\n\nSystem.out.println(sum - (n-2)*(n-1)/2);\n</code></pre>\n\n<p>This method is clearly of O(n) time, but if you want to achieve O(1) space, you should avoid storing all elements in an array. Instead of that, when you parsed nextToken, you add it to <code>sum</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T09:42:18.680", "Id": "26827", "Score": "0", "body": "Ah Brilliant :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T10:54:37.443", "Id": "26829", "Score": "0", "body": "@saeedn: can you please tell me how to compute that complexity?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T12:01:31.553", "Id": "26831", "Score": "1", "body": "@MohammadFaisal please [give the question a few days to breathe](http://meta.codereview.stackexchange.com/q/614/9390) before accepting an answer..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T12:07:19.360", "Id": "26832", "Score": "0", "body": "@codesparkle: okay. Do you have any better solution?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T12:12:46.827", "Id": "26833", "Score": "0", "body": "@MohammadFaisal not really, although I *am* writing down a few other points that might be relevant. saeedn's answer is good, but it doesn't deal with parsing input, which will have a significant space cost if done wrong. So leaving your question open a bit might get you a good answer about parsing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T12:39:19.693", "Id": "26834", "Score": "1", "body": "@MohammadFaisal For calculating space complexity, we can see that number of variables we're using is regardless of `N` and thus constant for every input data (`sum`, `n` and let's say `x` for holding current element). For time complexity, we can see that for each input element we perform constant number of operations (updating the `sum`), so for `N` elements we achieve `O(N)` time." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T08:52:57.900", "Id": "16500", "ParentId": "16497", "Score": "7" } } ]
{ "AcceptedAnswerId": "16500", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T04:40:02.600", "Id": "16497", "Score": "1", "Tags": [ "java", "programming-challenge" ], "Title": "Array absurdity challenge" }
16497
<p>I would like to write a python or c++ function to print numbers like the following examples (with n as input parameter):</p> <p>When n = 3, print:</p> <pre><code>1 2 3 8 0 4 7 6 5 </code></pre> <p>When n = 4, print:</p> <pre><code>4 5 6 7 15 0 1 8 14 3 2 9 13 12 11 10 </code></pre> <p>I have an answer in the following code block, but it is not quite elegant. Does anyone have a better solution?</p> <pre><code>def print_matrix(n): l = [i for i in range(0,n*n)] start = (n-1)/2 end = n-1-start count = 0 if start ==end: l [start+ n*end] = count start -= 1 count +=1 while start &gt;=0: end = n - start for i in range(start, end-1): x= i y= start print y*n +x l[y*n +x] = count count +=1 for i in range(start, end-1): x = end-1 y = i print y*n +x l[y*n +x] = count count +=1 for i in range(end-1,start,-1): x= i y= end-1 print y*n +x l[y*n +x] = count count +=1 for i in range(end-1, start,-1): x = start y = i print y*n +x l[y*n +x] = count count +=1 start -=1 print l </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T14:37:28.987", "Id": "26841", "Score": "1", "body": "Have no idea why this has been moved here. Much more suited to stack overflow. There are also many more people on SO that can help maybe you should rephrase the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T19:32:46.140", "Id": "27845", "Score": "3", "body": "@LokiAstari, its not clear to me why you think this is off-topic here. People presenting working code and ask for more elegant solutions seems to be a large part of the questions here." } ]
[ { "body": "<p>Using a 2D array to store the matrix, we can simplify the function greatly. This uses Python 2 syntax.</p>\n\n<pre><code>def print_matrix(n):\n mat = [[0]*n for _ in xrange(n)]\n\n k = 0 # value to write\n for level in reversed(xrange(n, 0, -2)):\n start = n/2 - level/2\n pr = pc = start # current row, column indices\n if level == 1: # special case: no perimeter crawl\n mat[pr][pc] = k\n k += 1\n continue\n # walk along each edge of the perimeter\n for dr, dc in [(0,1), (1,0), (0,-1), (-1,0)]:\n for i in xrange(level - 1):\n mat[pr][pc] = k\n k, pr, pc = k+1, pr+dr, pc+dc\n\n width = len(str(n*n-1))\n for i in mat:\n for j in i:\n print '{:&lt;{width}}'.format(j, width=width),\n print\n</code></pre>\n\n<p>Samples:</p>\n\n<pre><code>&gt;&gt;&gt; print_matrix(4)\n4 5 6 7 \n15 0 1 8 \n14 3 2 9 \n13 12 11 10\n&gt;&gt;&gt; print_matrix(3)\n1 2 3\n8 0 4\n7 6 5\n&gt;&gt;&gt; print_matrix(2)\n0 1\n3 2\n&gt;&gt;&gt; print_matrix(1)\n0\n&gt;&gt;&gt; print_matrix(9)\n49 50 51 52 53 54 55 56 57\n80 25 26 27 28 29 30 31 58\n79 48 9 10 11 12 13 32 59\n78 47 24 1 2 3 14 33 60\n77 46 23 8 0 4 15 34 61\n76 45 22 7 6 5 16 35 62\n75 44 21 20 19 18 17 36 63\n74 43 42 41 40 39 38 37 64\n73 72 71 70 69 68 67 66 65\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T17:42:02.093", "Id": "16505", "ParentId": "16503", "Score": "5" } }, { "body": "<p>The important element of a shorter program is using a direction-array to set the step directions in your matrix; whether the matrix is represented via a 1D vector or a 2D matrix is less important. In a vector, the same-column cell in the next row is n elements away from the current cell.</p>\n\n<pre><code>def print_matrix(n):\n ar = [0 for i in range(n*n)]\n m, bat = n, 0\n for shell in range((n+1)//2):\n at = bat\n m = m-2\n ar[at] = val = m*m # Each shell starts with a square\n if m&lt;0:\n ar[at] = 0\n break\n for delta in [1, n, -1, -n]: # Do 4 sides of shell\n # Fill from corner to just before next corner\n for tic in range(m+1):\n ar[at] = val\n at += delta # Step to next or prev row or col\n val += 1\n bat += n+1 # Step to next-inner shell\n\n # Print matrix in n rows, n columns\n for i in range(n):\n for j in range(n):\n print \"\\t\", ar[i*n+j],\n print\n\nfor n in range(1,7):\n print \"n = \", n\n print_matrix(n)\n</code></pre>\n\n<p>This produces output like the following:</p>\n\n<pre><code>n = 1\n 0\nn = 2\n 0 1\n 3 2\nn = 3\n 1 2 3\n 8 0 4\n 7 6 5\n...\nn = 6\n 16 17 18 19 20 21\n 35 4 5 6 7 22\n 34 15 0 1 8 23\n 33 14 3 2 9 24\n 32 13 12 11 10 25\n 31 30 29 28 27 26\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T18:23:23.993", "Id": "16508", "ParentId": "16503", "Score": "2" } }, { "body": "<p>Just a direction, not a full solution, but anyway...</p>\n\n<p>If limited by space, you could <strong>directly</strong> calculate each item in the matrix, given its indexes and N. So eventually you could have a function with the following signature:</p>\n\n<pre><code>def calc_mat_item(i, j, n)\n</code></pre>\n\n<p>The math behind this function is not that simple, but it's not that complex, too: You should calculate the shell's index, according to <code>i</code>, <code>j</code>, and <code>n</code>. Then you should calculate on which side of the shell are <code>i</code> and <code>j</code> (\"North\", \"South\", \"East\" or \"West\"), and calculate the \"distance\" (in steps) of the current item from the shell's start position.<br>\nAll this is pretty much mod calculations.</p>\n\n<p>Once this method is done, you could simply write a nested loop (N by N) with <code>i</code> and <code>j</code>, and print the function's value, without having to populate a matrix before that.</p>\n\n<p>The calculations in the <code>calc_mat_item</code> should not take more than <em>O(1)</em> (in space and time), so eventually you could have a solution of <em>Θ(N)</em> in time, and <em>O(1)</em> in space.</p>\n\n<p>Just an idea, though.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T19:18:47.507", "Id": "27970", "Score": "0", "body": "Yes, that's the idea I also had. Your direction has been converted into code! Checkout [my answer](http://codereview.stackexchange.com/a/17576/18383)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T19:23:22.600", "Id": "27971", "Score": "0", "body": "As you can see, there's only one `if`, everything else is maths!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T04:52:39.173", "Id": "17518", "ParentId": "16503", "Score": "1" } }, { "body": "<p>The code that you and other people posted could be simplified to the following:</p>\n\n<pre><code>def slot(n, x,y):\n ma = max(x,y)+1\n mi = min(x,y)\n o= min(n-ma,mi)\n l= max(n-2*(o+1),0)\n p= x+y - 2*o\n if x&lt;y: p= 4*(l+1)-p\n return l*l+p\n</code></pre>\n\n<p>To use the code you could do:</p>\n\n<pre><code>from sys import stdout as out\n\nn = 3\nfor y in xrange(n):\n for x in xrange(n):\n out.write(' %2d'%slot(n,x,y))\n print\n</code></pre>\n\n<p>As you can see, it doesn't need 2D arrays.<br>\nIt just calculates the values pixel-per-pixel.<br>\nIt is more robust: try to do any other program with <code>n=1000000000</code> and it will fail.</p>\n\n<p>The results are always as expected, see them <a href=\"http://ideone.com/8KakI\">at IdeOne</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T20:36:53.217", "Id": "27975", "Score": "0", "body": "nice.. :) however, I'd say that `min` and `max` have their own `if` in their implementation, so it's around 4-5 `if`s in a whole." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T06:34:08.167", "Id": "27981", "Score": "0", "body": "Yeah I know, but they're mathematic functions so their implementations don't count :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T19:17:10.037", "Id": "17576", "ParentId": "16503", "Score": "5" } } ]
{ "AcceptedAnswerId": "16505", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T13:14:44.300", "Id": "16503", "Score": "10", "Tags": [ "python", "algorithm" ], "Title": "Write a function to print numbers" }
16503
<p>Is my following (very basic) class considered good use for PDO integration? Or is there a better, more efficient way?</p> <pre><code>class Page { public $title; public $db; public function __construct($title) { $this-&gt;title = $title; } public function connect($host, $dbname, $username, $password) { $this-&gt;db = new PDO('mysql:host='.$host.';dbname='.$dbname, $username, $password); } public function disconnect() { $this-&gt;db = null; } } </code></pre>
[]
[ { "body": "<p><strong>Unused properties</strong></p>\n\n<p>You shoult not set <code>$this-&gt;title</code> in the <code>__construct()</code> method unless you are planning on using it.It would be better if you set this value in the particular method that is planning on using this data.</p>\n\n<p><strong>Visibility</strong> </p>\n\n<p>The first thing I noticed when I looked at this code is that these properties <code>public $title;\n public $db;</code>are indeed public. It would be best if you change the visibility to private to ensure that you have more control over the state of these values. </p>\n\n<p><strong>Exception handling</strong></p>\n\n<p>In your <em>connect</em> method you are creating a new PDO object without handling any errors that may occur. The correct approach is to use the <a href=\"http://php.net/manual/en/class.pdoexception.php\" rel=\"nofollow\">PDOException class</a>\nto handle this error. </p>\n\n<p>An example:</p>\n\n<pre><code>try\n{\n $this-&gt;db = new PDO('mysql:host='.$host.';dbname='.$dbname, $username, $password);\n}\ncatch (PDOException $e)\n{\n die($e-&gt;getMessage());\n}\n</code></pre>\n\n<p><strong>Commenting</strong></p>\n\n<p>It's always good to practice making comments in your code to ensure that its easy to follow and if another developer should use your class they will be able to understand exactly whats taking place. <a href=\"http://www.phpdoc.org/\" rel=\"nofollow\">phpDoc</a> is a good tool that can be used to generate documentation.</p>\n\n<p><strong>Querying</strong></p>\n\n<p>Is this the complete class? I ask this because it seems as if a query function is missing. Making queries with PDO have been simplified thus can implement a simple query method to retrieve to access your database.</p>\n\n<pre><code>public function query($query)\n{\n if($query)\n {\n $current_query-&gt;$this-&gt;db-&gt;prepare($query);\n $current_query-&gt;execute();\n $result-&gt;$current_query-&gt;fetchAll();\n\n return $result;\n }\n else\n return false;\n}\n</code></pre>\n\n<p>I hope my answers helps somewhat if they are any concerns or errors one can just leave a comment, I am open to criticism.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T09:37:21.390", "Id": "27865", "Score": "0", "body": "Thanks, that all makes sense! I left exception handling out, because I'm just starting to learn OO. And I left out querying because I thought it was redundant, because PDO already has native methods to do that. That's why I also made a `public $db`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T21:17:46.010", "Id": "27888", "Score": "0", "body": "ok great! glad I could help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T13:17:42.073", "Id": "28089", "Score": "0", "body": "@fishbaitfood: Would like to clarify a few things. Doccomments are good, inline comments are not. They clutter your code. Most IDEs know how to collapse doccomments all at once so they are out of the way. As for title, I agree that shouldn't be the sole item in the constructor, but following Paul's example should fix this. And finally, as you have already mentioned, adding the query functionality would be redundant, as would creating a class just to instantiate a database. If you are planning on doing more this is fine, but as is this is redundant." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T20:42:25.570", "Id": "17507", "ParentId": "16506", "Score": "1" } }, { "body": "<p>Interestingly, my review is going to be all about control.</p>\n\n<h1>Not Enough - Public Property</h1>\n\n<p>Just like in the real world, public property can be used by anyone. If your car was public property anyone could walk into your driveway and do whatever they liked with it. When you woke up you could not expect to <code>$this-&gt;car-&gt;drive()</code> (What if someone had already taken it and replaced it with <code>null</code>?). If they wanted to they could place a house brick in your driveway pretending that it is your car (good luck driving that).</p>\n\n<p>Public properties remove the encapsulation of state from an object. I see virtually no place for them in OO. Protected and Private properties on the other hand are set through using the public interface (the public methods) of an object. Importantly the public interface is testable, so you can ensure that you will not end up with a brick in your driveway unless you really want that.</p>\n\n<h1>Too Much - Inversion of Control</h1>\n\n<p>Your code will benefit from an Inversion of Conrtol (IoC). You can read about IoC on the web. There is a good answer on stackoverflow with code <a href=\"https://stackoverflow.com/a/3140/567663\">here</a>.</p>\n\n<p>With IoC and the protected properties your code becomes:</p>\n\n<pre><code>class Page {\n\n protected $title;\n protected $db;\n\n public function __construct($db, $title) {\n $this-&gt;db = $db;\n $this-&gt;title = $title;\n }\n}\n</code></pre>\n\n<p>Your code is no longer dependent on the specific database setup to function correctly. Your page will use any database connection that it is given. This has big benefits when it comes to unit testing. See <a href=\"http://misko.hevery.com/2008/07/08/how-to-think-about-the-new-operator/\" rel=\"nofollow noreferrer\">Miško Hevery - How to Think About the “new” Operator with Respect to Unit Testing</a>.</p>\n\n<p>I have another answer that covers similar things with an extra part on injecting interfaces <a href=\"https://codereview.stackexchange.com/a/9505/7585\">here</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T12:19:18.147", "Id": "28000", "Score": "2", "body": "+1 inversion of control as applied here is also referred to as dependency injection." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T05:35:10.763", "Id": "17519", "ParentId": "16506", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T18:13:19.243", "Id": "16506", "Score": "2", "Tags": [ "php", "object-oriented" ], "Title": "Basic Database Class with PDO functionality" }
16506
<p>I'm hoping that the more experienced devs here can help me improve these methods. I'm building a basic MVC framework for myself (as a learning project,) and I'd really appreciate your insights. Things I'm looking for specifically are:</p> <ol> <li><strong>Efficiency:</strong> can these methods be improved (particularly with the <code>Request:parseURI()</code> method.)?</li> <li><strong>Clarity:</strong> do these methods make sense the way they're written, or should I refactor?</li> </ol> <p>I'm including two key methods of my request routing system:</p> <ul> <li><code>RequestRouter</code></li> <li><code>Request</code></li> </ul> <h1><code>RequestRouter::dispatch()</code></h1> <pre><code>public function dispatch() { try { // Instantiate the requested controller class $class = ( $this-&gt;getController() != null ) ? ucwords( $this-&gt;getController() ) . 'Controller' : BaseController::ERROR_CONTROLLER; /** * Ensure this is a class that's contained in the Manifest get_class(..,true); * If it doesn't exist in the manifest, it will not be executed. */ $ref = new ReflectionClass( ( class_exists($class, true) ) ? $class : BaseController::ERROR_CONTROLLER ); /** * Ensure that the class follows conventions: * 1. Controller class must implement IController * 2. Controller class must implement a Controller::index() method -- this is implied since * the first condition won't be satisfied unless the IController interface is implemented. */ if( $ref-&gt;implementsInterface('IController') ) { // Instantiate a new Controller $controller = $ref-&gt;newInstance( $this-&gt;registry ); // Check to see if the method exists if( !$ref-&gt;hasMethod( $this-&gt;getAction() ) ) trigger_error("Method, \"{$this-&gt;getAction()}\" does not exist.", E_USER_WARNING); // Get a ReflectionMethod object $method = $ref-&gt;getMethod( ( $this-&gt;getAction() != null &amp;&amp; $ref-&gt;hasMethod( $this-&gt;getAction() ) ) ? $this-&gt;getAction() : BaseController::DEFAULT_METHOD ); // Track the request status $this-&gt;request-&gt;requestStatus( ( $ref-&gt;name == BaseController::ERROR_CONTROLLER ) ? HttpStatus::HTTP_NOT_FOUND : HttpStatus::HTTP_OK ); // Invoke the Controller::method() $method-&gt;invoke( $controller ); } else { trigger_error( 'Interface IContoller must be implemented.', E_USER_ERROR ); } } catch( Exception $e ) { header( HttpStatus::getHttpHeader( HttpStatus::HTTP_NOT_IMPLEMENTED ) ); throw new Exception(__METHOD__ . ' threw an exception: ' . $e-&gt;getMessage()); } } </code></pre> <h1><code>Request::parseURI()</code></h1> <p>This method makes use of an array of regular expressions, to match common and specific requests:</p> <ul> <li><code>"#^/(?&lt;controller&gt;[\w-]+)?(?:/(?&lt;action&gt;[\w-]+))?(?:/(?&lt;params&gt;[^?]+).*?|$)?#"</code></li> <li><code>"#^/admin/(?:(?&lt;controller&gt;[\w]+))?/(?:(?&lt;action&gt;[\w]+))?/(?:(?&lt;params&gt;[^?]+).*?|$)?#"</code></li> </ul> <p><strong>Note:</strong> The second expression is intended for a specific module, targeting the request for a controller defined in the second segment.</p> <p>The segments can appear as follows:</p> <ul> <li><code>/controller/action/argument-1/argument-2/argument-3/etc</code></li> <li><code>/admin/controller/action/argument-1/argument-2/argument-3/etc</code></li> </ul> <pre><code>/** * This methods parses a given URI into it's various segments, e.g. controller|action|params * * @param array $pattern_collection A list of regex patterns to match */ private function parseURI( array $pattern_collection ) { $request_uri = $_SERVER['REQUEST_URI']; // Find the first match (not necessarily the best match) foreach( $pattern_collection as $route =&gt; $patterns ) { foreach( $patterns as $pattern ) { $match = preg_match( $pattern, $request_uri, $uri_fragments ); if( $match &amp;&amp; $match !== false) { break 2; } } } // Populate object members match to one of the patterns was made, $this-&gt;uri = array_shift( $uri_fragments ); // 0 Always contains the original string $this-&gt;controller = ( !empty($uri_fragments) &amp;&amp; array_key_exists( 'controller', $uri_fragments ) ) ? $uri_fragments['controller'] : 'index'; $this-&gt;action = ( !empty($uri_fragments) &amp;&amp; array_key_exists( 'action', $uri_fragments ) ) ? $uri_fragments['action'] : 'index'; // Arguments $params = ( !empty($uri_fragments) &amp;&amp; array_key_exists( 'params', $uri_fragments ) ) ? $uri_fragments['params'] : null; $this-&gt;params = ( $params != null ) ? array_filter( explode( '/', $params ) ) : null; } </code></pre>
[]
[ { "body": "<p>Large wall of text incoming. Go to the bathroom, grab a drink, etc...</p>\n\n<hr>\n\n<p><strong>Try/Catch</strong></p>\n\n<p>The first thing I would refactor is your try/catch statement. Its just way too large, though that may just be the internal comments (which I'll get to next). Try blocks should really only encompass those statements that should be try'd. Everything else is just unnecessary overhead. I would help you here, but I'm unsure what is throwing exceptions, that and I've just never been all that good with try/catch myself. Something I've been meaning to rectify.</p>\n\n<hr>\n\n<p><strong>Comments</strong></p>\n\n<p>While this isn't a functional concern, it is a legibility one. You have way too many internal comments. Even one internal comment is too many. If you have something you need to say, that your code doesn't already say, you should say it in the doccomments where it will do some good. Doccomments are defined like so:</p>\n\n<pre><code>/** Short Description\n *\n * Long Description\n * @param\n * @return\n*/\npublic function dispatch() {\n</code></pre>\n\n<p>You'll notice that some of your multiline internal comments follow this syntax as well. That is because you are using the wrong multiline comments. The proper way to do internal multiline comments is like so:</p>\n\n<pre><code>/*\nThis is a multiline comment\n*/\n</code></pre>\n\n<p>Though, as I've already mentioned, the key is to remove all internal comments. I'm just pointing this out for completeness.</p>\n\n<p>The difference is in how they start and how they are structured. The doccomment uses two asterisks in the opening, whereas the internal one uses just one. Another difference, though not truly distinguishable between doccomment and non-doccomment, is the \"bullet\" asterisks on each newline. This isn't a difference between the two, merely a difference in preference. You can use \"bullet\" asterisks on both, not at all, or mix them. Personally, when I absolutely have to use internal comments, I use the above styles as it is immediately visually distinct from each other. Another key benefit here is that doccomments are supposed to show structure, thus \"bullets\", whereas regular comments should just show text (makes sense to me). The last difference are those doccomment \"tags\" (@param, @return). There are many and it is beyond the scope of this question to go into them here. Suffice it to say, these really help in your IDE when you are trying to use a particular method or property. Along with the autocomplete, a good IDE will also show the doccomments in some intelligent way, making it clear if that is truly the element you wished to use. Good examples of this are those doccomments associated with native PHP functions.</p>\n\n<p>One key thing I mentioned at the beginning of this section, but would like to emphasize here. If your code is expressive enough, comments become less necessary. This is the reason why Self Documenting code is so commonly used. Don't use comments to explain something your code is expressive enough to explain by itself.</p>\n\n<hr>\n\n<p><strong>Ternary</strong></p>\n\n<p>I just finished explaining this in another post. This is all too common a problem, especially for those who are just learning ternary. Ternary is a very powerful tool. But you should know when to use it, and when not. This very first ternary statement is an example of a bad ternary statement. When your statements start to get too long, or too complex, or you start trying to nest them, then you should revert to using if/else statements. This ternary statement is both too long and too complex. Though, that's not to say we should immediately jump to using if/else statements. With some minor tweaking we can fix this to be a perfect ternary statement. The easiest way to do this would be to abstract our sections and simplify it.</p>\n\n<pre><code>$controller = $this-&gt;getController() . 'Controller';\n$controller = ucwords( $controller );\n$class = $controller == 'Controller' ? BaseController::ERROR_CONTROLLER : $controller;\n</code></pre>\n\n<p>So the first thing I did was I moved your <code>getController()</code> call out of the ternary and into a variable. This does a couple of things. First, it makes the return reusable so that you don't have to call the function again, thus not violating the \"Don't Repeat Yourself\" (DRY) Principle. Second, it makes it easier to check and manipulate it, as we'll do next.</p>\n\n<p>In the same definition, I went ahead and appended \"controller\" to the end of our variable. If it turns out that <code>getController()</code> returns null, then all that will be left will be \"controller\", which is easy enough to check. Following this, in a new definition of the same variable, I capitalized the words. Notice, I did not do this in the first definition as it would have made this more difficult to read. Moving this to its own statement improves legibility and is a trick that can be used many times when refactoring, not just refactoring ternary.</p>\n\n<p>There, now we can crunch the ternary like before and it is much cleaner and easier to follow. The only difference is the comparison we are using, checking for \"Controller\" instead of NULL, and the lack of parenthesis, they were unnecessary. Speaking of which, try using <code>is_null()</code> in the future, its a bit more obvious, or at the very least use an absolute comparison <code>!==</code>. Just using a loose comparison <code>!=</code> means it will match anything \"similar\" to NULL, which could just as easily be rewritten using the subject of the comparison as a boolean:</p>\n\n<pre><code>$this-&gt;getController() != null\n//is the same as\n$this-&gt;getController()\n</code></pre>\n\n<p>I'm not going to do this for each of your ternary statements, but just know that the above will be helpful for all of them. One last tip here: abstract your ternary from other statements. Ternary, should be its own statement and should not be part of a larger one, as you have done in the next ternary statement.</p>\n\n<hr>\n\n<p><strong>DRY</strong></p>\n\n<p>I mentioned DRY above, but I found another, more obscure, violation. So, here is a section just for it. As the name implies, you don't want your code to repeat itself. Good code is completely reusable, either through functions/methods or variables/properties or loops. So, the fact that you are using <code>BaseController::ERROR_CONTROLLER</code> three separate times should be a hint that you should refactor it somehow. The easiest way would be to assign it to a local variable or property. This makes it easier to change if you ever decided to do so. Another benefit is shorter code. But its not all just variables/properties and functions/methods and loops. Sometimes you can just slightly refactor your code to eliminate the need for something. For instance, in your two ternary statements you use that constant in case of an error. Since you are handling that error the same both times, why not just combine the ternary and check it once?</p>\n\n<pre><code>$error = BaseController::ERROR_CONTROLLER;\n$classDefined = $controller != 'Controller'\n$classExists = class_exists( $class, true );\n$class = $classDefined &amp;&amp; $classExists ? $controller : $error;\n$ref = new ReflectionClass( $class );\n</code></pre>\n\n<hr>\n\n<p><strong>Single Responsibility Principle</strong></p>\n\n<p>As with the try/catch block, you can just tell by looking at this method that it is too large. Initially I just thought it was due to the excessive internal comments, so I didn't mention it. However, upon closer inspection it is still true. If we follow the Single Responsibility Principle, then we know that our functions/methods should do one thing, to the exclusion of all others. And that one thing should be easily identifiable by its name. In this case, <code>dispatch()</code> should be a conglomeration of other method calls, used to \"dispatch\" the request. Instead, you are, for the most part, doing everything here and delegating nothing. For instance, everything I've covered up to this point could be considered part of a <code>validateController()</code> method. I'll leave the rest up to you, it should be relatively easy. Just try grouping your code by functionality (note the root word function).</p>\n\n<hr>\n\n<p><strong>Troublesome Syntax</strong></p>\n\n<p>PHP inherently requires braces <code>{}</code> on its expressions, otherwise you wouldn't have to add them after adding more than one statement. I've had this argument with another member (Corbin I think), and though he agrees with my sentiments he says that this is common and not an incomplete implementation, however, I stand by this. If PHP were to implement entirely braceless syntax I would not comment on someone using it, so long as they were consistent. But the half-assed implementation that they do have just promotes bad habits and should be avoided. It is inconsistent and prone to errors. A new user picking up this code, not understanding this syntax, would add additional lines in such a statement and, unwittingly, crash the program. If they are lucky they will be able to figure this out quickly, but more than likely this wont have been the only thing they changed and it will quickly become frustrating or troublesome. So, in short, it is always best to use braces on your expressions, even those one liners. I'd also suggest adding a newline after the expression to help with legibility and line length, but that is a preference.</p>\n\n<pre><code>if( !$ref-&gt;hasMethod( $this-&gt;getAction() ) ) {\n trigger_error(\"Method, \\\"{$this-&gt;getAction()}\\\" does not exist.\", E_USER_WARNING);\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Foreach Loops</strong></p>\n\n<p>I'm a bit confused as to if this is just a typo, or if you are just unsure about this syntax. With foreach loops you can access either the <code>$key =&gt; $value</code> pair, or just the <code>$value</code>. In the following snippet you are requesting the key/value pair with <code>$route</code> as your key, but then never using the key. After that you then use the alternate syntax as prescribed. Since the key isn't being used in either loop, both foreach loops should follow the syntax of the second loop. </p>\n\n<pre><code>foreach( $pattern_collection as $route =&gt; $patterns )\n{\n foreach( $patterns as $pattern )\n</code></pre>\n\n<p><strong>Bonus:</strong> Some times it is desirable to only loop over the keys with a foreach loop. Many times programmers use the key/value pair syntax to do this when, in fact, the proper syntax is to use <code>array_keys()</code> on the array and loop over that instead.</p>\n\n<hr>\n\n<p><strong>Conclusion</strong></p>\n\n<p>Whew, done. There's quite a bit here, but hopefully I covered everything. If you have any questions, just let me know. I wasn't able to review your MVC implementation because all you provided was key methods rather than full classes. Which is fine, but typically one of the biggest things most programmers have issues with when programming MVC frameworks for the first time is the class structure. For instance, they may get a controller and model mixed up, or combine the controller and view (though in some special cases this is permissible). One last parting comment: This is a really complex MVC you have planned out. Typically a first MVC framework will not use the reflection class as the developer will hardcode any functionality they need, not worrying about adding dynamic method calling until they understand the structure more. You've not just jumped into the deep end, you've jumped off the cruise ship into the middle of the ocean. Good luck to you and I hope you can swim :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T18:56:24.343", "Id": "28037", "Score": "0", "body": "Thank YOU! I've been waiting days for feedback on this ;) Will have a read through now (after a drink...)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T19:22:58.983", "Id": "28038", "Score": "0", "body": "@user916011: Yea... I'm usually a little faster, but I've been on hiatus for a few days trying to get some stuff straight. There aren't many of us answering here, so sometimes we can get a bit backed up and it may seem like its taking a while. But don't worry, most questions do eventually get an answer. If yours happens to be one that doesn't then that's one of two things. First, it was a damn good question and no one is sure how to answer it, or two, there's nothing wrong with it, though typically someone will chime in and say so either way so as not to leave you hanging. Hope it helps!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T19:26:44.730", "Id": "28039", "Score": "0", "body": "Wow, thanks for spending the time to review my code -- it's rare that I'm able to get peers to provide this kind of feedback, so many thanks. To your last point: totally jumped in the deep end. This a complete refactoring of my first MVC which used a very basic routing mechanism. While it was pretty solid, it wasn't very flexible (e.g. admin features were hardwired into the framework...). This version makes better use of regex patterns, separation of concerns/responsibilities, etc. Lots of work to do still, but your insights are spot-on! Thanks again ;)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T17:20:54.703", "Id": "17617", "ParentId": "16507", "Score": "5" } } ]
{ "AcceptedAnswerId": "17617", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T18:20:41.627", "Id": "16507", "Score": "5", "Tags": [ "php", "mvc", "url-routing" ], "Title": "The Router - dispatch after parseURL" }
16507
<p>I have a Windows-service and this service will connect to an ftp server and do download, upload, and rename operations.</p> <p>My service runs every 30 seconds, so the ftp server will be busy during these operations.</p> <p>My question is: is my code useful for this job? Because my download/upload/rename functions open a webrequest each process? I use <code>FtpWebRequest</code> and <code>FtpWebResponse</code></p> <p>I write only the download functions, the other functions are similar. </p> <p>Download function:</p> <pre><code> public Result Download(string localPath,string remotePath,string fileName) { Result _result = new Result(); FtpWebRequest requestFileDownload = null; FtpWebResponse responseFileDownload = null; try { // requestFileDownload = (FtpWebRequest)WebRequest.Create(remotePath + fileName); // requestFileDownload.Credentials = new NetworkCredential(this.Username, this.Password); // requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile; responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse(); using (Stream responseStream = responseFileDownload.GetResponseStream()) { FileStream writeStream = new FileStream(localPath + fileName, FileMode.Create); int Length = 2048; Byte[] buffer = new Byte[Length]; int bytesRead; while((bytesRead = responseStream.Read(buffer, 0, Length)) &gt; 0) { writeStream.Write(buffer, 0, bytesRead); } writeStream.Close(); } return _result; } catch (Exception x) { _result.Error = true; _result.ErrorMessage = x.StackTrace; _result.ErrorFileName = fileName; _result.ErrorFilePath = remotePath + fileName; return _result; } finally { requestFileDownload = null; responseFileDownload = null; } } public struct Result { public bool Error; public string ErrorMessage; public string ErrorFileName; public string ErrorFilePath; public List&lt;string&gt; Files; } </code></pre>
[]
[ { "body": "<p>A few things:</p>\n\n<ol>\n<li><p>I would supply all the variables that you have hard coded into the method i.e. localPath, filename, ftp server, networkcredentials. Otherwise how can you re-use this method for other operations? </p></li>\n<li><p>I would probably avoid making the method static unless there was good reason to.</p></li>\n<li><p>In your finally clause you don't check if responseStream or writeStream are null? What if they never got created before an exception was thrown?</p></li>\n<li><p>I personally think unless there is a very valid reason you should always do something in an exception catch block, whether it be logging somewhere, re-throwing the exception or anything. Otherwise the calling method will have no idea that something went wrong.</p></li>\n<li><p>What is _result? I don't see it being set and I don't see it being declared anywhere?</p></li>\n<li><p>If Length is a constant, make it a constant. i.e. const int Length = 2048.</p></li>\n<li><p>I might also consider implementing some sort of call back method so you can provide status updates on the progress on the download. Just a suggestion, not sure how you would implement it exactly.</p></li>\n</ol>\n\n<p>I might consider writing the loop as such:</p>\n\n<pre><code>int bytesRead;\nwhile((bytesRead = responseStream.Read(buffer, 0, Length)) &gt; 0)\n{\n writeStream.Write(buffer, 0, bytesRead);\n}\n</code></pre>\n\n<p>As to your quesion. Is this code useful? In short. Yes, but only if you ever want to do only one thing with it and never want to re-use anything inside. Otherwise no.</p>\n\n<p>That's just a few comments off the top of my head. I hope those are a good starting point.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T21:14:24.797", "Id": "27850", "Score": "0", "body": "first thx so much for your answer , yes its static a sample , i will re-write hardcoded varibles later.I edited code a bit.My concern is i run this download function maybe 20 times(count of files in ftp folder).Must i use an ftp.dll for this job ? so i tried an ftp.dll for .net , this dll open connection once and gives to you dodownload() , doupload() , dorename() etc. functions.But somethimes i got socket error , missing file downloading etc. So i want to trust Framework libruary so i want to write myself :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T22:41:06.200", "Id": "27851", "Score": "0", "body": "I wouldn't suggest accepting this answer just yet Mennan. I'm pretty sure there are still lots of people that could contribute more or better to your question. Perhaps you might want to let it sit for a few days and see what other comments you get?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T23:06:05.777", "Id": "27852", "Score": "0", "body": "ok thx dreza..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T23:32:08.687", "Id": "27853", "Score": "1", "body": "You might want to consider removing the _ from your variable names. See http://msdn.microsoft.com/en-us/library/xzf533w0%28v=vs.71%29.aspx. also, you can remove the first bytesRead = line as that is covered in the while loop." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T20:53:57.817", "Id": "17508", "ParentId": "17506", "Score": "4" } }, { "body": "<p>If this process executes more than a single command in each interval, such as: upload something, then rename a file, then download something else - then it's not optimized.</p>\n\n<p>I suggest you use some kind of a library for FTP session, in which you should execute all of the commands in a single session. This should be better in terms of performance, since you're already connected to the FTP server, and therefore you already passed the firewalls and the FTP authentication.</p>\n\n<p>Update: so far I used several FTP libraries, some were free (long time ago, around .NET 1.1), some not (recently). I can't recommend a free library since I haven't recently used one. I suggest visiting free <a href=\"https://stackoverflow.com/questions/1371964/free-ftp-library\">ftp library question</a> (and answers) in stackoverflow for a discussion about the subject. However, I recently used the non free <a href=\"http://www.rebex.net/ftp-ssl.net/\" rel=\"nofollow noreferrer\">Rebex FTP</a> library, and it's excellent.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T16:36:47.183", "Id": "27875", "Score": "2", "body": "what you suggest as opensource and stable ftp libruary ?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T15:52:38.170", "Id": "17525", "ParentId": "17506", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T19:55:45.567", "Id": "17506", "Score": "3", "Tags": [ "c#", "ftp" ], "Title": "Is this FTP download code useful?" }
17506
<p>I currently use setInterval and a wait flag to process this collection. Is there a cleaner way?</p> <pre><code>var wait = false; var processInterval = setInterval(function(){ if(!wait){ var currentVideo = videos.shift(); if(currentVideo){ wait = true; validateSongById(currentVideo.videoId, function(result){ wait = false; if(result){ clearInterval(processInterval); callback(currentVideo); return; } }); } } }, 200); </code></pre>
[]
[ { "body": "<p>You're basically there, I would say. If the <code>validateSongById</code> function works as expected, it'll call its callback when it's done, and you then do it again for the next video.</p>\n\n<pre><code>function processVideos(videos, callback) {\n var results = [], i = 0;\n function processNext() {\n if(i &lt; videos.length) {\n validateSongById(videos[i].videoId, function (result) {\n results.push(result);\n i++;\n processNext();\n });\n } else {\n callback(results); // when called, all the videos have been processed\n }\n }\n processNext(); // start the processing\n}\n</code></pre>\n\n<p>With this, you call <code>processVideos</code> with the videos array and a callback. The callback is called with a new array of all the results.</p>\n\n<p>Alternatively, you can attach the result to the <code>video</code>-object directly, so the video and the result are tied together:</p>\n\n<pre><code>function processVideos(videos, callback) {\n var i = 0;\n function processNext() {\n if(i &lt; videos.length) {\n validateSongById(videos[i].videoId, function (result) {\n videos[i].result = result;\n i++;\n processNext();\n });\n } else {\n callback(); // when called, all the videos have been processed\n }\n }\n processNext(); // start the processing\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T00:06:42.667", "Id": "17512", "ParentId": "17510", "Score": "1" } } ]
{ "AcceptedAnswerId": "17512", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T23:22:49.473", "Id": "17510", "Score": "0", "Tags": [ "javascript", "jquery", "asynchronous" ], "Title": "Processing a collection of objects, one at a time, with an asynchronous method." }
17510
<p>What I can think of improving is:</p> <ul> <li>Show stack on screen to fail gracefully i.e. improved catch part of try..catch</li> <li>Make the try part shorter to improve readability</li> <li>Make imports with * to improve readability so you don't have to import the same package twice</li> </ul> <p>Source code:</p> <pre><code>//source is probably public domain since prv.se is a public authority: package se.prv.pandora.arendeprocess.actionhandler; import java.util.List; import org.apache.log4j.Logger; import se.prv.framework.forms.IFormData; import se.prv.framework.forms.IFormPattern; import se.prv.framework.general.Action; import se.prv.framework.general.ISessionHandler; import se.prv.pandora.arendeprocess.daos.AnsokanDAO; import se.prv.pandora.arendeprocess.entity.Ansokan; import se.prv.pandora.arendeprocess.exceptions.PandoraDAOException; import se.prv.pandora.arendeprocess.forms.NamnsokningFormPattern; import se.prv.pandora.arendeprocess.general.PandoraActionHandler; import se.prv.pandora.arendeprocess.obj.AnsokanInfo; import se.prv.pandora.arendeprocess.obj.ArendeProcessSessionData; import se.prv.pandora.arendeprocess.obj.ArendeSearchAdmin; import se.prv.pandora.arendeprocess.obj.ArendesokInfo; import se.prv.pandora.arendeprocess.util.ArendeComparatorManager; import se.prv.pandora.arendeprocess.util.ArendeProcessListComparator; import se.prv.pandora.arendeprocess.util.ArendeSokListComparator; import se.prv.pandora.arendeprocess.util.LookupHelper; import se.prv.pandora.arendeprocess.util.MenuManager; import se.prv.pandora.arendeprocess.util.PandoraAnsokanHandler; import se.prv.pandora.arendeprocess.util.PandoraFieldConstants; /** * @author Niklas Rosencrantz (adbnro) * */ public class ArendesokningActionHandler extends PandoraActionHandler { private ArendeProcessSessionData sessionData; private AnsokanDAO ansokanDAO; private int initialSort = ArendeProcessListComparator.INKOM_FIRST; private final static Logger logger = Logger.getLogger(ArendesokningActionHandler.class); protected IFormData getFormData() { return null; } protected IFormPattern getPattern() { return NamnsokningFormPattern.getInstance(); } public ArendesokningActionHandler(){ ansokanDAO = LookupHelper.lookup(se.prv.pandora.arendeprocess.daos.AnsokanDAO.class); } protected void performAction(ISessionHandler sessionHandler, Action action) { String returnPage = null; List&lt;AnsokanInfo&gt; ansokanInfoList = null; List&lt;AnsokanInfo&gt; sortedList = null; ArendesokInfo arendesokInfo = null; ArendeComparatorManager compManager = null; ArendeSearchAdmin admin = new ArendeSearchAdmin(); PandoraAnsokanHandler ansokanHandler = new PandoraAnsokanHandler(); try { sessionData = (ArendeProcessSessionData) sessionHandler.getSessionData(); MenuManager menuManager = sessionData.getMenuManager(); returnPage = menuManager.getLatestDestination(action.getActionTarget()); arendesokInfo = sessionData.getArendesokInfo(); if(arendesokInfo != null) { if(arendesokInfo.getArendeComparatorManager() != null) { compManager = arendesokInfo.getArendeComparatorManager(); } else { compManager = new ArendeComparatorManager(); } } else { arendesokInfo = new ArendesokInfo(); compManager = new ArendeComparatorManager(); } IFormData formData = sessionData.getFormData(); //ansokanInfo.setEditPersonInfo(null); if(action.getActionCommand().equalsIgnoreCase("choose")){ // TODO: Ska valideras //saveGrunduppgifter(formData, ansokanInfo, ansokan); returnPage = sessionData.getLatestAction().getCurrPage(); //"arendeprocess_grunduppgifter.jsp" } else if(action.getActionCommand().equalsIgnoreCase("search")){ logger.info("i search"); String search_arende = formData.getValue(PandoraFieldConstants.FIELD_SEARCH_ARENDE); List&lt;Ansokan&gt; ansokningar = ansokanDAO.search(search_arende); sessionData.setArendesokningLista(ansokanHandler.getAnsokanInfoFromAnsokan(ansokningar)); returnPage = sessionData.getLatestAction().getCurrPage(); } compManager.setLastSortNr(initialSort); ArendeSokListComparator comp = new ArendeSokListComparator(initialSort); sortedList = sortFormList(sessionData.getArendesokningLista(), comp); admin.setResultList(sortedList); admin.setNbOfHits(sortedList.size()); arendesokInfo.setArendeSearchAdmin(admin); arendesokInfo.setAnsokanInfoList(ansokanInfoList); arendesokInfo.setArendeComparatorManager(compManager); sessionData.setArendesokInfo(arendesokInfo); action.setReturnPage(returnPage); } catch (Exception e) { logger.error("ArendesokningActionHandler: performAction() ", e); throw new PandoraDAOException(e, "performAction()", "Error. Transaction must be rolled back: " + e.getMessage()); } } List&lt;AnsokanInfo&gt; sortFormList(List&lt;AnsokanInfo&gt; resultList1, ArendeSokListComparator comp) { java.util.Collections.sort(resultList1, comp); return resultList1; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T01:53:21.897", "Id": "27855", "Score": "0", "body": "You might want to consider putting some spacing and indentation around your code segments to make it easier for people to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T02:03:07.853", "Id": "27856", "Score": "0", "body": "@dreza Thank you for the comment. I failed formatting and tried posting the source anyways." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T02:47:28.740", "Id": "27857", "Score": "0", "body": "I've often struggled with formatting when I follow code straight after bullet points as well. I find putting some text between the bullet and the code helps (see my edit)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T03:01:49.753", "Id": "27858", "Score": "1", "body": "Where you are setting your variables to null in performAction. I would pull that into a private method to make it easier to read." } ]
[ { "body": "<blockquote>\n <p>Make imports with * to improve readability so you don't have to import the same package twice</p>\n</blockquote>\n\n<p>I disagree with that:</p>\n\n<ul>\n<li><p>Most people use IDEs to develop and view Java code, and any half-decent IDE is able to \"fold\" imports to save screen real-estate.</p></li>\n<li><p>\"*\" imports have the problem that otherwise harmless changes external to your class can lead to compilation errors. Consider this:</p>\n\n<pre><code>import java.util.*;\nimport com.foobar.foolib.*;\n\npublic MyClass {\n List list = ...;\n}\n</code></pre>\n\n<p>Today, that may compile fine. But if the \"foobar\" folks decide to add a class called \"com.foobar.foolib.List\" in the next version of the library, then when change my dependencies, <strong>my</strong> code will now give compilation errors because <code>List</code> is now being imported from two different places. (OK, the \"foobar\" guys have made a particularly bad choice of classname here ... but it is also my fault for using \"*\" imports.)</p></li>\n</ul>\n\n<blockquote>\n <p>Show stack on screen to fail gracefully i.e. improved catch part of try..catch</p>\n</blockquote>\n\n<p>Do you really want to show stacktraces to end users? I actually think you have probably got the logging right.</p>\n\n<hr>\n\n<p>Here are some comments of my own:</p>\n\n<ul>\n<li><p>It is not a good idea to always initialize local variables. If you think it is a good idea to declare them all at the start of the method, then it is better to leave off the initializers. That way, the compiler can tell you if you use a variable before it is initialized. By contrast, if you dummy initialize with some nonsense value (e.g. <code>null</code>), the compiler can't tell you that you have missed out the real initialization.</p></li>\n<li><p>I have some concerns with this:</p>\n\n<pre><code>} catch (Exception e) {\n logger.error(\"ArendesokningActionHandler: performAction() \", e);\n throw new PandoraDAOException(e, \"performAction()\", \n \"Error. Transaction must be rolled back: \" + e.getMessage());\n}\n</code></pre>\n\n<p>Three concerns:</p>\n\n<ol>\n<li>You are catching <code>Exception</code>, and that is usually a bad idea. (Whether it is in this case is hard to determine ...)</li>\n<li>There is something fishy about throwing <code>PandoraDAOException</code> from a class that doesn't appear to be a DAO class.</li>\n<li><p>There is something fishy about a non-DAO class saying <code>\"Transaction must be rolled back\"</code>. Surely, this class should not <em>know</em> about transactions.</p>\n\n<p>It strikes me that that all three of this fall under the general concern of separation of responsibility. This class seems to be doing things / knowing things that shouldn't really be its responsibility.</p></li>\n</ol></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T03:55:52.733", "Id": "17515", "ParentId": "17514", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T01:09:31.213", "Id": "17514", "Score": "1", "Tags": [ "java", "search" ], "Title": "Kindly review this class" }
17514
<p>Examples: </p> <pre><code>char test1[] = " "; char test2[] = " hello z"; char test3[] = "hello world "; char test4[] = "x y z "; </code></pre> <p>Results:</p> <pre><code>" " " olleh z" "olleh dlrow " "x y z " </code></pre> <p>The problem:</p> <blockquote> <p>Reverse every world in a string, ignore the spaces.</p> <p>The following is my code. The basic idea is to scan the string, when finding a word, then reverse it. The complexity of the algorithm is O(n), where n is the length of the string.</p> </blockquote> <p>Could anyone help me verify it? Is there any better solution?</p> <pre><code>void reverse_word(char* s, char* e) { while(s &lt; e) { char tmp = *s; *s = *e; *e = tmp; ++s; --e; } } char* word_start_index(char* p) { while((*p != '\0') &amp;&amp; (*p == ' ')) { ++p; } if(*p == '\0') return NULL; else return p; } char* word_end_index(char* p) { while((*p != '\0') &amp;&amp; (*p != ' ')) { ++p; } return p-1; } void reverse_string(char* s) { char* s_w = NULL; char* e_w = NULL; char* runner = s; while(*runner != '\0') { char* cur_word_s = word_start_index(runner); if(cur_word_s == NULL) break; char* cur_word_e = word_end_index(cur_word_s); reverse_word(cur_word_s, cur_word_e); runner = cur_word_e+1; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T05:01:04.830", "Id": "27859", "Score": "0", "body": "I'd skip the spaces in the main loop, instead of having them in the start index calculations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T00:17:51.087", "Id": "27894", "Score": "1", "body": "Your functions `word_end_index` and `word_start_index` are effectively rewriting `strcspn` and `strspn`. Checkout the standard library!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T14:03:24.070", "Id": "28095", "Score": "0", "body": "Interview in Boulder much?" } ]
[ { "body": "<p>If using C++ is an option for you (which your tags suggest), then you might consider using <a href=\"http://en.cppreference.com/w/cpp/algorithm/swap\"><code>std::swap</code></a> for swapping the characters. You might also want to use <a href=\"http://en.cppreference.com/w/c/string/byte/isspace\"><code>isspace</code></a> to check for whitespace other than <code>' '</code>.</p>\n\n<p>You could also write it all in a single function:</p>\n\n<pre><code>void reverse_every_word(char* s)\n{\n char* front;\n char* back;\n while(*s != '\\0')\n {\n // handle whitespace\n while(*s != '\\0' &amp;&amp; isspace(*s))\n s++;\n\n // skip to the end of the current word\n front = s;\n while(*s != '\\0' &amp;&amp; !isspace(*s))\n s++;\n\n // reverse\n back = s-1;\n while (front &lt; back)\n std::swap(*front++, *back--);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T13:55:21.123", "Id": "17557", "ParentId": "17517", "Score": "5" } }, { "body": "<h3>Comments on code</h3>\n<p>In C++ code you do not want to be messing with C-Strings. All that memory management makes the code hard to maintain and is difficult to get correct. prefer to use std::string which does all the hard work and lets you concentrate on the algorithm.</p>\n<pre><code>void reverse_word(char* s, char* e)\n</code></pre>\n<p>There are already algorithms for reversing stuff <code>std::reverse()</code> and swapping the two values <code>std::swap()</code> so there is no need to implement either.</p>\n<pre><code> while(s &lt; e)\n {\n char tmp = *s;\n *s = *e;\n *e = tmp;\n ++s;\n --e;\n }\n</code></pre>\n<p>Space <code>' '</code> is not the only <em>white space character</em>. Rather than explicitly testing for a space you should use the standard function for testing if a character is white space <code>std::is_space()</code></p>\n<pre><code> while((*p != '\\0') &amp;&amp; (*p == ' '))\n \n</code></pre>\n<h3>Comments on Algorithm</h3>\n<p>There is already a std::reverse() algorithm.<br />\nUsing this would reduce the complexity of your code to just finding the beginning and end of each word. Since <code>operator&gt;&gt;</code> does this automatically it makes the code very trivial:</p>\n<pre><code>void reverse_string(std::string&amp; paragraph)\n{\n std::stringstream pStream(paragraph);\n std::string word;\n\n paragraph.clear();\n while(pStream &gt;&gt; word)\n {\n std::reverse(word.begin(), word.end());\n paragraph.append(word);\n paragraph.append(&quot; &quot;);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T05:49:34.253", "Id": "28078", "Score": "0", "body": "Thanks very much Loki. For the function reverse_string, does it keep the original white space?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T06:45:27.920", "Id": "28080", "Score": "0", "body": "No. Space is dropped." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T14:25:30.167", "Id": "17558", "ParentId": "17517", "Score": "4" } }, { "body": "<p>Having C++11, we could do,</p>\n\n<pre><code>template&lt;class InputIterator, class UnaryPredicate&gt;\nvoid reverseSeparate(InputIterator first, InputIterator last, UnaryPredicate pred)\n{\n first = std::find_if_not(first,last,pred);\n while(first!=last){\n InputIterator t = std::find_if(first,last,pred);\n std::reverse(first,t);\n first = std::find_if_not(t,last,pred);\n }\n}\n</code></pre>\n\n<p>using this, we can (among other things) reverse every word in a string.</p>\n\n<pre><code>std::string s = \"hi hello world \";\nreverseSeparate(s.begin(),s.end(), [](char c){return c==' ';});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-13T12:33:40.763", "Id": "29682", "ParentId": "17517", "Score": "2" } } ]
{ "AcceptedAnswerId": "17557", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T04:46:50.480", "Id": "17517", "Score": "8", "Tags": [ "c", "strings", "interview-questions" ], "Title": "Reversing every word in a string" }
17517