body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have an extension method that does this:</p> <pre><code>public static IEnumerable&lt;T&gt; ToIEnumerable&lt;T&gt;(this T source) where T : new() { return new[] { source }; } </code></pre> <p>I need to be able to convert any object to an <code>IEnumerable</code>.</p> <p>For example when I use the .NET <code>Except</code> method:</p> <pre><code>public static IEnumerable&lt;TSource&gt; Except&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; first) </code></pre> <p>I can call <code>Except</code> by doing the following:</p> <pre><code>return objects.Except(this.ToIEnumerable()); </code></pre> <p><strong>Is <code>ToIEnumerable&lt;T&gt;</code> good practice or should I solve the problem in differently?</strong></p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T09:19:26.303", "Id": "1591", "Score": "0", "body": "Doesn't the first method return an array of T while the second one returns an IEnumerable of T?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T10:32:55.873", "Id": "1695", "Score": "2", "body": "There are probably better names for the method. AsSingleton is what I'd use unless it risks being confused for the singleton design pattern." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T19:24:51.790", "Id": "1750", "Score": "0", "body": "I agree with Peter. I would expect that calling ToEnumerable on a collection would yield the contents of the collection (maybe taking a snapshot), rather than an enumerable containing the collection as a single item. Returning an array is probably more efficient than using a Yield, though it has the slight disadvantage that if it's cast back to an array one could write to it. Not a huge problem (since ToIEnumerable creates a new array, such a write would only affect future attempts to enumerate it) but worth noting." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T07:04:52.840", "Id": "1763", "Score": "0", "body": "@supercat @Peter, Very good name! I will use it." } ]
[ { "body": "<p>I don't see why not.</p>\n\n<p>If you wanted to be 'monadically pure', you could call it <code>Return</code> (because in monads, the function which performs <code>'a -&gt; M 'a</code> is called <code>return</code>).</p>\n\n<p>(See <a href=\"https://stackoverflow.com/questions/1577822/passing-a-single-item-as-ienumerablet\">this question</a>: <code>FromSingleItem</code>, or <code>AsEnumerable</code> - someone there also suggested using the existing <code>Enumerable.Repeat(T item, int count)</code>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:39:39.763", "Id": "1605", "Score": "0", "body": "That is why in the Reactive Extensions the EnumerableEx class has a Return method, that does exactly that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-18T13:38:20.360", "Id": "839", "ParentId": "836", "Score": "3" } }, { "body": "<p>While I don't see why <code>ToIEnumerable</code> is bad practice, in this specific case I think it is. You're comparing with only one object; why not just attach a where clause on to things? I.e.</p>\n\n<pre><code>return objects.Where((other) =&gt; other != this);\n</code></pre>\n\n<p>or possibly </p>\n\n<pre><code>return objects.Where((other) =&gt; !Object.ReferenceEquals(other, this));\n</code></pre>\n\n<p>Not only will this perform better than Except here, but it's easier to understand, and avoids the entire ToIEnumerable thing entirely.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-31T00:36:26.253", "Id": "2737", "Score": "1", "body": "you don't need the parens around `(other)` in either case." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-18T16:44:28.403", "Id": "841", "ParentId": "836", "Score": "7" } }, { "body": "<p>It's potentially annoying to have an extension method like that turn up on almost every type. With just a single one, it's probably a minor irritation at most, but in the future you may find yourself coming up with more <code>this object</code> or <code>this T</code> extension methods, and either you'll start to get a very clogged up Intellisense. So think about whether this is really something that you want frequently enough to justify it. If you're working on code that may be maintained by colleagues, check their opinions.</p>\n\n<p>Note also that <code>new[] { source }</code> actually has fewer characters than <code>source.ToIEnumerable()</code>. Which is more readable and clear in stating what it is doing is arguable, but at least the array is instantly universally recognisable.</p>\n\n<p>So while it would be harsh to say that it's \"bad practice\", on balance I would probably advise slightly against it. If the benefits seem to outweigh the costs to you, though, then go for it.</p>\n\n<p>As a side-note, you don't need your <code>where T : new()</code> condition, either. It's the array that you're creating a new instance of, not the <code>T</code> itself.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-17T16:41:49.497", "Id": "57316", "ParentId": "836", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-18T12:17:19.520", "Id": "836", "Score": "4", "Tags": [ "c#", "linq", "ienumerable" ], "Title": "Is ToIEnumerable<T> good practice?" }
836
<p>I think there are some confusing and weird indentation problems in this WordPress file (single.php). Any suggestions on improving indentation and readability?</p> <pre><code>&lt;?php /** * The Template for displaying all single posts. * * @package WordPress * @subpackage Starkers * @since Starkers 3.0 */ get_header(); ?&gt; &lt;?php get_sidebar(); ?&gt; &lt;div id="content"&gt; &lt;?php // Set and display custom field $intro_image = get_post_meta($post-&gt;ID, 'Intro Image', true); ?&gt; &lt;div class="block-1"&gt; &lt;img src="&lt;?php echo $intro_image; ?&gt;" alt="" /&gt; &lt;/div&gt; &lt;?php ?&gt; &lt;?php // Start The Loop if ( have_posts() ) while ( have_posts() ) : the_post(); ?&gt; &lt;div class="block-2 padding-top no-overlay"&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt;&lt;!-- .entry-content --&gt; &lt;?php endwhile; // end of the loop. ?&gt; &lt;?php // Display previous and next posts thumbnails ?&gt; &lt;div class="block-2 border-top"&gt; &lt;?php // Set and display custom field $mainbar_left_title = get_post_meta($post-&gt;ID, 'Mainbar Left Title', true); $mainbar_left_image = get_post_meta($post-&gt;ID, 'Mainbar Left Image', true); ?&gt; &lt;div class="float-left"&gt; &lt;h2&gt;&lt;?php echo $mainbar_left_title; ?&gt;&lt;/h2&gt; &lt;img src="&lt;?php echo $mainbar_left_image ?&gt;" alt="" /&gt; &lt;/div&gt; &lt;?php ?&gt; &lt;?php // Set and display custom field $mainbar_right_title = get_post_meta($post-&gt;ID, 'Mainbar Right Title', true); $mainbar_right_image = get_post_meta($post-&gt;ID, 'Mainbar Right Image', true); ?&gt; &lt;div class="float-right"&gt; &lt;h2&gt;&lt;?php echo $mainbar_right_title; ?&gt;&lt;/h2&gt; &lt;img src="&lt;?php echo $mainbar_right_image ?&gt;" alt="" /&gt; &lt;/div&gt; &lt;?php ?&gt; &lt;/div&gt; &lt;?php // Set and display custom field $mainbar_right_title = get_post_meta($post-&gt;ID, 'Mainbar Right Title', true); $mainbar_right_image = get_post_meta($post-&gt;ID, 'Mainbar Right Image', true); ?&gt; &lt;div class="block-3 border-top"&gt; &lt;h2&gt;&lt;?php echo $mainbar_right_title; ?&gt;&lt;/h2&gt; &lt;img src="&lt;?php echo $mainbar_right_image ?&gt;" alt="" /&gt; &lt;/div&gt; &lt;?php ?&gt; &lt;?php // Start The Loop if ( have_posts() ) while ( have_posts() ) : the_post(); ?&gt; &lt;div class="block-4 border-top"&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt;&lt;!-- .entry-content --&gt; &lt;?php endwhile; // end of the loop. ?&gt; &lt;?php get_sidebar('secondary'); ?&gt; &lt;/div&gt;&lt;!-- #content --&gt; &lt;?php get_footer(); ?&gt; </code></pre>
[]
[ { "body": "<pre><code>&lt;?php // Start The Loop\n if ( have_posts() ) while ( have_posts() ) : the_post();\n?&gt; &lt;div class=\"block-2 padding-top no-overlay\"&gt;\n &lt;?php the_content(); ?&gt;\n &lt;/div&gt;&lt;!-- .entry-content --&gt;\n&lt;?php endwhile; // end of the loop. ?&gt; \n</code></pre>\n\n<p>That could become:</p>\n\n<pre><code>&lt;?php // Start The Loop\n if (have_posts()) {\n while (have_posts()) : the_post(); ?&gt;\n &lt;div class=\"block-2 padding-top no-overlay\"&gt;\n &lt;?php the_content(); ?&gt;\n &lt;/div&gt;&lt;!-- .entry-content --&gt;\n &lt;?php endwhile; // end of the loop.\n } ?&gt;\n</code></pre>\n\n<p>Still a bit confusing, but I'll keep thinking about it.</p>\n\n<p>Another idea, that uses more <code>&lt;?php&gt;</code> tags:</p>\n\n<pre><code>&lt;?php if (have_posts()) { // Start the loop ?&gt;\n &lt;? while (have_posts()) : the_post(); ?&gt;\n &lt;div class=\"block-2 padding-top no-overlay\"&gt;\n &lt;?php the_content(); ?&gt;\n &lt;/div&gt;&lt;!-- .entry-content --&gt;\n &lt;?php endwhile; // end of the loop. ?&gt;\n&lt;?php } ?&gt;\n</code></pre>\n\n<p>Another section change:</p>\n\n<pre><code>&lt;?php // Set and display custom field\n $mainbar_right_title = get_post_meta($post-&gt;ID, 'Mainbar Right Title', true);\n $mainbar_right_image = get_post_meta($post-&gt;ID, 'Mainbar Right Image', true);\n?&gt;\n&lt;div class=\"float-right\"&gt;\n &lt;h2&gt;&lt;?php echo $mainbar_right_title; ?&gt;&lt;/h2&gt;\n &lt;img src=\"&lt;?php echo $mainbar_right_image ?&gt;\" alt=\"\" /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>There's a seemingly useless <code>&lt;?php \\n ?&gt;</code> sitting there. It looks like the idea was to close a code block, but it doesn't do anything. I removed that and changed the indentation so it didn't look like a block.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-18T14:09:34.423", "Id": "1559", "Score": "0", "body": "I think looks cleaner but is there a way of making the end match horizontally with the top?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-18T14:17:31.357", "Id": "1560", "Score": "0", "body": "I posted another idea - it would be easier to read as well if you can use `<? ?>` instead of `<?php ?>`. Is that an option?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-18T14:29:36.683", "Id": "1561", "Score": "0", "body": "Sorry it is against the law: http://codex.wordpress.org/WordPress_Coding_Standards (I will wait more answers for 2 days if there's no more I will check yours. Thanks.)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-18T14:33:56.110", "Id": "1562", "Score": "0", "body": "@janoChen: Interesting read." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-18T14:06:29.280", "Id": "840", "ParentId": "837", "Score": "3" } }, { "body": "<p>You could you PHP <a href=\"http://php.net/manual/en/control-structures.alternative-syntax.php\" rel=\"noreferrer\">alternate syntax</a></p>\n\n<pre><code>&lt;?php\n/**\n * The Template for displaying all single posts.\n *\n * @package WordPress\n * @subpackage Starkers\n * @since Starkers 3.0\n */\n?&gt;\n\n&lt;?php get_header(); \n&lt;?php get_sidebar(); ?&gt;\n\n&lt;div id=\"content\"&gt;\n &lt;?php $intro_image = get_post_meta($post-&gt;ID, 'Intro Image', true); ?&gt;\n &lt;div class=\"block-1\"&gt;\n &lt;img src=\"&lt;?php echo $intro_image; ?&gt;\" alt=\"\" /&gt;\n &lt;/div&gt;\n\n &lt;?php if ( have_posts() ? while ( have_posts() ) : the_post()): ?&gt; \n &lt;div class=\"block-2 padding-top no-overlay\"&gt;\n &lt;?php the_content(); ?&gt;\n &lt;/div&gt;\n &lt;?php endwhile; ?&gt;\n\n &lt;div class=\"block-2 border-top\"&gt;\n &lt;?php $mainbar_left_title = get_post_meta($post-&gt;ID, 'Mainbar Left Title', true); ?&gt;\n &lt;?php $mainbar_left_image = get_post_meta($post-&gt;ID, 'Mainbar Left Image', true); ?&gt;\n &lt;div class=\"float-left\"&gt;\n &lt;h2&gt;&lt;?php echo $mainbar_left_title; ?&gt;&lt;/h2&gt;\n &lt;img src=\"&lt;?php echo $mainbar_left_image ?&gt;\" alt=\"\" /&gt;\n &lt;/div&gt;\n\n &lt;?php $mainbar_right_title = get_post_meta($post-&gt;ID, 'Mainbar Right Title', true); ?&gt;\n &lt;?php $mainbar_right_image = get_post_meta($post-&gt;ID, 'Mainbar Right Image', true); ?&gt;\n &lt;div class=\"float-right\"&gt;\n &lt;h2&gt;&lt;?php echo $mainbar_right_title; ?&gt;&lt;/h2&gt;\n &lt;img src=\"&lt;?php echo $mainbar_right_image ?&gt;\" alt=\"\" /&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n &lt;?php $mainbar_right_title = get_post_meta($post-&gt;ID, 'Mainbar Right Title', true); ?&gt;\n &lt;?php $mainbar_right_image = get_post_meta($post-&gt;ID, 'Mainbar Right Image', true); ?&gt;\n &lt;div class=\"block-3 border-top\"&gt;\n &lt;h2&gt;&lt;?php echo $mainbar_right_title; ?&gt;&lt;/h2&gt;\n &lt;img src=\"&lt;?php echo $mainbar_right_image ?&gt;\" alt=\"\" /&gt;\n &lt;/div&gt;\n\n &lt;?php if ( have_posts() ? while ( have_posts() ) : the_post()): ?&gt;\n &lt;div class=\"block-4 border-top\"&gt;\n &lt;?php the_content(); ?&gt;\n &lt;/div&gt;\n &lt;?php endwhile; ?&gt;\n\n &lt;?php get_sidebar('secondary'); ?&gt;\n&lt;/div&gt;\n\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p>This follows all WP coding standards from what I can tell and is readable.\nI would also suggest changing sections like this:</p>\n\n<pre><code>&lt;?php $mainbar_right_title = get_post_meta($post-&gt;ID, 'Mainbar Right Title', true); ?&gt;\n&lt;?php $mainbar_right_image = get_post_meta($post-&gt;ID, 'Mainbar Right Image', true); ?&gt;\n&lt;div class=\"block-3 border-top\"&gt;\n &lt;h2&gt;&lt;?php echo $mainbar_right_title; ?&gt;&lt;/h2&gt;\n &lt;img src=\"&lt;?php echo $mainbar_right_image ?&gt;\" alt=\"\" /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>&lt;div class=\"block-3 border-top\"&gt;\n &lt;h2&gt;&lt;?php echo get_post_meta($post-&gt;ID, 'Mainbar Right Title', true); ?&gt;&lt;/h2&gt;\n &lt;img src=\"&lt;?php echo get_post_meta($post-&gt;ID, 'Mainbar Right Image', true) ?&gt;\" alt=\"\" /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Although that's just personal preference, I find it much more readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T12:52:01.923", "Id": "1593", "Score": "0", "body": "haha well if it helps, it's considered bad practice to use braces `{` `}` for conditional or control structure in php templates. In the link you provided, although it shows the correct WP coding standard for for conditionals or control structures that have braces. The example if statement further down the page uses alternate syntax." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T02:41:31.897", "Id": "863", "ParentId": "837", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-18T12:51:36.253", "Id": "837", "Score": "5", "Tags": [ "php", "wordpress" ], "Title": "Displaying all single posts" }
837
<p>I'm new to Java and find it hard to grasp the concept of objects. I wrote a simple guessing game to practice the concept of OO programming but I am not sure if I am doing it correctly. </p> <p>The objective of the game is to guess a number from 0-9 with 3 players and the first player who guesses it correctly will win the game.</p> <p><strong>Player</strong></p> <pre><code>public class Player { private String playerName; private int number; public int getNumber() { return number; } public String getPlayerName() { return playerName; } public void setPlayerName(String playerName) { this.playerName = playerName; } public void guessNumber(){ number = Integer.parseInt(JOptionPane.showInputDialog(playerName + "'s Turn\nGuess the Number")); JOptionPane.showMessageDialog(null, playerName+ "'s GUESS is " + number); } } </code></pre> <p><strong>GuessGame</strong></p> <pre><code>public class GuessGame { private int numberToGuess; private Player p1; private Player p2; private Player p3; public void startGame(){ numberToGuess = (int) (Math.random()*10); p1 = new Player(); p2 = new Player(); p3 = new Player(); p1.setPlayerName(JOptionPane.showInputDialog("Enter Player 1 Name: ")); p2.setPlayerName(JOptionPane.showInputDialog("Enter Player 2 Name: ")); p3.setPlayerName(JOptionPane.showInputDialog("Enter Player 3 Name: ")); int flagWinner = 0; while(0==flagWinner){ p1.guessNumber(); if (p1.getNumber()==numberToGuess){ flagWinner = 1; break; } JOptionPane.showMessageDialog(null, p1.getPlayerName() + "'s Guess is Wrong!"); p2.guessNumber(); if (p2.getNumber()==numberToGuess){ flagWinner = 2; break; } JOptionPane.showMessageDialog(null, p2.getPlayerName() + "'s Guess is Wrong!"); p3.guessNumber(); if (p3.getNumber()==numberToGuess){ flagWinner = 3; break; } JOptionPane.showMessageDialog(null, p3.getPlayerName() + "'s Guess is Wrong!"); } if (1 == flagWinner){ JOptionPane.showMessageDialog(null,p1.getPlayerName()+ " Wins!"); } else if (2 == flagWinner){ JOptionPane.showMessageDialog(null,p2.getPlayerName()+ " Wins!"); } else JOptionPane.showMessageDialog(null,p3.getPlayerName()+ " Wins!"); } } </code></pre> <p>And I have a <code>gameLauncher</code> where I have the <code>main()</code> method which creates the game.</p> <p>Am I doing it correctly especially in the <code>Player</code> class where I created a method <code>guessNumber()</code> instead of setter <code>setNumber(int number)</code>? </p> <p>Am I violating any object-oriented concepts in my code? </p> <p>How can I improve my code?</p>
[]
[ { "body": "<p>The layout felt very C++ and very connected to \"functions\" instead of objects. Though you seem to got a nice idea of how it's work and do a lot better at objects than most people do.</p>\n\n<p>I would do it like this (dirty version, should be improved, but it was a quick redesign):</p>\n\n<pre><code>public class Player {\n private String playerName;\n private int number;\n\n public Player(String name){\n this.playerName = name;\n }\n\n public int guessNumber() {\n return Integer.parseInt(JOptionPane.showInputDialog(playerName\n +\"'s Turn\\nGuess the Number\"));\n JOptionPane.showMessageDialog(null, playerName+ \"'s GUESS is \" + number);\n }\n\n public String getPlayerName() {\n return playerName;\n }\n}\n\npublic class GuessGame {\n\n private int numberToGuess;\n private Player p1;\n private Player p2;\n private Player p3;\n\n //Would probably made amount of players dynamic as well.\n public GuessGame(String player1, String player2, String player3){\n numberToGuess = (int) (Math.random()*10);\n p1 = new Player(player1);\n p2 = new Player(player2);\n p3 = new Player(player3);\n }\n\n //Would probably split this up in submethods too.\n //The flagging is quite ugly too but I don't got time to edit it.\n public void startGame(){\n int flagWinner = 0;\n while(0==flagWinner){\n if (p1.guessNumber()==numberToGuess){\n flagWinner = 1;\n break;\n }\n JOptionPane.showMessageDialog(null, p1.getPlayerName()\n + \"'s Guess is Wrong!\");\n if (p2.guessNumber()==numberToGuess){\n flagWinner = 2;\n break;\n }\n JOptionPane.showMessageDialog(null,p2.getPlayerName()\n + \"'s Guess is Wrong!\");\n if (p3.guessNumber()==numberToGuess){\n flagWinner = 3;\n break;\n }\n JOptionPane.showMessageDialog(null,p3.getPlayerName()\n + \"'s Guess is Wrong!\");\n }\n if (1 == flagWinner){\n JOptionPane.showMessageDialog(null,p1.getPlayerName()+ \" Wins!\");\n } else if (2 == flagWinner){\n JOptionPane.showMessageDialog(null,p2.getPlayerName()+ \" Wins!\");\n } else JOptionPane.showMessageDialog(null,p3.getPlayerName()+ \" Wins!\");\n }\n\n public static void main(String[] e){\n GuessGame gg = new GuessGame(\n JOptionPane.showInputDialog(\"Enter Player 1 Name: \"),\n JOptionPane.showInputDialog(\"Enter Player 2 Name: \"),\n JOptionPane.showInputDialog(\"Enter Player 3 Name: \")\n );\n gg.startGame();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-19T10:59:26.037", "Id": "851", "ParentId": "850", "Score": "2" } }, { "body": "<p>To start with, spot the inconsistency. For the name you create it in your main loop and then use a setter; for the number you have a method in the Player object to acquire the guess. The latter is more in line with the message-passing philosophy of OO. (Many people seem to think that using getters and setters is being OO. They're often - not always - a sign of non-OO thinking). However, it doesn't take it as far as it could. The number guessed isn't a property of the player - it's a property of the guess.</p>\n\n<p>Guessing a number isn't the same thing as displaying it - either rename the method or, probably better - a method should do one thing - move that out.</p>\n\n<p>Next up, the <code>flagWinner</code> is a big red flag. Its sole purpose is to identify one of the objects <code>p1</code>, <code>p2</code>, <code>p3</code>, or none of the above. What's the OO way to do that? Use the object to identify itself.</p>\n\n<p>I'd be inclined to factor out the IO as an object too, to be a bit less procedural. So without going into a full over-patterned architecture we have</p>\n\n<pre>\npublic class IO {\n public void output(String msg) {\n JOptionPane.showMessageDialog(null, msg);\n }\n\n public String input(String prompt) {\n return JOptionPane.showInputDialog(prompt)\n }\n\n public int inputInt(String prompt) {\n return Integer.parseInt(input(prompt));\n }\n}\n\npublic class Player {\n private String playerName;\n\n private Player(String name) {\n playerName = name;\n }\n\n public static Player createPlayer(IO io, String prompt) {\n String name = io.input(\"Enter \" + prompt + \" Name: \");\n return new Player(name);\n }\n\n public String getPlayerName() {\n return playerName;\n }\n\n public int guessNumber(IO io) {\n return io.inputInt(playerName +\"'s Turn\\nGuess the Number\"));\n }\n}\n\npublic class GuessGame {\n\n private final IO io;\n private final int numPlayers;\n private int numberToGuess;\n private List&lt;Player&gt; players = new LinkedList&lt;Player&gt;();\n\n public GuessGame(IO io, int numPlayers) {\n this.io = io;\n this.numPlayers = numPlayers;\n }\n\n public void init() {\n numberToGuess = (int) (Math.random()*10);\n for (int i = 0; i &lt; numPlayers; i++) {\n players.add(Player.createPlayer(io, \"Player \" + (i+1)));\n }\n }\n\n public void runGame(){\n init();\n\n Player winner = null;\n Iterator&lt;Player&gt; it = players.iterator();\n while (winner == null) {\n if (!it.hasNext()) {\n it = players.iterator();\n }\n\n Player turnPlayer = it.next();\n String playerName = turnPlayer.getPlayerName();\n\n int guess = turnPlayer.guessNumber(io);\n io.output(playerName+ \"'s GUESS is \" + number);\n\n if (guess == numberToGuess) {\n winner = turnPlayer;\n }\n else {\n io.output(playerName + \"'s Guess is Wrong!\");\n }\n }\n\n io.output(winner.getPlayerName()+ \" Wins!\");\n }\n}\n</pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T06:37:42.333", "Id": "3086", "Score": "0", "body": "Your IO-class has no attributes, so all methods could be made static, and every instance removed/replaced with IO. And a lot of minor coding error can be found: IO.output should be void, inputInt return an Int, createPlayer has to be static, the second it = p.iterator should be it=p.next (); String playerName with capital S and so on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T09:02:05.237", "Id": "3087", "Score": "2", "body": "@user, most of those points are correct, thanks. IO is deliberately not made static because I was refactoring the OP's code with an eye to making it easy to make more OO, and that class is en-route to becoming an interface. And the second `it=p.iterator()` is correct: it resets the iterator to the start to allow looping through the players more than once." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T09:14:12.933", "Id": "3088", "Score": "2", "body": "IO should **not** be static, it is good the way it is. This design makes it easy to write different versions (e.g. a console input version, or a version for JUnit tests), and to switch to Dependency Injection (e.g. Spring or Guice) later. static is not an OO concept (e.g. doesn't play nice with inheritance) and should be avoided if possible, except for \"constants\" and for functions that will never ever change (say Math.sin)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-11T09:27:02.293", "Id": "3089", "Score": "0", "body": "p.next, I see now. :) My fault. @Landei (Landei? Hi!): I have to think about the static question, and hope I will not forget it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-21T18:58:15.720", "Id": "253895", "Score": "0", "body": "GG :) I would rename IO to UI but otherwise nice and clear" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-21T19:01:24.373", "Id": "253896", "Score": "0", "body": "@Peter how can quote your answer? there are like 20 questions like this one ... I guess some that's some schools homework. and yes your answer is very good example of OOP design. Bounty should be for you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-07-22T07:09:47.520", "Id": "253958", "Score": "1", "body": "@deian, if you just want to link to the answer, there's a \"share\" link between the answer itself and the comments. It gives you a short URL which includes your user ID, and people following it are counted for the \"Announcer\" family of badges. If you want to quote parts of the answer verbatim in your own answer, you can use the \"edit\" link to copy the original Markdown, and then if you add `> ` before each line it will be processed into a blockquote. You should also link back to the original answer. See https://blog.stackoverflow.com/2009/06/attribution-required/" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-19T12:27:58.477", "Id": "852", "ParentId": "850", "Score": "11" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-19T10:18:26.970", "Id": "850", "Score": "15", "Tags": [ "java", "object-oriented", "game", "swing" ], "Title": "Guessing game - am I using the concept of objects in Java properly?" }
850
<p>So... I have a program in which I want to flip heads three times in the row.</p> <p>What I'm asking for is for proposals of other solutions for this program, in pro way, as You do in natural sense.</p> <p>That's my code as Java novice.</p> <pre><code>/* * File: ConsecutiveHeads.java * ---------------- * This program flips a coin repeatly until three consecutive heads * are tossed. */ import acm.program.*; import acm.util.*; public class ConsecutiveHeads extends ConsoleProgram { /* Run the program */ public void run() { println("This program flips a coin until there are three" + "heads in the row."); while(counter != 3) { FlipACoin(); } println("Yupii! There are already three same heads in the row :)"); } /* Flip a coin. Then if heads are tossed, increment our counter. * In tails case, zero counter. */ private void FlipACoin() { boolean rank = rgen.nextBoolean(); if(rank) { println("heads"); counter++; } else { println("tails"); counter = 0; } } /* Create an instance variable for the random number generator */ private RandomGenerator rgen = new RandomGenerator(); /* Create an instance variable for counter detecting three heads in row */ private int counter = 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-19T17:01:11.933", "Id": "1587", "Score": "0", "body": "Unless you need cryptographic stength randomness, this approach is good." } ]
[ { "body": "<p>Some things you could consider</p>\n\n<ul>\n<li>make the starting class a simple program which calls other methods and/or classes to do most of the work.</li>\n<li>if you want something more general, you could use an abstract output stream so it can be captured or even use a Listener interface.</li>\n<li>make fields which are not intended to change <code>final</code> this can improve clarity.</li>\n<li>is it conventional to place fields then constructors then methods as the class order.</li>\n<li>you could restructure the fields/method calls to be thread safe if that might be an issue. e.g. SimpleDateFormat is not thread-safe and causes no end of concern.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T20:37:15.783", "Id": "33023", "Score": "1", "body": "I can tell you're unfamiliar with the ACM Library. These suggestions would make perfect sense, but they don't apply to ACM. ConsoleProgram is its own program. ACM hides the main method because it introduces too many complex concepts to new programmers. Also not supposed to call its constructor. RandomGenerator is a class in ACM. They didn't like the the Random class because the name makes it unclear that its a number generator. (I think they possibly changed the implementation to make it more random.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-16T21:24:59.717", "Id": "33027", "Score": "0", "body": "@Eva Thank you for the clarification. It can be interesting to read old answers to see if I would write them differently today and you comment suggests some improvements." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-19T17:28:58.047", "Id": "857", "ParentId": "855", "Score": "3" } }, { "body": "<p>Your function is called <code>FlipACoin()</code>, but you are doing more than just flipping the coin. A more appropriate name might be <code>FlipACoinAndCountConsecutiveHeadRolls()</code>.</p>\n\n<p>I would suggest keeping the function as simple as the name suggests and return a string (or boolean) from <code>FlipACoin()</code>, then examine the result outside the function. This will also allow you to make the counter a local variable to the run function, which will make the class smaller.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-19T20:26:10.507", "Id": "861", "ParentId": "855", "Score": "4" } }, { "body": "<p>I'd do it like this:</p>\n\n<pre><code>/*\n * File: ConsecutiveHeads.java\n * ----------------\n * This program flips a coin repeatly until three consecutive heads\n * are tossed.\n */\n\nimport acm.program.*;\nimport acm.util.*;\n\npublic class ConsecutiveHeads extends ConsoleProgram {\n /* Run the program */\n public void run() {\n println(\"This program flips a coin until there are three\" +\n \"heads in the row.\");\n while(!TryFlipThreeHeads()) {\n }\n println(\"Yupii! There are already three same heads in the row :)\");\n }\n\n /* Flip a coin. */\n private boolean FlipACoin() {\n boolean rank = rgen.nextBoolean();\n if(rank) {\n println(\"heads\");\n } else {\n println(\"tails\");\n }\n return rank;\n }\n\n private boolean TryGetThreeHeads() {\n for(int counter = 0; counter &lt; 3; counter++)\n {\n // if we get a tail, give up\n if(!FlipACoin()) return false;\n }\n return true;\n }\n\n /* Create an instance variable for the random number generator */\n private RandomGenerator rgen = new RandomGenerator();\n}\n</code></pre>\n\n<p>That way each piece is self-contained. FlipACoin just flips the coin, it doesn't keep track of counting. And TryGetThreeHeads() only worries about trying to flip three heads not the process of flipping each coin.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-23T23:24:46.840", "Id": "3610", "ParentId": "855", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-19T16:57:29.663", "Id": "855", "Score": "4", "Tags": [ "java", "homework" ], "Title": "\"Consecutive Heads\" program" }
855
<p>I've got this javascript function which was written a bit ad-hoc and I'm not really sure how to go about refactoring and improving it.</p> <p>It's basically an implementation of <a href="http://wiki.commonjs.org/wiki/Unit_Testing/1.1">draft Unit-Testing/1.1</a> specification.</p> <pre><code>// Runs the object as a test. The async paramater is an optional function // To be passed in if the test is to be run async. // notRoot is an internal paramater var run = function(object, async, notRoot) { // if its the root call then cache the async func for us in _pushTests if (!notRoot) { func = async; } // tests to run var tests = []; // Assert constructor to be used is either on the object or from assert var Assert = object.Assert || assert.Assert; var failures = 0; // Push the tests to the tests array _pushTests(object, tests); var len = tests.length; // function that runs the test var testRunner; // If async Do I have to document it? It's full of the hacks. if (async) { // results object stores the calls to pass/fail/error var results = {}; results.passes = []; results.fails = []; results.errors = []; // tests passed in the test object var testsPassed = 0; testRunner = function(val, key) { // Local assert object var _assert = new Assert; // Forward the mute property to the assert if (object.mute === true) { _assert.mute = true; } // cache pass, fail &amp; error var _pass = _assert.pass; var _fail = _assert.fail; var _error = _assert.error; // Wrap pass. Push the pass massge to the results object _assert.pass = function(message) { _pass.apply(_assert, arguments); results.passes.push(message); // If an assert passed after done then throw an error in // assert.error if (doneCalled) { _assert.error(new Error( "assertion passed after done was called" + "for test : " + key + " and message was : " + message )); } } // Wrap fail. Push the fail message to the results object _assert.fail = function(message) { _fail.apply(_assert, arguments); results.failures.push(message); // Throw an error if assertion failed after done has been // called if (doneCalled) { _assert.error(new Error( "assertion failed after done was called" + "for test : " + key + " and message was : " + message )); } } // Wrap error. Log calls to error _assert.error = function(error) { _error.apply(_assert, arguments); results.errors.push(error); } // Done has not been called var doneCalled = false; var done = function() { // If its not been called then set it to be called if (!doneCalled) { doneCalled = true; // Increment the number of tests that have passed // If we have passed all then call the async function // with the results if (++testsPassed === len) { async(results, object.name); }; } else { // Done has already been called thrown an error _assert.error(new Error( "done already called for test : " + key )); } }; // Try running the test function. try { val(_assert, done); } catch(e) { // If a failure occurs log it when its an AssertionError if (e instanceof assert.AssertionError) { console.log("failed : " + e.message); } else { // and throw if its another error _assert.error(e); } failures++; } }; } else { // the test runner takes the test function as a paramater testRunner = function(val) { // create a local assert var _assert = new Assert; // If we want to mute it then pass mute to the assert if (object.mute === true) { _assert.mute = true; } // Try the test try { val(_assert); } catch(e) { // If it throws an assertion error then log it if (e instanceof assert.AssertionError) { console.log("failed : " + e.message); } else { // Other error thrown so pass it to assert.error _assert.error(e); } failures++; } }; } // For each test run it. _.each(tests, testRunner); // If the object had a name and was not async then print a message // saying we've finishe if (object.name &amp;&amp; !async) { var string = "Completed " + len + " tests. Finished : " + object.name + " with " + failures + " tests failing"; console.log(string); } // Return the count of failures (Kind of useless for async). return failures; }; </code></pre> <p>For more information the full file can be found <a href="https://github.com/Raynos/BrowserCJS/blob/master/Modules/test/test1.1.js">here</a>. It also relies on <a href="https://github.com/Raynos/BrowserCJS/blob/master/Modules/assert/assert1.1.js"><code>assert</code></a> object which is documented <a href="https://github.com/Raynos/BrowserCJS/blob/master/Modules/assert/assert1.1.js">here</a>.</p> <p>There are some (limited) <a href="https://github.com/Raynos/BrowserCJS/tree/master/Modules/unit-tests">unit tests</a> and they can be run in the browser <a href="http://raynos.github.com/BrowserCJS/tests.html">here</a>.</p> <p>Please tell me if more information is needed. </p> <p>I was going to write some proper high level documentation on how to use it because the commonJS spec is a bit vague. I'll edit when that's done.</p>
[]
[ { "body": "<p>I would start out by cleaning the code along these lines:</p>\n\n<ol>\n<li>Refactor variable names and functions so as to limit the use comments (<em>code doesn't' lie, comments sometimes do</em>)</li>\n<li>Use better descriptive names (fx <strong>key/val</strong> relates to test's in your code but has me thinking of object literals).</li>\n<li>Split the function in smaller functions so they are easier to test and comprehend by them self:</li>\n</ol>\n\n<p>i.e:</p>\n\n<pre><code>testRunner = (async) ? asyncTestRunner : functionTestRunner;\n</code></pre>\n\n<p>followed by the the functions them self </p>\n\n<pre><code>// \nfunction asyncTestRunner(descriptiveParameterNames) {\n :\n}\n// \nfunction functionTestRunner(anotherDescriptiveParameter) {\n :\n}\n</code></pre>\n\n<p>Try to build up your code as a series of progressions, each building logically on the former without needing to many commentary's along the way, in a similar manner as a well written textbook.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-12T19:48:36.727", "Id": "1825", "ParentId": "856", "Score": "6" } } ]
{ "AcceptedAnswerId": "1825", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-19T17:19:48.293", "Id": "856", "Score": "20", "Tags": [ "javascript", "unit-testing" ], "Title": "Unit-testing function" }
856
<p>I feel like I can make my switch statements more elegant with a function pointer, i.e. I'd like to set the <code>digestLength</code> and a pointer to a function in the same switch statement instead of setting the length, declaring the result array, then calling the function.</p> <pre><code>- (NSString *)hashWithDigestType:(NSStringDigestType)type { const char *s = [self UTF8String]; int digestLength; switch (type) { case NSStringDigestTypeMD5: digestLength = CC_MD5_DIGEST_LENGTH; break; case NSStringDigestTypeSHA1: digestLength = CC_SHA1_DIGEST_LENGTH; break; case NSStringDigestTypeSHA512: digestLength = CC_SHA512_DIGEST_LENGTH; break; } unsigned char result[digestLength]; switch (type) { case NSStringDigestTypeMD5: CC_MD5(s, strlen(s), result); break; case NSStringDigestTypeSHA1: CC_SHA1(s, strlen(s), result); break; case NSStringDigestTypeSHA512: CC_SHA512(s, strlen(s), result); break; } NSMutableString *digest = [NSMutableString stringWithCapacity:(digestLength * 2)]; for (NSUInteger i = 0; i &lt; digestLength; i++) [digest appendFormat:@"%02x",result[i]]; return [NSString stringWithString:digest]; } </code></pre>
[]
[ { "body": "<p>I can't write the code in Objective-C, but in C, you could create yourself a structure type to get the information in one move. I don't know whether the NSStringDigestTypeXXX values are conveniently numbered compactly from 0 or 1, so I'm taking the pessimistic view that they are not. You can simplify the code below if they are compact and small.</p>\n\n<pre><code>struct Digestifier // Declaration in a header (probably)\n{\n int hashtype;\n void (*hash)(const char *source, size_t length, char *result);\n size_t hashlen;\n};\nstatic const struct Digestifier digests[] =\n{\n { NSStringDigestTypeSHA1, CC_SHA1, CC_SHA1_DIGEST_LENGTH },\n { NSStringDigestTypeMD5, CC_MD5, CC_MD5_DIGEST_LENGTH },\n { NSStringDigestTypeSHA512, CC_SHA512, CC_SHA512_DIGEST_LENGTH },\n};\n{ enum NUM_DIGESTS = sizeof(digests) / sizeof(digests[0]) };\n</code></pre>\n\n<p>You can then write a lookup function for this:</p>\n\n<pre><code>const struct Digestifier *digest_lookup(int hashtype)\n{\n for (i = 0; i &lt; NUM_DIGESTS; i++)\n {\n if (digests[i].hashtype == hashtype)\n return &amp;digests[i];\n }\n assert(i != NUM_DIGESTS); // Or other error handling!\n return 0;\n}\n</code></pre>\n\n<p>And in your function:</p>\n\n<pre><code>- (NSString *)hashWithDigestType:(NSStringDigestType)type {\n const char *s = [self UTF8String];\n const struct Digestifier *digest = digest_lookup(type);\n\n // Error check digest if digest_lookup() does not do it for you!\n unsigned char result[digest-&gt;hashlen];\n digest-&gt;hash(s, strlen(s), result);\n\n NSMutableString *digest = [NSMutableString stringWithCapacity:(digest-&gt;hashlen * 2)];\n for (NSUInteger i = 0; i &lt; digestLength; i++)\n [digest appendFormat:@\"%02x\",result[i]];\n\n return [NSString stringWithString:digest];\n}\n</code></pre>\n\n<hr>\n\n<p>Note that you could also write the hash function invocation as:</p>\n\n<pre><code> (*digest-&gt;hash)(s, strlen(s), result);\n</code></pre>\n\n<p>To some of us old-school (pre-standard) C programmers, that might perhaps be clearer.</p>\n\n<p>Also, if Objective-C supports the C99 designated initializer notation, you could make the initializer for the <code>digests[]</code> array more robust (and render the <code>hashtype</code> member superfluous except for a cross-check):</p>\n\n<pre><code>static const struct Digestifier digests[] =\n{\n [NSStringDigestTypeSHA1] =\n { NSStringDigestTypeSHA1, CC_SHA1, CC_SHA1_DIGEST_LENGTH },\n [NSStringDigestTypeMD5] =\n { NSStringDigestTypeMD5, CC_MD5, CC_MD5_DIGEST_LENGTH },\n [NSStringDigestTypeSHA512] =\n { NSStringDigestTypeSHA512, CC_SHA512, CC_SHA512_DIGEST_LENGTH },\n};\n</code></pre>\n\n<p>This initializer correctly places the three rows in the array regardless of which member of the enumeration is mapped to 0, 1, 2.</p>\n\n<hr>\n\n<p>With the additional information that the NSStringDigestTypeXXX values are 0, 1, 2, you can simplify the <code>digest_lookup()</code> function by:</p>\n\n<ol>\n<li>Ensuring that the rows in the <code>digests</code> array are in the correct (0, 1, 2) sequence.</li>\n<li>Changing from a search loop to a direct array lookup.</li>\n<li>Probably asserting that the value is under control.</li>\n</ol>\n\n<p>For the purposes of the code below, I'm assuming that NSStringDigestTypeMD5 is 0 and NSStringDigestTypeSHA512 is 2, but the ordering of the names is arbitrary; just choose the equivalent of 0 for the first name in the assert and 2 for the second.</p>\n\n<pre><code>const struct Digestifier *digest_lookup(NSStringDigestType hashtype)\n{\n assert(hashtype &gt;= NSStringDigestTypeMD5 &amp;&amp;\n hashtype &lt;= NSStringDigestTypeSHA512);\n assert(digest[hashtype].hashtype == hashtype);\n return &amp;digests[hashtype];\n}\n</code></pre>\n\n<p>The first assertion ensures that the value is in range. The second assertion ensures that the table is properly sequenced and you are getting back the entry your expect.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T00:38:25.283", "Id": "1589", "Score": "0", "body": "Objective-C is just C with a bunch of additional syntax, so anything that works in C will work for me. `NSStringDigestType` is an enum I declared in the header, so the values are just 0,1,2. Give me a bit to parse your answer, I'm not as comfortable with C as I should be. Thanks!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T01:15:27.420", "Id": "1590", "Score": "0", "body": "@kubi: I am aware that C is a subset of Objective-C, which is one reason I proffered an answer with some confidence that it would be useful to you. However, it was also only fair to point out that I cannot reliably use the distinctive Objective-C notations, so there may be a better, more idiomatic construction for the ideas. Nevertheless, I think the code is generally better as shown." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-19T21:59:12.443", "Id": "862", "ParentId": "858", "Score": "4" } }, { "body": "<p>Here's some 2 cents.</p>\n\n<ol>\n<li>You should never use identifiers beginning with <code>NS</code>, as this prefix is reserved for Apple only. In fact, recently Apple has begun discouraging the use of two- or three-letter prefixes entirely.</li>\n<li><p>[I'm not sure about this approach, but] consider implementing each hash calculation as separate methods; and simply using selectors instead of function pointers:</p>\n\n<pre><code>- (NSString *) hashWithDigestType:(StringDigestType) type\n{\n SEL digestMethods[] = {\n @selector(hashWithMD5),\n @selector(hashWithSHA1),\n @selector(hashWithSHA256)\n };\n\n return [self performSelector:digestMethods[type]];\n}\n</code></pre>\n\n<p>Consider also validating the <code>type</code> variable and the possibility of using designated initialisers, so that you can directly map the enum values to the appropriate selectors.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T13:55:44.750", "Id": "1594", "Score": "0", "body": "Very good point on the prefix, I'll make that change. As far as your selector solution, it's not quite what I'm looking for. I'll end up having to write three separate methods that perform nearly identical tasks." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T19:56:35.807", "Id": "1599", "Score": "0", "body": "@kubi, it was discussed at WWDC 2010." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T16:45:00.150", "Id": "3181", "Score": "0", "body": "Are you sure? The Cocoa coding guidelines only discourage prefixes for method names and structure fields. Beyond that, they stress the importance of prefixes: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingBasics.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-14T22:29:14.310", "Id": "3184", "Score": "0", "body": "@Philip: The documentation always lags behind the discussions at WWDC. The documentation you linked to was last updated *before* WWDC in 2010." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T04:26:03.220", "Id": "864", "ParentId": "858", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-19T18:05:21.783", "Id": "858", "Score": "6", "Tags": [ "c", "objective-c" ], "Title": "Function pointers and switch statements" }
858
<p>I was bored over the last couple of days and wrote up a string interpolation library for JavaScript.</p> <p>I'm very pleased with its functionality, it passes it <a href="https://github.com/BonsaiDen/Fomatto/blob/master/test/test.js" rel="nofollow">79 tests</a> cross browser and the comments and <a href="https://github.com/BonsaiDen/Fomatto#readme" rel="nofollow">README</a> seem fine too.</p> <p>My main concern here are the regular expressions. I'm not a real pro in that area so I suspect there could be some enhancement to them.</p> <p>Another thing is readability of the code as well as how good the comments are. I'd like to have "unclear" sections of the code pointed out so I can improve the naming / comments.</p> <p>The library brings with it the <code>Formatter</code> factory and the <code>FormatError</code>.</p> <p><strong>Basic usage</strong></p> <pre><code>&gt; format = Formatter() &gt; format('Good {} Sir {}.', 'morning', 'Lancelot') 'Good morning Sir Lancelot.' &gt; format('Good {time} Sir {name}.', 'morning', 'Lancelot') 'Good morning Sir Lancelot.' &gt; format('Good {0} Sir {1}.', ['morning', 'Lancelot']) 'Good morning Sir Lancelot.' </code></pre> <p><strong>Source</strong> </p> <pre><code>(function(undefined) { 'use strict'; // Formatter factory function Formatter(formats) { function f() { return format(f.formats, arguments); } f.formats = formats || {}; return f; } // Default formatters Formatter.formats = { repeat: repeat, join: function(value, str) { return value.join(str || ', '); }, upper: function(value) { return value.toUpperCase(); }, lower: function(value) { return value.toLowerCase(); }, lpad: function(value, length, str) { return pad(value, length, str, 'l'); }, rpad: function(value, length, str) { return pad(value, length, str, 'r'); }, pad: function(value, length, str) { return pad(value, length, str); }, surround: function(value, left, right) { return left + value + (right || left); }, hex: function(value, lead) { return (lead ? '0x' : '') + value.toString(16); }, bin: function(value, lead) { return (lead ? '0b' : '') + value.toString(2); } }; function repeat(value, count) { return new Array((count || 0) + 1).join(value || ' '); } function pad(value, length, str, mode) { value = '' + value; str = str || ' '; var len = length - value.length; if (len &lt; 0) { return value; } else if (mode === 'l') { return repeat(str, len) + value; } else if (mode === 'r') { return value + repeat(str, len); } else { return repeat(str, len - ~~(len / 2)) + value + repeat(str, ~~(len / 2)); } } // match {} placholders like {0}, {name}, {} and the inner "{{foo}}" // {} can be escaped with \ var replaceExp = /([^\\]|^)\{([^\{\}]*[^\\^\}]|)\}/g, // match things like: foo[0].test["test"]['test] accessExp = /^\.?([^\.\[]+)|\[((-?\d+)|('|")(.*?[^\\])\4)\]/, // match :foo and :foo(.*?) formatExp = /\:([a-zA-Z]+)(\((.*?)\))?(\:|$)/, // match arguments: "test", 12, -12, 'test', true, false // strings can contain escaped characters like \" argumentsExp = /^(,|^)\s*?((true|false|(-?\d+))|('|")(.*?([^\\]|\5))\5)/; // Main formatting function function format(formatters, args) { // Setup magic! var string = args[0], first = args[1], argsLength = args.length - 2, type = first != null ? {}.toString.call(first).slice(8, -1) : '', arrayLength = first ? first.length - 1 : 0, autoIndex = 0; function replace(value, pre, form) { // Extract formatters var formats = [], format = null, id = form; while (format = form.match(formatExp)) { if (formats.length === 0) { id = form.substring(0, format.index); } form = form.substring(format[0].length - 1); formats.push(format); } // In case of a valid number use it for indexing var num = (isNaN(+id) || id === '') ? null : +id; // Handle objects if (type === 'Object' &amp;&amp; id !== '') { // Handle plain keys if (id.indexOf('.') === -1 &amp;&amp; id.indexOf('[') === -1) { if (first[id] !== undefined) { value = first[id]; // fall back to obj.toString() } else { value = args[1 + autoIndex]; } // Access properties } else { value = getProperty(first, id); } // Handle given array indexes } else if (type === 'Array' &amp;&amp; num !== null) { value = first[num &gt;= 0 ? num : arrayLength + num]; // Handle given arguments indexes } else if (num !== null) { value = args[1 + (num &gt;= 0 ? num : argsLength + num)]; // Handle automatic arguments indexes } else { value = args[1 + autoIndex]; } autoIndex++; // Apply formats while (format = formats.shift()) { var method = (formatters[format[1]] ? formatters : Formatter.formats)[format[1]]; if (method) { value = method.apply(undefined, getArguments(value, format[3] || '')); } else { throw new FormatError( replace, 'Undefined formatter "{}".', format[1] ); } } return pre + value; } return string.replace(replaceExp, replace); } // Get a specific peoperty of an object based on a accessor string function getProperty(obj, id) { var m, pos = 0; while (m = id.substring(pos).match(accessExp)) { // .name / [0] / ["test"] var prop = m[1] || (m[3] ? +m[3] : m[5].replace('\\' + m[4], m[4])); if (obj === undefined) { throw new FormatError( getProperty, 'Cannot access property "{}" of undefined.', prop ); } else { obj = obj[prop]; } pos += m[0].length; } return obj; } // Convert a string like: // true, false, -1, 34, 'foo', "bla\" foo" // // Into a list of arguments: // [true, false, -1, 34, 'foo', 'bla" foo'] function getArguments(value, string) { var m, pos = 0, args = [value]; while (m = string.substring(pos).match(argumentsExp)) { // number args.push(m[4] ? +m[4] // boolean : (m[3] ? m[3] === 'true' // string : m[6].replace('\\' + m[5], m[5]))); pos += m[0].length; } return args; } // Formatting error type function FormatError(func, msg, value) { this.name = 'FormatError'; this.message = format(Formatter.formats, [msg, value]); if (Error.captureStackTrace) { Error.captureStackTrace(this, func); } } FormatError.prototype = new Error(); // Exports var exp = typeof window === 'undefined' ? exports : window; exp.Formatter = Formatter; exp.FormatError = FormatError; })(); </code></pre>
[]
[ { "body": "<p>I have not looked at your regexes in detail. Could you please explain them? The rest of the code could use better documentation as well.</p>\n\n<p>I did find two serious code correctness issues:</p>\n\n<ol>\n<li><p>Your <code>:join()</code> formatter will not work with the empty string as the delimiter.</p>\n\n<pre><code>return value.join(str || ', '); // Boolean('') === false\n</code></pre></li>\n<li><p>Your <code>:pad()</code> formatter, when used for center padding, will not correctly add an odd number of padding characters, as the padding on either side is rounded down.</p>\n\n<pre><code>} else {\n return repeat(str, len - ~~(len / 2))\n + value\n + repeat(str, ~~(len / 2));\n}\n</code></pre>\n\n<p>In general, using tricks such as <code>~~</code> tends to reduce the code's clarity, and this is an excellent example of that. You should use the <code>Math.floor()</code> and <code>Math.ceil()</code> functions instead if that is what you intend.</p></li>\n</ol>\n\n<p>Fix these issues, and of course add corresponding tests. Also document the fact that <code>:pad()</code> and the other padding functions are only intended to work with a single padding character.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T12:48:23.543", "Id": "1696", "Score": "0", "body": "Good catches. `:pad()` actually works with odd numbers, maybe I fixed that after I last updated the post. The `:join()` problem uncovered some bugs with the parsing of empty strings in arguments, that's also fixed and tested for now. I also replaced the ~~ floor shortcut. I'll add the note and try to document the regular expressions, JS unfortunately doesn't allow them to be split over multiple lines :(" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T09:01:58.690", "Id": "1782", "Score": "0", "body": "@IvoWetzel You can have large comment blocks explaining how they work though: https://github.com/derobins/wmd/blob/master/showdown.js#L161" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T11:29:45.043", "Id": "1785", "Score": "0", "body": "Added the fixed / changed code to the question. There are also 7 new tests accompanying the changes. @YiJiang I gave the regex commenting a try, could you tell me whether the format is useful?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T23:16:45.673", "Id": "936", "ParentId": "860", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-19T19:06:14.757", "Id": "860", "Score": "11", "Tags": [ "javascript", "strings", "formatting", "library" ], "Title": "String interpolation library" }
860
<p>Writing a new site, has anyone got any comments on the HTML here? Is it all semantically correct? Thanks! This will basically be the template, so I want to make sure it's pretty perfect.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Welcome to Scirra.com&lt;/title&gt; &lt;meta name="description" content="Construct 2 is a free open source HTML5 games creator." /&gt; &lt;meta charset="UTF-8" /&gt; &lt;link rel="stylesheet" href="css/default.css" type="text/css" /&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/common.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="plugins/coin-slider/coin-slider.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="plugins/coin-slider/coin-slider-styles.css" type="text/css" /&gt; &lt;link href="plugins/jquery.twit.0.2.0/twit.css" type="text/css" rel="stylesheet" /&gt; &lt;script type="text/javascript" src="plugins/jquery.twit.0.2.0/twit.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $('#coin-slider').coinslider({ width: 470, height: 261, spw: 8, sph: 4, delay: 7000, effect: 'straight', hoverPause: true }); $('#twitterFeed').twit('Scirra', { limit: 5, label: '', icon: false, count: 20 }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="topBar"&gt;&lt;/div&gt; &lt;div class="mainBox"&gt; &lt;div class="headWrapper"&gt; &lt;div class="searchBox"&gt; &lt;div class="searchContent"&gt; &lt;input type="text" id="SearchBox" /&gt; &lt;div class="s searchIco"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="topMenu"&gt; &lt;a href="#" class="topNormal"&gt;Main Link&lt;/a&gt; &lt;a href="#" class="topNormal"&gt;Mainy Link&lt;/a&gt; &lt;a href="#" class="topSelWrapper"&gt;Main Link&lt;/a&gt; &lt;a href="#" class="topNormal"&gt;Main Link&lt;/a&gt; &lt;/div&gt; &lt;div class="subMenu"&gt; &lt;a href="#" class="subSelWrapper"&gt;Another Sub Link&lt;/a&gt; &lt;a href="#" class="subNormal"&gt;Sub Link&lt;/a&gt; &lt;a href="#" class="subNormal"&gt;Sub Link&lt;/a&gt; &lt;a href="#" class="subNormal"&gt;Sub Link&lt;/a&gt; &lt;a href="#" class="subNormal"&gt;Sub Link&lt;/a&gt; &lt;/div&gt; &lt;div class="contentWrapper"&gt; &lt;div class="wideCol"&gt; &lt;div class="s slideShowWrapper"&gt; &lt;div id='coin-slider'&gt; &lt;a href="#" target="_blank"&gt; &lt;img src='images/screenshot1.jpg' &gt; &lt;span&gt; Scirra software allows you to bring your imagination to life &lt;/span&gt; &lt;/a&gt; &lt;a href="#"&gt; &lt;img src='images/screenshot2.jpg' &gt; &lt;span&gt; Export your creations to HTML5 pages &lt;/span&gt; &lt;/a&gt; &lt;a href="#"&gt; &lt;img src='images/screenshot3.jpg' &gt; &lt;span&gt; Another description of some image &lt;/span&gt; &lt;/a&gt; &lt;a href="#"&gt; &lt;img src='images/screenshot4.jpg' &gt; &lt;span&gt; Something motivational to tell people &lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="newsWrapper"&gt; &lt;h1&gt;Latest from Twitter&lt;/h1&gt; &lt;div id="twitterFeed"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="thinCol"&gt; &lt;h1&gt;Main Heading&lt;/h1&gt; &lt;p&gt;Some paragraph goes here. It tells you about the picture. Cool! Have you thought about downloading Construct 2? Well you can download it with the link below. This column will expand vertically.&lt;/p&gt; &lt;a class="blueLinkBox" href="#"&gt;Learn More&lt;/a&gt;&lt;div class="clear"&gt;&lt;/div&gt; &lt;h2&gt;Help Me!&lt;/h2&gt; &lt;p&gt;This column will keep expanging and expanging. It pads stuff out to make other things look good imo.&lt;/p&gt; &lt;a class="blueLinkBox" href="#"&gt;Learn More&lt;/a&gt;&lt;div class="clear"&gt;&lt;/div&gt; &lt;h2&gt;Why Download?&lt;/h2&gt; &lt;p&gt;As well as other features, we also have some other features. Check out our &lt;a href="#"&gt;other features&lt;/a&gt;. Each of our other features is really cool and there to help everyone suceed.&lt;/p&gt; &lt;a href="#" class="s downloadBox"&gt; &lt;div class="downloadHead"&gt;Download&lt;/div&gt; &lt;div class="downloadSize"&gt;24.5 MB&lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;h1&gt;This Weeks Spotlight&lt;/h1&gt; &lt;div class="halfColWrapper"&gt; &lt;img src="images/spotlight1.png" class="spotLightImg" /&gt; &lt;p&gt;Our spotlight member this week is Pooh-Bah. He writes good stuff. Read it.&lt;/p&gt; &lt;a class="blueLinkBox" href="#"&gt;Learn More&lt;/a&gt; &lt;/div&gt; &lt;div class="halfColSpacer"&gt;&amp;nbsp;&lt;/div&gt; &lt;div class="halfColWrapper"&gt; &lt;img src="images/spotlight2.png" class="spotLightImg" /&gt; &lt;p&gt;Killer Bears is a scary ass game from JimmyJones. How many bears can you escape from?&lt;/p&gt; &lt;a class="blueLinkBox" href="#"&gt;Learn More&lt;/a&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="footer"&gt; &lt;div class="footerContent"&gt; &lt;div class="footerItem"&gt; &lt;h3&gt;Community&lt;/h3&gt; &lt;a href="#"&gt;The Blog&lt;/a&gt;&lt;br /&gt; &lt;a href="#"&gt;Community Forum&lt;/a&gt;&lt;br /&gt; &lt;a href="#"&gt;RSS Feed&lt;/a&gt;&lt;br /&gt; &lt;a class="s footIco facebook" href="http://www.facebook.com/ScirraOfficial" target="_blank"&gt;&lt;/a&gt; &lt;a class="s footIco twitter" href="http://twitter.com/Scirra" target="_blank"&gt;&lt;/a&gt; &lt;a class="s footIco youtube" href="http://www.youtube.com/user/ScirraVideos" target="_blank"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="footerItem"&gt; &lt;h3&gt;About Us&lt;/h3&gt; &lt;a href="#"&gt;Contact Information&lt;/a&gt;&lt;br /&gt; &lt;a href="#"&gt;Advertising&lt;/a&gt;&lt;br /&gt; &lt;a href="#"&gt;History&lt;/a&gt;&lt;br /&gt; &lt;a href="#"&gt;Privacy Policy&lt;/a&gt;&lt;br /&gt; &lt;a href="#"&gt;Terms and Conditions&lt;/a&gt; &lt;/div&gt; &lt;div class="footerItem"&gt; &lt;h3&gt;Want to Help?&lt;/h3&gt; You can contribute to Scirra software as it is &lt;a href="#"&gt;Open Source&lt;/a&gt;. We welcome all contributions, and there are lots of ways to join in!&lt;br /&gt; &lt;div class="ralign"&gt; &lt;a href="#"&gt;&lt;strong&gt;Learn More&lt;/strong&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="copyright"&gt; Copyright &amp;copy; 2011 Scirra.com. All rights reserved. &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Looks great in all browsers, but want to check it's valid markup and as perfect as it could be.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T22:51:25.903", "Id": "1613", "Score": "0", "body": "Why such a short DOCTYPE?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T23:03:22.870", "Id": "1615", "Score": "6", "body": "@Peter I was under the impression that's the HTML5 doctype" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T09:05:22.973", "Id": "1629", "Score": "0", "body": "@Peter no worries! I was also pleasantly surprised to see that is the new doctype." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T17:20:34.633", "Id": "1676", "Score": "4", "body": "always declare the charset first (before the title and meta description)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:11:45.877", "Id": "64514", "Score": "0", "body": "The validator says [it looks good](http://validator.w3.org/check)." } ]
[ { "body": "<p>Looks like a lot of extra <code>&lt;div&gt;</code>s, as far as I can see. Why do you have <code>.footer</code> and <code>.footerContent</code>? Generally a <code>&lt;div&gt;</code> without any siblings can be killed.</p>\n\n<p>And that header looks really out of control. Any reason for wrapping the input and search icon in 4 lonely <code>&lt;div&gt;</code>s?</p>\n\n<p>You should also avoid this: <code>class=\"blueLinkBox\"</code>. Because what happens when you change your design to be orange? Would you then rename all your link boxes, or just try to remember that <code>blueLinkBox</code> are those orange boxes? Name your classes by their content. <code>.importantLink</code> or <code>.readMoreLink</code> might be better names.</p>\n\n<p>You also have some links without any content or <code>title</code> attribute, which is bad for screen readers, seo and other stuff that can't \"see\" your website.</p>\n\n<p>It's not a good idea to have multiple <code>&lt;h1&gt;</code>s on one page. There are of course exceptions (eg: scrolling-for-navigation), but this page doesn't seem to fit... Because what you're saying now is that \"this weeks spotlight\" is as important as the main features of your product, which I'm guessing (hoping) is not the case.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:45:05.340", "Id": "876", "ParentId": "866", "Score": "6" } }, { "body": "<p><strong>Some things that come to mind:</strong></p>\n\n<ul>\n<li>Load .css resources before .js resource for faster loading</li>\n<li>Don't use inline javascript</li>\n<li>Use an <code>&lt;ul&gt;</code> with <code>&lt;li&gt;</code> items for a menu, this is semantically more correct</li>\n<li>Always use an alt tag on <code>&lt;img&gt;</code></li>\n<li>Don't use <code>&lt;br&gt;</code> tags, use <code>&lt;p&gt;</code> if we're talking about text. Use css (display:block) if you want to force an element to the next line.</li>\n<li>Use IDs when there is only one occurence per page, e.g. <code>&lt;div id=\"footer\"&gt;</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:45:40.597", "Id": "877", "ParentId": "866", "Score": "10" } }, { "body": "<p>If you are going with HTML5, I would suggest a few more things:</p>\n\n<ol>\n<li>Lose the type=\"text/javascript\" from the script tags - you don't need them in HTML5</li>\n<li>Same goes with type=\"text/css\" on link tags</li>\n<li>Keep your self-closing XML syntax consistent - on some tags you have the closing />, on some you don't (it doesn't matter which way, just make it consistent)</li>\n<li>Consider placing .js files at the bottom of the document - that way the page can start rendering before it's downloaded them all. Often these are required for post-rendering functions anyway - so do your users a favor and put them at the bottom of the document.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T13:24:45.020", "Id": "1814", "Score": "2", "body": "On the HTML5 kick, I'd consider using the new semantic tags such as `header` and `footer` instead of a `div` with a class. `nav` looks appropriate in this case too." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-14T23:45:55.927", "Id": "2250", "Score": "0", "body": "Agreed - for a great intro to HTML5, I recommend http://www.diveintohtml5.org/." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-27T10:33:23.367", "Id": "14910", "Score": "0", "body": "Improvement: the [defer and async](http://developers.whatwg.org/scripting-1.html#the-script-element) attributes can be used on the script tag so it stops delaying page load." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T23:14:24.773", "Id": "884", "ParentId": "866", "Score": "17" } }, { "body": "<p>The validator says there are a lot of meta tag values missing (about 10) and that there a 2 starting <code>&lt;body&gt;</code> tags.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T22:22:35.497", "Id": "1842", "Score": "0", "body": "I don't see those warnings." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-26T09:05:08.673", "Id": "1007", "ParentId": "866", "Score": "0" } } ]
{ "AcceptedAnswerId": "884", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-20T20:59:18.157", "Id": "866", "Score": "12", "Tags": [ "html", "html5", "template" ], "Title": "HTML Review of template for site - Is this ok for HTML5?" }
866
<p>We're calculating entropy of a string a few places in Stack Overflow as a signifier of low quality.</p> <p>I whipped up this simple method which counts unique characters in a string, but it is quite literally the first thing that popped into my head. It's the "dumbest thing that works".</p> <pre><code>/// &lt;summary&gt; /// returns the # of unique characters in a string as a rough /// measurement of entropy /// &lt;/summary&gt; public static int Entropy(this string s) { var d = new Dictionary&lt;char, bool&gt;(); foreach (char c in s) if (!d.ContainsKey(c)) d.Add(c, true); return d.Count(); } </code></pre> <p>Is there a better / more elegant / more accurate way to calculate the entropy of a string?</p> <p>Efficiency is also good, though we never call this on large strings so it is not a huge concern.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:25:37.800", "Id": "1603", "Score": "0", "body": "Why a `Dictionary` as opposed to a `List`?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:26:05.693", "Id": "1604", "Score": "0", "body": "Or, SortedList<>?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T16:22:48.663", "Id": "1638", "Score": "3", "body": "http://en.wikipedia.org/wiki/Entropy_(information_theory)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T19:05:01.423", "Id": "1645", "Score": "4", "body": "Your question reminded me of a Dr Dobbs article I read about 20 years ago. Fortunately, it's available online. It include simple .c code http://www.drdobbs.com/security/184408492" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T04:14:09.660", "Id": "1692", "Score": "57", "body": "Jeff, please tell me you are not trying to use this code to make it even harder to post short comments like “Yes.” by preventing users from adding dots or dashes..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-17T13:11:46.473", "Id": "9458", "Score": "1", "body": "Why are you not using lambda ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-06T18:16:04.743", "Id": "11832", "Score": "2", "body": "I don't know what you want to do with it, but one way to estimate entropy in data is to compress it, and take the length of the result. Length of the data is the upper bound of the entropy. The better the compressor program - the better estimate." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-14T14:06:53.857", "Id": "44694", "Score": "16", "body": "Technically, a known string has no entropy; a process of producing strings has an entropy. What you are doing is hypothesizing a space of processes, estimating which process produced this string, and giving the entropy of that process." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-20T17:26:01.363", "Id": "95835", "Score": "0", "body": "How about just compressing it with gzip, or what is easily available? That's precise and elegant, and likely very optimised." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-15T06:26:45.593", "Id": "133877", "Score": "0", "body": "@NRS , resharper will do that at the end :) :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:40:58.653", "Id": "160493", "Score": "0", "body": "Pull the entropy finding source from any compression algotithm, i.e. Huffman" } ]
[ { "body": "<pre><code>public static int Entropy(this string s)\n{\n HashSet&lt;char&gt; chars = new HashSet&lt;char&gt;(s);\n return chars.Count;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T17:56:22.177", "Id": "1642", "Score": "44", "body": "I am always amazed at how simple algorithms can get, or, as in this case, *completely vanish*, by just using the right data structures. My favorite example is computing a histogram of discrete values, which is literally just `new MultiSet(sourceData)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-19T12:30:13.267", "Id": "426058", "Score": "0", "body": "What about different characters that represent the same glyph, or glyphs that cannot be represented with a single character?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-20T17:37:56.607", "Id": "426214", "Score": "0", "body": "@dfhwze That `s` parameter is a stream of tokens. In the implementation provided in this answer each character is already a token, so no need to preprocess it; in your case you need to \"tokenize\" your input before. (And the parameter won't be a `string`, more like `IEnumerable<Token>` or similar)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:26:01.330", "Id": "869", "ParentId": "868", "Score": "102" } }, { "body": "<p>Won't this work too?</p>\n\n<pre><code>string name = \"lltt\";\nint uniqueCharacterCount = name.Distinct().Count();\n</code></pre>\n\n<p>will return 2</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:43:59.320", "Id": "1606", "Score": "39", "body": "Given Distinct probably uses a HashSet, I think this is the most concise and clear implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-13T14:37:30.190", "Id": "140131", "Score": "34", "body": "This is missing the point. The goal is to calculate the entropy of the string, not find a fancy way to count characters. Counting characters was one attempt (in the OP): counting characters more elegantly is not significantly better at calculating entropy." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:26:39.127", "Id": "870", "ParentId": "868", "Score": "227" } }, { "body": "<p>You can probably expand this to something like bi-grams and tri-grams to get things like \"sdsdsdsdsdsdsdsdsdsd\" (although yours would catch this as well). Would a bayesian approach like spam filters do be appropriate for something like what you're trying to achieve?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T22:04:01.217", "Id": "1609", "Score": "0", "body": "the first derivative will catch this easily as well" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:26:48.453", "Id": "871", "ParentId": "868", "Score": "13" } }, { "body": "<ol>\n<li>I don't understand the point of the bool. You never appear to set it to false, so we can use a <code>List&lt;T&gt;</code> instead.</li>\n<li>Given that you want just unique items, we can just use <code>HashSet&lt;T&gt;</code> instead.</li>\n</ol>\n\n<p>Haven't tested, but this method should be equivalent and faster:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// returns the # of unique characters in a string as a rough \n/// measurement of entropy\n/// &lt;/summary&gt;\npublic static int Entropy(this string s)\n{\n var hs = new HashSet&lt;char&gt;();\n foreach (char c in s)\n hs.Add(c);\n return hs.Count();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:45:32.170", "Id": "1607", "Score": "0", "body": "While I agree that using a `HashSet` is clearer than using a `Dictionary` and just ignoring its values, I don't see any reason why it would be faster." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:27:57.423", "Id": "872", "ParentId": "868", "Score": "18" } }, { "body": "<p>I'm going to assume this is English (seeing as that's all we do). Wouldn't it be better to keep a <code>HashSet&lt;string&gt;</code> of stop words (the most common words in English that don't convey meaning), tokenize the string into words, and count the number of words that aren't stop words?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:39:17.327", "Id": "874", "ParentId": "868", "Score": "12" } }, { "body": "<p>in theory you can measure entropy only from the point of view of a given model. For instance the PI digits are well distributed, but actually is the entropy high? Not at all since the infinite sequence can be compressed into a small program calculating all the digits.</p>\n\n<p>I'll not dig further in the math side, since I'm not an expert in the field. But I want to suggest to you a few things that can make a very simple but practical model.</p>\n\n<p><strong>Short strings</strong></p>\n\n<p>To start, distribution. Comparing characters that are the same is exactly this in some way, but the generalization is to build a frequency table and check the distribution.</p>\n\n<p>Given a string of length N, how many A chars should I expect in average, given my model (that can be the english distribution, or natural distribution)?</p>\n\n<p>But then what about \"abcdefg\"? No repetition here, but this is not random at all.\nSo what you want here is to take also the first derivative, and check the distribution of the first derivative.</p>\n\n<p>it is as trivial as subtracting the second char from the first, the thrid from the second, so in our example string this turns into: \"abcdefg\" => 1,1,1,1,1,1</p>\n\n<p>Now what aobut \"ababab\"... ? this will appear to have a better distribution, since the derivative is 1,-1,1,-1,... so what you actually want here is to take the absolute value.</p>\n\n<p><strong>Long strings</strong></p>\n\n<p>If the string is long enough the no brainer approach is: try to compress it, and calculate the ratio between the compression output and the input.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T22:17:32.690", "Id": "1610", "Score": "4", "body": "its tricky ... `asdfghjkl;` is a pretty crappy string as well" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T22:19:59.123", "Id": "1611", "Score": "3", "body": "@Sam: your string will be actually flagged as low entropy by the first derivative test. Of course here you are changing the model, that is, accordingly to the position of chars in a keyboard, that is also a good model. You can add it to the mix as well of course." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T22:24:37.630", "Id": "1612", "Score": "0", "body": "very interesting approach. keep in mind our entropy tests are mainly there for really short strings. Here is the classic example of where we use it ( http://stackoverflow.com/review/low-quality-posts?pagesize=15&filter=day ) in conjunction with a few other algorithms" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T11:59:47.367", "Id": "1633", "Score": "1", "body": "You cannot tell from looking at a string whether it is randomly produced (abc). If you pick 3 characters from an equal distribution, abc, aaa, zzz, zur and apk are of equal chance. Of course, in your example, you choosed the abcdef intentionally and not randomly, but this doesn't prove a random generator couldn't have formed it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-20T21:59:15.373", "Id": "878", "ParentId": "868", "Score": "78" } }, { "body": "<p>Why not divide the number of unique characters in the given string by the total number of characters in that string. That would give a more accurate measure of entropy.</p>\n\n<p>For example, going by your formula, an entropy of 3 for a string of 5 characters should be fine but an entropy of 3 for a string of 8 characters is poor. But, your formula wouldn't be able to differentiate between the two results. Whereas, the above given formula would do so to give a more accurate measure.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:59:16.470", "Id": "879", "ParentId": "868", "Score": "15" } }, { "body": "<p>I think antirez is right in suggesting that an entropy approach needs a model. So assuming we're talking English, then examining the string's character distribution and how closely it aligns with \"average\" will likely show that the text is mostly English. But is this what you want to achieve? Presumable many things are code or pseudo-code. Compression is a great idea, but this'll give the highest entropy for random text - is high entropy bad? Low entropy would indicate lots of repetition, maybe verbosity, but one can write long drawn out sentences with frilly words and transmit little information (e.g. this comment).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T22:20:03.140", "Id": "880", "ParentId": "868", "Score": "14" } }, { "body": "<p>I would try to count each character and verify that it roughly matches the normal frequency of English letters. It could be more precise (on sufficiently large inputs) than counting the number of letters.</p>\n\n<p>If you sort letters by their number of appearences, you should, statistically speaking, get something like <code>ETAONRISHDLFCMUGYPWBVKXJQZ</code>. You could use the edit distance between this string and the letters sorted by order of appearance to give a rough measurement of entropy.</p>\n\n<p>Also, you could possibly catch non-English posts that way. (If you do go this way, I recommend you exclude code fragments from the count...)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T23:29:03.637", "Id": "1617", "Score": "1", "body": "As a second cut of the original count of unique characters, I was going to suggest calculating the variance of the count of each unique character. This way you won't bias it towards English and against code, but only require that some characters appear less often than others." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T22:56:23.587", "Id": "883", "ParentId": "868", "Score": "9" } }, { "body": "<p>How about actually computing entropy? Also, it's not clear that character-level entropy will help, but here goes. It's in my mother tongue C++, but surely you can convert this to Java using Array instead of std::vector. </p>\n\n<pre><code>float CharacterEntropy(const char *str) {\n std::vector&lt;unsigned&gt; counts(256);\n for (const char *i = str; *i; ++i)\n ++counts[static_cast&lt;unsigned char&gt;(*i)];\n unsigned int total = 0;\n for (unsigned i = 0; i &lt; 256; ++i)\n total += counts[i];\n float total_float = static_cast&lt;float&gt;(total);\n float ret = 0.0;\n for (unsigned i = 0; i &lt; 256; ++i) {\n float p = static_cast&lt;float&gt;(counts[i]) / total_float;\n ret -= p * logf(p);\n }\n return p * M_LN2;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T00:25:26.820", "Id": "1618", "Score": "0", "body": "be careful that 0 * log(0) -> 0" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T13:18:03.087", "Id": "1634", "Score": "2", "body": "It's not Java - I guess it's C#. In Java it is 'String' not 'string'. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T00:16:04.513", "Id": "886", "ParentId": "868", "Score": "27" } }, { "body": "<p>I also came up with this, based on <a href=\"http://en.wikipedia.org/wiki/Entropy_%28information_theory%29\">Shannon entropy</a>.</p>\n\n<blockquote>\n <p>In information theory, entropy is a measure of the uncertainty associated with a random variable. In this context, the term usually refers to the <strong>Shannon entropy, which quantifies the expected value of the information contained in a message, usually in units such as bits.</strong> </p>\n</blockquote>\n\n<p>It is a more \"formal\" calculation of entropy than simply counting letters:</p>\n\n<pre><code>/// &lt;summary&gt;\n/// returns bits of entropy represented in a given string, per \n/// http://en.wikipedia.org/wiki/Entropy_(information_theory) \n/// &lt;/summary&gt;\npublic static double ShannonEntropy(string s)\n{\n var map = new Dictionary&lt;char, int&gt;();\n foreach (char c in s)\n {\n if (!map.ContainsKey(c))\n map.Add(c, 1);\n else\n map[c] += 1;\n }\n\n double result = 0.0;\n int len = s.Length;\n foreach (var item in map)\n {\n var frequency = (double)item.Value / len;\n result -= frequency * (Math.Log(frequency) / Math.Log(2));\n }\n\n return result;\n}\n</code></pre>\n\n<p>Results are:</p>\n\n<pre>\n\"abcdefghijklmnop\" = 4.00\n\"Hello, World!\" = 3.18\n\"hello world\" = 2.85\n\"123123123123\" = 1.58\n\"aaaa\" = 0\n</pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T16:42:58.707", "Id": "1675", "Score": "7", "body": "There are some subtleties here. What you're calculating there isn't the entropy of the string but the entropy of a character in the string. You should consider whether to include a pseudo-character with frequency 1 for the string terminator (a unary number has some content), and whether to multiply by the length of the string." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T02:03:57.070", "Id": "1722", "Score": "1", "body": "Sorry, just noticed this, this is equivalent to the code I later posted. Jeff, this is definitely a better solution; I think the most upvoted answer to this question is missing the point." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T14:14:42.720", "Id": "1830", "Score": "2", "body": "Here we see another case where a frequency data structure would be useful. `var map = new FrequencyTable<char>(); foreach (char c in s) { map.Add(c); }`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T14:15:39.257", "Id": "1831", "Score": "1", "body": "If you're not using the keys, would it not be more clear to do `foreach (var value in map.Values)`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-21T19:15:57.200", "Id": "9588", "Score": "2", "body": "Not that it'd be a huge thing, but I'd lift the `Math.Log(2)` calculation out of the loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-05T07:50:04.723", "Id": "15390", "Score": "0", "body": "By the way, this could also be used to for fraudulent vote detection. Past a certain amount of votes, if there are only votes for \"user x\", the entropy of the different votes is zero: there is no additional information, and the votes should be discarded, whether they're upvotes or downvotes. Could be difficult to find a meaningful threshold." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-13T14:42:44.530", "Id": "140133", "Score": "1", "body": "Instead of the above, just compress the string using a few algorithms. The above seems to correspond to Huffman coding. LZ would allow character tuples to be factored into the entropy (so `ababab` has less entropy than `aabbab`). The neat thing is you could build more than one compression model (keyboard position based for asdf, for example). Picking which models needs be given \"cost\" in theory (as enough models make anything low entropy)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-01T18:48:33.523", "Id": "237846", "Score": "0", "body": "Are you sure about using natural logarithms for binary systems? I need to calculate this. But as I am no mathematician, this is hard topic to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-01T03:42:03.390", "Id": "437458", "Score": "1", "body": "@LinuxSecurityFreak I'm a bit late, but Log2(x) == LogY(x)/LogY(2)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T21:34:58.517", "Id": "909", "ParentId": "868", "Score": "92" } }, { "body": "<p>Similar to <a href=\"https://codereview.stackexchange.com/questions/868/calculating-entropy-of-a-string/886#886\">zngu's answer</a>, I think better than just counting the number of characters would be calculating the <a href=\"http://en.wikipedia.org/wiki/Entropy_%28information_theory%29#Definition\" rel=\"noreferrer\">character-entropy of the message</a>:</p>\n\n<pre><code>public double CalculateEntropy(string entropyString)\n{\n Dictionary&lt;char, int&gt; characterCounts = new Dictionary&lt;char, int&gt;();\n foreach(char c in entropyString.ToLower())\n {\n if(c == ' ') continue;\n int currentCount;\n characterCounts.TryGetValue(c, out currentCount);\n characterCounts[c] = currentCount + 1;\n }\n\n IEnumerable&lt;double&gt; characterEntropies = \n from c in characterCounts.Keys\n let frequency = (double)characterCounts[c]/entropyString.Length\n select -1*frequency*Math.Log(frequency);\n\n return characterEntropies.Sum();\n}\n</code></pre>\n\n<p>It seems to work well with both code and text, but note that it is not calculating the actual entropy of the string, only the entropy of the character-distribution; sorting the characters within the string should reduce the entropy of the string, but it does not reduce the result of this function.</p>\n\n<p>Here are some tests:</p>\n\n<pre><code>private void CalculateEntropyTest(object sender, EventArgs e)\n{\n string[] testStrings = {\n \"Hello world!\",\n \"This is a typical english sentence containing all the letters of the english language - The quick brown fox jumped over the lazy dogs\",\n String.Join(\"\", \"This is a typical english sentence containing all the letters of the english language - The quick brown fox jumped over the lazy dogs\".ToCharArray().OrderBy(o =&gt; o).Select(o =&gt; o.ToString()).ToArray()),\n \"Won't this work too?\\nstring name = \\\"lltt\\\";\\nint uniqueCharacterCount = name.Distinct().Count();\\nwill return 2\",\n \"Pull the entropy finding source from any compression algotithm, i.e. Huffman\",\n \"float CharacterEntropy(const char *str) {\\n std::vector&lt;unsigned&gt; counts(256);\\n for (const char *i = str; *i; ++i)\\n ++counts[static_cast&lt;unsigned char&gt;(*i)];\\n unsigned int total = 0;\\n for (unsigned i = 0; i &lt; 256; ++i)\\n total += counts[i];\\n float total_float = static_cast&lt;float&gt;(total);\\n float ret = 0.0;\\n for (unsigned i = 0; i &lt; 256; ++i) {\\n float p = static_cast&lt;float&gt;(counts[i]) / total_float;\\n ret -= p * logf(p);\\n }\\n return p * M_LN2;\\n}\",\n \"~~~~~~No.~~~~~~\",\n \"asdasdasdasdasdasd\",\n \"abcdefghijklmnopqrstuvwxyz\",\n \"Fuuuuuuu-------\", \n };\n foreach(string str in testStrings)\n {\n Console.WriteLine(\"{0}\\nEntropy: {1:0.000}\\n\", str, CalculateEntropy(str));\n }\n}\n</code></pre>\n\n<p></p>\n\n<blockquote>\n <p>Results:<br>\n Hello world!<br>\n Entropy: 1.888</p>\n \n <p>This is a typical english sentence containing all the letters of the english language - The quick brown fox jumped over the lazy dogs<br>\n Entropy: 2.593</p>\n \n <p>-TTaaaaaaabccccddeeeeeeeeeeeeeeffgggggghhhhhhhiiiiiiiijk\n lllllllmnnnnnnnnnooooooppqrrrsssssssttttttttuuuvwxyyz<br>\n Entropy: 2.593</p>\n \n <p>Won't this work too?\n string name = \"lltt\";\n int uniqueCharacterCount = name.Distinct().Count();\n will return 2<br>\n Entropy: 2.838</p>\n \n <p>Pull the entropy finding source from any compression algotithm, i.e. Huffman<br>\n Entropy: 2.641</p>\n \n <p>float CharacterEntropy(const char *str) {\n std::vector counts(256);\n for (const char *i = str; *i; ++i)\n ++counts[static_cast(*i)];\n unsigned int total = 0;\n for (unsigned i = 0; i &lt; 256; ++i)\n total += counts[i];\n float total_float = static_cast(total);\n float ret = 0.0;\n for (unsigned i = 0; i &lt; 256; ++i) {\n float p = static_cast(counts[i]) / total_float;\n ret -= p * logf(p);\n }\n return p * M_LN2;\n }<br>\n Entropy: 2.866</p>\n \n <p>~~~~~~No.~~~~~~<br>\n Entropy: 0.720</p>\n \n <p>asdasdasdasdasdasd<br>\n Entropy: 1.099</p>\n \n <p>abcdefghijklmnopqrstuvwxyz<br>\n Entropy: 3.258</p>\n \n <p>Fuuuuuuu-------<br>\n Entropy: 0.892</p>\n</blockquote>\n\n<hr>\n\n<p>Actually, I think it would be better to do some frequency analysis, but I don't know anything about the frequencies of symbols used in code. The best place to determine that would be the stackoverflow data-dump - I'll have to get back to you after it finishes downloading, in 2 years.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T18:46:04.730", "Id": "926", "ParentId": "868", "Score": "25" } }, { "body": "<p>I just whipped this algorithm together, so I have no idea how good this is. I fear that it will cause an overflow exception if used on <em>very</em> long strings.</p>\n\n<p>Key concepts of this algorithm:</p>\n\n<ul>\n<li>When encountering a character for the first time, the maximum value is added to the un-normalized entropy total. The \"maximum value\" is the length of the string.</li>\n<li>If a character is encountered again, then we count the number of positions between this occurrence and the last occurrence, then we subtract the total number of times this character has appeared in the string. We then add that value to the un-normalized entropy total.</li>\n<li><p>Once the final un-normalized entropy total has been calculated, it is divided by the length of the string in order to \"normalize\" it.</p>\n\n<pre><code>public static int Entropy(this string s)\n{\n int entropy = 0;\n\n var mapOfIndexByChar = new Dictionary&lt;char, CharEntropyInfo&gt;();\n\n int index = 0;\n foreach (char c in s)\n {\n CharEntropyInfo charEntropyInfo;\n if (mapOfIndexByChar.TryGetValue(c, out charEntropyInfo))\n {\n // If this character has occurred previously, then only add the number of characters from\n // the last occurrence to this occurrence, and subtract the number of previous occurrences.\n // Many repeated characters can actually result in the entropy total being negative.\n entropy += ((index - charEntropyInfo.LastIndex) - charEntropyInfo.Occurrences);\n\n // update the last index and number of occurrences of this character\n mapOfIndexByChar[c] = new CharEntropyInfo(index, charEntropyInfo.Occurrences + 1);\n }\n else\n {\n // each newly found character adds the maximum possible value to the entropy total\n entropy += s.Length;\n\n // record the first index of this character\n mapOfIndexByChar.Add(c, new CharEntropyInfo(index, 1));\n }\n }\n\n // divide the entropy total by the length of the string to \"normalize\" the result\n return entropy / s.Length;\n}\n\nstruct CharEntropyInfo\n{\n int _LastIndex;\n int _Occurrences;\n\n public int LastIndex\n {\n get { return _LastIndex; }\n }\n public int Occurrences\n {\n get { return _Occurrences; }\n }\n\n public CharEntropyInfo(int lastIndex, int occurrences)\n {\n _LastIndex = lastIndex;\n _Occurrences = occurrences;\n }\n}\n</code></pre></li>\n</ul>\n\n<p>A quick test:</p>\n\n<pre><code> var inputs = new[]{\n \"Hi there!\",\n \"Hi there, bob!\",\n \"ababababababababababababab\",\n @\"We're calculating entropy of a string a few places in Stack Overflow as a signifier of low quality.\n\nI whipped up this simple method which counts unique characters in a string, but it is quite literally the first thing that popped into my head. It's the \"\"dumbest thing that works\"\".\"\n };\n\n foreach (string s in inputs)\n {\n System.Console.WriteLine(\"{1}: \\\"{0}\\\"\", s, s.Entropy());\n }\n</code></pre>\n\n<p>Resulting entropy values:</p>\n\n<ul>\n<li>7: \"Hi there!\"</li>\n<li>10: \"Hi there, bob!\"</li>\n<li>-4: \"ababababababababababababab\"</li>\n<li>25: \"We're calculating entropy of a string ...\"</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-06T21:41:40.773", "Id": "7542", "ParentId": "868", "Score": "14" } }, { "body": "<p>I have seen many answers that suggest counting the number of distinct characters. <strong>But beware that this only works for 16-bit characters!</strong></p>\n\n<p>A character in C# is a <a href=\"https://stackoverflow.com/questions/10572902/encoding-char-in-c-sharp\">UTF-16 code unit</a>. Extended unicode characters are stored in multiple C# characters. <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.globalization.charunicodeinfo.getunicodecategory?view=netframework-4.8\" rel=\"nofollow noreferrer\">CharUnicodeInfo.GetUnicodeCategory</a> allows us to detect whether a C# character represents a real character or whether it is part of an extended unicode character or combined character (UnicodeCategory.Surrogate).</p>\n\n<p><strong>Test (fake) entropy:</strong></p>\n\n<pre><code> public static void Main()\n {\n var value = \"\\U00020B20\";\n\n // yields 2, even though \\U00020B20 represents a single unicode-character ''\n var entropyTest = value.Distinct().Count(); \n }\n</code></pre>\n\n<p>In order to count the characters (not the C# characters), we need to augment our algorithm. I am using a class called <a href=\"https://en.wikipedia.org/wiki/Grapheme\" rel=\"nofollow noreferrer\">Grapheme</a> to do the trick. This class is able to detect <em>extended unicode characters</em> and <a href=\"https://en.wikipedia.org/wiki/Diacritic\" rel=\"nofollow noreferrer\">diacritics</a>.</p>\n\n<p><strong>Test entropy:</strong></p>\n\n<pre><code> public static void Main()\n { \n var grapheme = Grapheme.Parse(\"\\U00020B20\");\n\n // yields 1, as \\U00020B20 represents a single unicode-character ''.\n var entropyTest = grapheme.Select(x =&gt; x.Glyph).Distinct().Count();\n\n // yields 2, as \\U00020B20 is stored in 2 C# characters.\n var codeUnits = grapheme.Single().CodeUnits.Length;\n }\n</code></pre>\n\n<p><strong>Final note:</strong></p>\n\n<p>Testing entropy on a string is <strong>not</strong> <em>context-free</em>. Some characters or combined characters result in the same glyph, depending on the <a href=\"https://en.wikipedia.org/wiki/Font\" rel=\"nofollow noreferrer\">Font</a> used. So entropy can only be calculated in the context of a font. The Grapheme class does not take this into account, since different fonts would render different entropies. The Grapheme class is said to be <em>context-free</em>.</p>\n\n<ul>\n<li>(A) two different characters might have the exact same glyph (homoglyph)</li>\n<li>(B) combined characters might have the same glyph as another character</li>\n</ul>\n\n<p>Examples:</p>\n\n<ul>\n<li>A: \\u0061 and \\u0430 represent both the letter 'a' in certain fonts</li>\n<li>B: Å is both the character \\u00C5 and the combined character <code>A</code> with an <a href=\"https://en.wikipedia.org/wiki/Dot_(diacritic)\" rel=\"nofollow noreferrer\">overdot</a> character</li>\n</ul>\n\n<p><strong>Appendix: Grapheme</strong></p>\n\n<pre><code>public class Grapheme\n{\n private char[] _codeUnits;\n private Grapheme[] _diacritics;\n private string _glyph;\n\n public Grapheme(string glyph) {\n\n Guard.NotNull(glyph, \"glyph\");\n _glyph = StringInfo.GetNextTextElement(glyph);\n Guard.Condition(_glyph.Length != glyph.Length, \"glyph\", \"Invalid glyph specified\");\n\n var codeUnits = new List&lt;char&gt;();\n var diacritics = new List&lt;Grapheme&gt;();\n var buffer = _glyph;\n\n if (buffer.Length &gt; 0) {\n var cu0 = CharUnicodeInfo.GetUnicodeCategory(buffer[0]);\n switch (cu0) {\n case UnicodeCategory.Surrogate:\n codeUnits.AddRange(buffer.Take(2));\n buffer = buffer.Substring(2);\n break;\n default:\n codeUnits.Add(buffer[0]);\n buffer = buffer.Substring(1);\n break;\n }\n diacritics.AddRange(Parse(buffer));\n }\n\n _codeUnits = codeUnits.ToArray();\n _diacritics = diacritics.ToArray();\n\n if (_codeUnits.Length == 2) {\n Guard.Condition(!char.IsSurrogatePair(new string(_codeUnits), 0),\n \"glyph\", \"Invalid surrogate pair specified\");\n }\n }\n\n public static Grapheme[] Parse(string value) {\n Guard.NotNull(value, \"value\");\n return StringInfo.ParseCombiningCharacters(value).Select(i \n =&gt; new Grapheme(StringInfo.GetNextTextElement(value, i))).ToArray();\n }\n\n public static int[] ParseIndices(string value) {\n Guard.NotNull(value, \"value\");\n return StringInfo.ParseCombiningCharacters(value).ToArray();\n }\n\n public static Grapheme ParseNext(string value, int index) {\n return new Grapheme(StringInfo.GetNextTextElement(value, index));\n }\n\n public static Grapheme ParseNext(string value) {\n return ParseNext(value, 0);\n }\n\n public char[] CodeUnits { \n get { \n return _codeUnits; \n }\n }\n\n public Grapheme[] Diacritics {\n get { \n return _diacritics; \n }\n }\n\n public string Glyph {\n get { \n return _glyph;\n }\n }\n\n public Grapheme[] Flatten() {\n return new[] { this }.Concat(_diacritics.SelectMany(x =&gt; x.Flatten())).ToArray();\n }\n\n public Grapheme Normalize() {\n return new Grapheme(_glyph.Normalize());\n }\n\n public Grapheme Normalize(NormalizationForm form) {\n return new Grapheme(_glyph.Normalize(form));\n }\n\n public override bool Equals(object obj) {\n if (obj is Grapheme) {\n return string.Equals(((Grapheme)obj)._glyph, _glyph);\n }\n return false;\n }\n\n public override int GetHashCode() {\n return _glyph.GetHashCode();\n }\n\n public override string ToString() {\n return _glyph;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T09:57:10.613", "Id": "220456", "ParentId": "868", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T21:21:40.627", "Id": "868", "Score": "241", "Tags": [ "c#", "strings" ], "Title": "Calculating entropy of a string" }
868
<p>I often run into the problem of producing a javascript array on an ASP.net page from an IEnumerable and I was wondering if there was an easier or clearer way to do it than</p> <pre><code>&lt;% bool firstItem = true; foreach(var item in items){ if(firstItem) { firstItem = false; } else {%&gt; , &lt;%}%&gt; '&lt;%:item%&gt;' %&gt; </code></pre> <p>The whole thing is made much more verbose because of IE's inability to handle a hanging comma in an array or object.</p>
[]
[ { "body": "<p>With a bit of help from System.Linq this becomes quite easy.</p>\n\n<pre><code>var array = [ &lt;%= \n string.Join(\",\", items.Select(v =&gt; \"'\" + v.ToString() + \"'\").ToArray()) \n%&gt; ];\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T01:33:43.007", "Id": "1620", "Score": "0", "body": "Oh I really like that." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T15:55:00.740", "Id": "1732", "Score": "2", "body": "I really do hope the items never contain an apostrophe character or the `</script>` character sequence. A good solution would guard against these possibilities." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-09T14:12:34.553", "Id": "51861", "Score": "0", "body": "The answer below should properly handle that: http://codereview.stackexchange.com/questions/881/is-there-a-better-way-to-output-a-javascript-array-from-asp-net/960#960" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T01:22:20.473", "Id": "887", "ParentId": "881", "Score": "6" } }, { "body": "<p>You can use an anonymous class and DataContractJsonSerializer and do something like this:</p>\n\n<pre><code>\nvar toSerialize = items.Select(x => new { JSProp = x.ItemProp }).ToList();\n\nvar serializer = new DataContractJsonSerializer(toSerialize.GetType());\nMemoryStream ms = new MemoryStream();\nserializer.WriteObject(ms, myPerson);\nstring json = Encoding.Default.GetString(ms.ToArray());\n</code></pre>\n\n<p>I like this approach because you can create complex javascript types in a simply way.</p>\n\n<p>Sorry if it does not compile but I'm not with a dev machine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T15:57:04.780", "Id": "1733", "Score": "0", "body": "I would find this cleaner and more robust if it used `using` clauses for the stream and the serializer." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T00:15:44.067", "Id": "1758", "Score": "0", "body": "Yeah, sure! The idea was to show the anonymous type generation with LINQ" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T00:41:15.083", "Id": "937", "ParentId": "881", "Score": "1" } }, { "body": "<p>Use the JavaScriptSerializer from System.Web.Extensions</p>\n\n<p><code>&lt;%: new JavaScriptSerializer().Serialize(items) %&gt;</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T22:53:44.107", "Id": "960", "ParentId": "881", "Score": "4" } } ]
{ "AcceptedAnswerId": "887", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-20T22:34:53.247", "Id": "881", "Score": "9", "Tags": [ "c#", "javascript", "asp.net" ], "Title": "Is there a better way to output a javascript array from ASP.net?" }
881
<p>Here's my code:</p> <pre><code>public static void CopyStream(Stream input, Stream output) { var size = 8192; var inBuffer = new byte[size]; var outBuffer = new byte[size]; IAsyncResult writeAsync = null; int count; while (true) { var readAsync = input.BeginRead(inBuffer, 0, size, null, null); if (writeAsync != null) { output.EndWrite(writeAsync); writeAsync = null; } count = input.EndRead(readAsync); inBuffer.CopyTo(outBuffer, 0); if (count &gt; 0) { writeAsync = output.BeginWrite(outBuffer, 0, count, null, null); } else { break; } } } </code></pre> <p>This really is my first piece of code using the Begin/End asynchronous model. I'm just wondering if I have any glaring issues.</p> <p>Or, are there any improvements that you can see to make this even better?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T01:34:25.333", "Id": "1621", "Score": "0", "body": "This is a cross-post of http://stackoverflow.com/questions/5061345/, but I'm not sure how to handle the closing of the other site's question." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T01:34:51.030", "Id": "1622", "Score": "0", "body": "Also, could somebody with more rep add the 'asynchronous' and 'stream' tags to this?" } ]
[ { "body": "<p>It's not entirely clear what your goals are with this bit of code. Three possibilities that come to mind:</p>\n\n<ul>\n<li>CopyStream should be asynchronous. As written, it does not meet this goal since it blocks on the results of EndRead and EndWrite. If this is your goal, you need to use callback methods and not call the End methods until your callbacks have been called. You also need to modify CopyStream's signature to return IAsyncResult and take a callback and state as parameters.</li>\n<li>CopyStream should hide the details of the underlying asynchronous calls from its users, but is itself synchronous. Your code accomplishes this goal, but there are a few things that could use cleaning up.</li>\n<li>CopyStream should hide the details of the underlying asynchronous calls, and also maximize performance by making sure the writer is kept busy at all times and never sitting around idle waiting for reads, to the extent possible. It seems like this may have been your goal due to the attempt to read/write in parallel, but by only allowing a single outstanding read or write, you're not really getting much out of it. In order to implement this correctly, you need to use a reader thread and a writer thread, with a queue of items to be written. The reader reads as fast as it can and inserts chunks of data into the queue, which the writer then writes as fast as it can or as fast as they show up.</li>\n</ul>\n\n<p>EDIT:</p>\n\n<p>As an example of how to write this code using a queue, see the following. Note that I didn't need to spin up a thread because I can just make use of the EndRead/EndWrite callbacks and have the original thread wait for a signal to be raised. Also, this is a lightly-tested first draft, so beware that there could be bugs lurking in there. This type of code is complex and difficult to get right, and should only be used when really necessary for valid perf reasons. If the complexity is not justified, I would just use the synchronous Read and Write methods to simplify the code as much as possible.</p>\n\n<pre><code>public static void CopyStream(Stream input, Stream output)\n{\n AutoResetEvent completed = new AutoResetEvent(false);\n BeginRead(new CopyStreamState(completed, input, output));\n\n completed.WaitOne();\n}\n\nprivate static void BeginRead(CopyStreamState state)\n{\n const int bufferSize = 8192;\n\n state.InputBuffer = new byte[bufferSize];\n state.Input.BeginRead(state.InputBuffer, 0, bufferSize, ReadCallback, state);\n}\n\nprivate static void ReadCallback(IAsyncResult ar)\n{\n CopyStreamState state = (CopyStreamState)ar.AsyncState;\n\n int bytesRead = state.Input.EndRead(ar);\n if (bytesRead &gt; 0)\n {\n byte[] dataToWrite = state.InputBuffer;\n\n if (bytesRead &lt; state.InputBuffer.Length)\n {\n dataToWrite = new byte[bytesRead];\n Array.Copy(state.InputBuffer, dataToWrite, bytesRead);\n }\n\n EnqueueWriteData(state, dataToWrite);\n BeginRead(state);\n }\n else\n {\n state.FinishedReading = true;\n }\n\n BeginWriteOrComplete(state);\n}\n\nprivate static void EnqueueWriteData(CopyStreamState state, byte[] data)\n{\n lock (state)\n {\n state.WriteQueue.Enqueue(data);\n }\n}\n\nprivate static void BeginWriteOrComplete(CopyStreamState state)\n{\n lock (state)\n {\n if (!state.WriteInProgress)\n {\n if (state.WriteQueue.Count &gt; 0)\n {\n byte[] outputBuffer = state.WriteQueue.Dequeue();\n state.WriteInProgress = true;\n state.Output.BeginWrite(outputBuffer, 0, outputBuffer.Length, WriteCallback, state);\n }\n else if (state.FinishedReading)\n {\n state.Completed.Set();\n }\n }\n }\n}\n\nprivate static void WriteCallback(IAsyncResult ar)\n{\n CopyStreamState state = (CopyStreamState)ar.AsyncState;\n state.Output.EndWrite(ar);\n\n lock (state)\n {\n state.WriteInProgress = false;\n BeginWriteOrComplete(state);\n }\n}\n\nprivate class CopyStreamState\n{\n public CopyStreamState(\n AutoResetEvent completed, \n Stream input, \n Stream output)\n {\n this.Completed = completed;\n this.Input = input;\n this.Output = output;\n this.WriteQueue = new Queue&lt;byte[]&gt;();\n }\n\n public AutoResetEvent Completed { get; private set; }\n public Stream Input { get; private set; }\n public Stream Output { get; private set; }\n public Queue&lt;byte[]&gt; WriteQueue { get; private set; }\n\n public byte[] InputBuffer { get; set; }\n public bool FinishedReading { get; set; }\n public bool WriteInProgress { get; set; }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T03:31:54.577", "Id": "1623", "Score": "0", "body": "Ah, cool, thanks for the info on swapping buffers. Anyways, the second or third bullet point are what I was looking for." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T03:33:05.700", "Id": "1624", "Score": "0", "body": "However, I'm not seeing how having a Queue in between the reader and writer will actually help the overall time of the method go down. I mean, it will ensure that the faster operation is done as soon as possible, but even with the Queue, you are still limited by the slowest of the two..." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T03:38:16.680", "Id": "1625", "Score": "0", "body": "You are still limited by the slowest of the two (writing), but the queue ensures that you can write continuously instead of having to move in lock-step with reading. As it is now, your reader will sit idle while waiting for the writer, and then writer has to sit idle while waiting for the reader. By using a queue, you can allow the reader to move as fast as it can, and ensure that the writer always has something to write, so it never sits idle. Certainly, the reader will finish first and the writer will take longer, but the overall time can go down considerably." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T10:21:16.743", "Id": "1631", "Score": "0", "body": "I would say that using a queue is the single most important thing here. Using a queue would eliminate any and all swapping/copying of buffers. At least to me, that was the first thing that caught my mind when reading the code." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T18:15:16.057", "Id": "1644", "Score": "0", "body": "Ok, fair enough. However, this method needs to be synchronous. What is the simplest way to do this with a queue? Certainly we are going to need to spin up at least 1 Thread (possibly from the pool), and will need locking around the queue, and cross thread signaling, and.... this is getting complex. Not difficult, just complex." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T22:27:30.760", "Id": "1654", "Score": "0", "body": "Yes, using a queue and a concurrent reader and writer is definitely more complex. However, if your goal is to keep the writer as busy as possible, that's the only way to do it. What you have now is not considerably better than just doing the reads and writes fully synchronously, and you'd be better off (less complexity, same basic perf) if you just use the synchronous Read and Write methods. Give me a few minutes and I'll add an example of how to do this to my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-15T15:20:59.703", "Id": "3202", "Score": "0", "body": "Very nicely done @Saeed!!\nI've added an edit to the code above. The **ReadCallback** can be simplified to enqueue the buffer directly because upon calling **BeginRead** the buffer gets set to a new object. Therefore we can eliminate copying the array to another variable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-30T17:03:56.127", "Id": "3528", "Score": "0", "body": "@Adam, Thanks for the changes but I reverted it back to the original code. The new changes have a compiler bug (there is no BufferSize), but also I feel that the new conditional was more complex and introduced unnecessary redundant calls to EnqueueWriteData and BeginRead. The original code already only copied the buffer if the bytesRead was smaller than requested, so the new complexity did not add any benefit." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-21T03:27:21.547", "Id": "893", "ParentId": "888", "Score": "7" } }, { "body": "<p>Just a quick note: If I'm following your code correctly, I just can't see how the last <code>if (writeAsync != null)</code> could ever be true.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T18:11:25.420", "Id": "1643", "Score": "0", "body": "You're right. My bad. I originally had the EndRead call at the top of the loop." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T10:27:22.887", "Id": "895", "ParentId": "888", "Score": "1" } } ]
{ "AcceptedAnswerId": "893", "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T01:33:23.120", "Id": "888", "Score": "10", "Tags": [ "c#", "asynchronous" ], "Title": "Am I overlooking anything with this asynchronous read/write loop?" }
888
<p>I want to create a validation wherein blank entries will not be accepted. So if I call this code:</p> <pre><code>entry[i].setName(JOptionPane.showInputDialog("Enter Name: ")); if the entry is blank, it will not be accepted and an error will prompt: </code></pre> <p>it cannot accept blank entries. Of course it could easily remedied with this code:</p> <pre><code>String name = JOptionPane.showInputDialog("Enter Name: "); while (name.equals("")){ JOptionPane.showMessageDialog(null, "Cannot accept blank entries!"); name = JOptionPane.showInputDialog("Enter Name: "); } </code></pre> <p>but if I want to validate 100 fields that I don't want to have a blank entry, then my code will be messy and long.</p> <p>How could I do it better? I've read about using getters and setters or the try-catch methods to do the validation but I don't know if this kind of validation is applicable. And I don't know how I can do it. And if it is applicable, would I be violating the Model-View-Controller concept if I included a <code>JOption</code> message dialog box on my getter and setter methods? What code does programmers usually use in doing blank entries validation?</p>
[]
[ { "body": "<p>Extract the input code into a method:</p>\n\n<pre><code>String getNonBlankInput(String prompt) {\n String input = JOptionPane.showInputDialog(prompt);\n\n while (input.equals(\"\")) {\n JOptionPane.showMessageDialog(null, \"Cannot accept blank entries!\");\n input = JOptionPane.showInputDialog(prompt);\n }\n\n return input;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>String name = getNonBlankInput(\"Enter name: \");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T02:19:06.757", "Id": "890", "ParentId": "889", "Score": "5" } }, { "body": "<p>Please change the validating condition like this.</p>\n\n<pre><code>while (\"\".equals(input.trim())) {\n JOptionPane.showMessageDialog(null, \"Cannot accept blank entries!\");\n input = JOptionPane.showInputDialog(prompt);\n}\n</code></pre>\n\n<p>This type of validation may also check only blanks as input &amp; any other value also.</p>\n\n<pre><code>1. String name = JOptionPane.showInputDialog(\"Enter Name: \"); contains spaces.\n2. String name = JOptionPane.showInputDialog(\"Enter Name: \"); contains null.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T09:49:20.653", "Id": "894", "ParentId": "889", "Score": "2" } }, { "body": "<p>You should really look at the java validation standard, specifically JSR303.</p>\n\n<p><a href=\"http://www.hibernate.org/subprojects/validator.html\" rel=\"nofollow\">Hibernate Validator</a> is the reference implementation, take a look at <a href=\"http://docs.jboss.org/hibernate/validator/4.2/reference/en-US/html/\" rel=\"nofollow\">their documentation</a>.</p>\n\n<p>To provide a simple example</p>\n\n<pre><code>public class Foo {\n @NotNull(message = \"property bar must be provided\")\n @Pattern(regexp = \"[a-z0-9]\", message = \"property bar must contain only letters and numbers\")\n private String bar;\n}\n\nValidatorFactory factory = Validation.buildDefaultValidatorFactory();\nvalidator = factory.getValidator();\n\nFoo foo = new Foo();\n\nSet&lt;ConstraintViolation&lt;Foo&gt;&gt; constraintViolations = validator.validate(foo);\n// now you have a Set of ConstraintViolations, if something is not working\n</code></pre>\n\n<p>Use the existing standards, no need to reinvent the wheel.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-04T10:09:45.950", "Id": "518305", "Score": "0", "body": "You misunderstand the question, he never speak about hibernate. So before making ugly comment with your wheel, try to understand the question." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T19:50:54.160", "Id": "1027", "ParentId": "889", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-21T02:07:04.827", "Id": "889", "Score": "6", "Tags": [ "java", "beginner", "validation" ], "Title": "Data validation for preventing blank entries" }
889
<p>I have created a <code>HashMap&lt;string,int&gt;</code> in C++. I would like help determining if it is good or bad.</p> <p>I have not handled the errors or successes with messages. I have also not implemented the load factor in this map. As of now, once the size limit is reached, no more keys are accepted. I have written this code for just educational purpose only. I would like to know few things to make it better. </p> <ol> <li><p>How can I implement the load factor concept? The hash function <code>O/P</code> is dependent on the previous table size. If we are to change the table size, the old <code>&lt;key, value&gt;</code> pair will be lost.</p></li> <li><p>How can I make this generic? i.e. instead of <code>&lt;string,int&gt;</code>, is it possible to write a template code for both key and the value?</p> <p>Implementing a hash function will not be a problem, since the hash function can be overloaded. What about the storage? In case of Java, the key and value will be treated as <code>Object</code>. Is there any option similar to that in C++?</p></li> <li><p>Any other important (or mandatory) feature this map is missing?</p></li> </ol> <p></p> <pre><code>#include &lt;string&gt; #include &lt;vector&gt; using namespace std; typedef struct Node { string key; int value; struct Node * left; struct Node * right; }doubly; class myHashStrKey{ private: int currentCount; int hashsize; // Default n = 2000. So 701 slots will be initialized. vector&lt;doubly *&gt; table; //hash function taken from net and modified. size_t hash(const std::string data) { size_t h(0); for (int i=0; i&lt;data.length(); i++){ h = (h &lt;&lt; (31-i) ^ (h &gt;&gt; i) ^ data[i]); } h = h%hashsize; return h; } //Inserts the key and value. If the key is already present, the value is updated. //Checks if the currentCount &lt; (hashsize+1)*3 void insertNode(doubly ** root, int Value, const string Key){ if(*root ==NULL){ if(myHashStrKey::currentCount &gt;= ((hashsize+1)*3)) return; doubly * newNode = new doubly(); newNode-&gt;value = Value; newNode-&gt;left = NULL; newNode-&gt;right = NULL; newNode-&gt;key = (Key); *root = newNode; myHashStrKey::currentCount++; return; } doubly * prev = NULL; doubly * current = *root; while(current != NULL &amp;&amp; ((current)-&gt;key).compare(Key)){ prev = current; current = current-&gt;right; } if(current ==NULL){ if(myHashStrKey::currentCount &gt;= ((hashsize+1)*3)) return; doubly *newNode = new doubly(); newNode-&gt;value = Value; newNode-&gt;key = Key; newNode-&gt;left = prev; newNode-&gt;right = NULL; prev-&gt;right = newNode; myHashStrKey::currentCount++; } else{ (current)-&gt;value = Value; } } //Return the corresponding value for the given key from the table int getNodeValue(doubly * root, string key){ while(root != NULL){ if(!key.compare(root-&gt;key)){ return root-&gt;value; } root = root-&gt;right; } return -1; } //Removes the node from bucket if present and reduces the currentcount //else nothing. void removeNode(doubly ** root, string Key){ doubly * toRemove; doubly * head = *root; //Check to see if the first element is the target. if((head != NULL) &amp;&amp;!(head-&gt;key).compare(Key)){ toRemove = head; *root = head-&gt;right; if(head-&gt;right != NULL) head-&gt;right-&gt;left = NULL; delete toRemove; myHashStrKey::currentCount--; return; } //First element is not the target. else{ if(head == NULL) return; while((head != NULL) &amp;&amp;(head-&gt;key).compare(Key)){ head = head-&gt;right; } //Element not present. return if(head == NULL) return; //Element found. Remove the element and decrement currentCount. toRemove = head; head-&gt;left-&gt;right = head-&gt;right; if(head-&gt;right !=NULL) head-&gt;right-&gt;left = head-&gt;left; myHashStrKey::currentCount--; delete toRemove; return; } } public: //Constructor for default size. //I am considering that hash table size to have default value of 701. //The average elements per bucket is 3. //THe total allowed elements will be 701*3 i.e. tablesize*3. myHashStrKey(){ myHashStrKey::currentCount=0; myHashStrKey::hashsize = 701; myHashStrKey::table.insert(myHashStrKey::table.begin(),hashsize,((doubly *)NULL)); } //Constructor for the user given size //Hashsize is calculated to be size/3 +1 (average elements per bucket is 3) myHashStrKey(int size){ myHashStrKey::currentCount=0; myHashStrKey::hashsize = size/3 +1; myHashStrKey::table.insert(myHashStrKey::table.begin(),hashsize,((doubly *)NULL)); } //Adds entry to the HashMap void addKeyValue(const string &amp;key,int value ){ size_t keyHash = hash(key); insertNode(&amp;(table[keyHash]), value, key); } //Gets the corresponding value for the key if present else nothing int getValue(const string &amp;key ){ size_t keyHash = hash(key); int result = getNodeValue(table[keyHash],key); return result; } //Deletes the key if present else nothing. void deleteKey(const string &amp;key){ size_t keyHash = hash(key); removeNode(&amp;(table[keyHash]),key); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T04:10:48.710", "Id": "1627", "Score": "5", "body": "I suggest you look at the boost implementation of a TR1 unordered_map." } ]
[ { "body": "<blockquote>\n <p>How to implement the load factor concept, because the hash function o/p is dependent on the previous table size. If we are to change the table size, the old <code>&lt;key, value&gt;</code> pair will be lost.</p>\n</blockquote>\n\n<p>You will need to rehash when the table size changes, removing the nodes from the old table and inserting them in their new locations in the new table. I would suggest that you remove the line <code>h = h%hashsize;</code> from the <code>hash</code> function, and apply the modulo operation when you're actually doing the table lookup, for two reasons:</p>\n\n<ul>\n<li>The hash function will no longer be dependent on the hash table, and can be made a static or non-member function</li>\n<li>You can store the raw hash value in the node, so you won't need to recalculate when you rehash.</li>\n</ul>\n\n<blockquote>\n <p>How to make this generic ? i.e. instead of <code>&lt;string,int&gt;</code> , is it possible to write a template code for both key and the value ?</p>\n</blockquote>\n\n<p>You can make it generic by turning it into a class template, with template parameters to specify the key and value types:</p>\n\n<pre><code>template &lt;typename Key, typename Value&gt;\nclass MyHashMap\n{\n struct Node\n {\n Key key;\n Value value;\n ...\n };\n ...\n};\n</code></pre>\n\n<p>Then find where you're using <code>string</code> as a key type and replace it with <code>Key</code>; similarly, replace <code>int</code> as a value type with <code>Value</code>. You'll then need to make sure you're always using generic rather than type-specific operations on them. In particular, your (slightly odd) string comparisons will need to change from, for example, <code>!(head-&gt;key).compare(key)</code> to <code>head-&gt;key == key</code> - which is rather more readable anyway, in my opinion.</p>\n\n<p>Finally, as you say, you'll need hash functions for each key type. The best way to support this is to move the hash function outside the class; then any user of the hash template can overload it for their own types.</p>\n\n<blockquote>\n <p>Any other important (or mandatory )feature this map is missing ?</p>\n</blockquote>\n\n<p>You do not have a destructor, so when the map is destroyed any memory allocated for the nodes will be lost. There are two choices here:</p>\n\n<ul>\n<li>Add a destructor to walk through all remaining nodes and delete them. Add a copy constructor and assignment operator (or declare them private), to prevent shallow copying leading to double deletion.</li>\n<li>Use a memory-managed container to store the nodes; remove the <code>left</code> and <code>right</code> pointers, and change the type of <code>table</code> from <code>vector&lt;Node*&gt;</code> to <code>vector&lt;vector&lt;Node&gt; &gt;</code>. In my opinion, this would be the better option, as it removes the responsibility for memory management from your class.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T21:45:11.893", "Id": "1806", "Score": "0", "body": "Thanks Mike. I have been thinking about the implementation details which you suggested. 1. If the implementation is going to be in vector<vector<node>>, where the first dimension will be my effective table and the second will act as the bucket. If this is the case, then how do I decide the place in the table i.e. the first dimension without doing 'h = h%hashsize;'. 2. Moving the hash function. I dont understand what you mean by \"any user of the hash template can overload it \". I had initially thought of having overloaded hash function for all data type . Please clarify my doubts" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T14:01:19.680", "Id": "1854", "Score": "0", "body": "1. You calculate the table index as `hash(key)%hashsize`. You are still doing the modulo calculation, but not in the hash function itself; that means the hash function is independent of the hash table." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T14:04:39.677", "Id": "1855", "Score": "0", "body": "2. You can (and should) overload the hash function for most, if not all, built-in and standard types. However, the user might define a different type (which you have no knowledge of) and want to use it as a hash key. By placing the hash function in the namespace outside your hash table, anyone can create overloads for their own types, and use them as keys in your template. By leaving it as a member, they are restricted to the types that you provide overloads for." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T18:51:32.597", "Id": "1935", "Score": "0", "body": "One more question though, instead of using the second dimension as a vector, would it help in performance if I used a List ??? I was thinking about the (1) for few days and this morning I got it and I logged in to say that and I see your comment :) . Now I got the (2) point . Thank you." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T10:33:53.067", "Id": "1966", "Score": "1", "body": "A vector will most likely be faster, as it will involve fewer memory allocations when adding and removing elements, and probably better cache behaviour when iterating through it. Since the order doesn't matter, you can add elements at the end, and remove one by swapping it with the last element, then removing it from the end. These are all constant-time operations, so a list wouldn't improve on that." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T21:12:06.977", "Id": "1994", "Score": "0", "body": "I like the swapping part" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T11:47:56.303", "Id": "924", "ParentId": "892", "Score": "9" } }, { "body": "<p>Other features which may be convenient and are missing: <code>isEmpty()</code>, <code>size()</code>, <code>addAll()</code>, <code>removeAll()</code>, set view of the keys, subset views based on input key. Also even if it is not your primary concern the lookup time seems to be in logarithmic magnitude which can reduce its interest.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-05T12:20:15.677", "Id": "2052", "Score": "0", "body": "The lookup time isn't logarithmic; finding the bucket takes constant time, and finding the node within the bucket is linear in the bucket size (which should be small if the hash function is good and the map isn't too full)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T17:28:10.940", "Id": "2084", "Score": "0", "body": "Correct, went thru the code too quickly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-03T18:11:29.457", "Id": "1130", "ParentId": "892", "Score": "-1" } } ]
{ "AcceptedAnswerId": "924", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-21T03:17:14.243", "Id": "892", "Score": "11", "Tags": [ "c++", "hash-map" ], "Title": "Improving HashMap in C++" }
892
<p>I have this piece of code I would like some help with. I'm running a lengthy process that I want to interrupt at any time. The thing is, as you can see in the code, I have <code>if(stop)</code> everywhere, also in the methods inside the <code>for</code> (since they have <code>for</code> loops also).</p> <p><code>stop</code> is a member variable of the class, and the <code>Stop()</code> method is called from the UI from a different thread.</p> <p>I don't think making it multithreading would be a good option since would be more complex to keep state and to communicate between threads.</p> <p>Can you think of a better way to solve this, making the code cleaner?</p> <pre><code>public void Start() { for(int i = 0; i &lt; Length; i++) { if(stop) return; LengthyMethodA(); if(stop) return; LengthyMethodB(); if(stop) return; LengthyMethodC(); } } public void Stop() { stop = true; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-07T18:27:05.163", "Id": "107105", "Score": "0", "body": "You can also look into using a cancellation token instead (http://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx)." } ]
[ { "body": "<p>Any answer given will be completely conditional. Can you be sure that stopping after step B will not have dire consequences related to the fact that step A was completed successfully? I recommend you break each section into work that must be completed with a chance to terminate before entering. Then I recommend you switch to <code>AutoResetEvent</code> which is thread safe. Unfortunately this really won't lead to less code but it will make your code more robust. </p>\n\n<pre><code>private readonly AutoResetEvent _stopRunning = new AutoResetEvent(false);\n\npublic void Start()\n{\n for(int i = 0; i &lt; Length; i++)\n { \n if (_stopRunning.WaitOne(1)) return;\n WorkThatMustRunToCompletion();\n }\n}\n\npublic void Stop()\n{\n _stopRunning.Set(); \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T07:50:29.497", "Id": "1657", "Score": "0", "body": "If you mark the bool as volatile then it would still be perfectly thread safe (I think even without volatile, the most it would suffer from is a delay in realising the flag had changed). If you do however use a WaitHandle like this, then I suggest passing 0 into WaitOne() instead of 1. This will avoid the cost of a block and context switch when not told to stop." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T16:31:11.877", "Id": "901", "ParentId": "899", "Score": "2" } }, { "body": "<p>You say that <code>Start</code> is running in a thread other than the UI thread and that the <code>Stop</code> method is called from the UI thread.</p>\n\n<p>That being the case, why not just call <code>Abort</code> on the thread Start is running in? This throws a <code>ThreadAbortException</code> in the Start thread and causes your code to fall through as you intend.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T22:21:05.130", "Id": "1651", "Score": "3", "body": "Microsoft's [Managed Threading Best Practices](http://msdn.microsoft.com/en-us/library/1c9txz50(v=VS.100).aspx) say to avoid calling Thread.Abort on another threads." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T19:50:39.127", "Id": "1681", "Score": "0", "body": "Yes, it does, under \"Consider the following guidelines when using multiple threads\". But if killing the thread without needing to know where it has got to is your goal, which it seems to be here, then you consider it and disregard it" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T21:37:41.270", "Id": "1683", "Score": "1", "body": "+1 It's really a good idea, I didn't even thought about it, I think I was too inside my code, couldn't see it from the outside (the UI :D), anyway I'm accepting mongus answer because it looks like a better practice for broader use cases." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T22:28:43.097", "Id": "1685", "Score": "0", "body": "@rodrigoq - Agree. Both valid solutions, depending on the problem, and Mongo's is better in more cases" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T17:59:42.873", "Id": "904", "ParentId": "899", "Score": "4" } }, { "body": "<p>You could always set up a list of Actions that need to be worked on, and then loop through them checking for Stop each time.</p>\n\n<p>Something like :</p>\n\n<pre><code>List&lt;Action&gt; actions = new List&lt;Action&gt; {\n () =&gt; LengthyMethodA(),\n () =&gt; LengthyMethodB(),\n () =&gt; LengthyMethodC() };\n\n for(int i = 0; i &lt; Length; i++)\n { \n foreach (Action action in actions)\n {\n action();\n if(stop)\n return;\n } \n }\n</code></pre>\n\n<p>This may or may not be better. It depends on the actual code. The actions list would represent an ordered set of transactional units of code - each unit must be completed, but the whole set can be broken apart and cancelled if necessary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T07:54:23.553", "Id": "1658", "Score": "2", "body": "The lambdas seem redundant since the called methods (appear to) have the same signature as the delegate. +1 because the rest of it looks good though :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T21:04:13.040", "Id": "907", "ParentId": "899", "Score": "8" } }, { "body": "<p>Looks like so long as you aren't calling more than these three methods, what you have is better for clarity's sake. And the cost of the conditionals is pretty cheap as far as compilation goes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T22:19:57.627", "Id": "913", "ParentId": "899", "Score": "0" } } ]
{ "AcceptedAnswerId": "907", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-21T15:57:50.980", "Id": "899", "Score": "11", "Tags": [ "c#" ], "Title": "Interrupt lengthy for loops" }
899
<pre><code>public static class StringHelpers { public static string CapitalizeEachWord(this string sentence) { CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; TextInfo textInfo = cultureInfo.TextInfo; if (String.IsNullOrEmpty(sentence)) { return String.Empty; } return textInfo.ToTitleCase(sentence); } public static string CapitalizeFirstWord(this string sentence) { if (String.IsNullOrEmpty(sentence)) { return String.Empty; } var words = sentence.Split(); StringBuilder resultBuilder = new StringBuilder(); var letters = words[0].ToCharArray(); List&lt;string&gt; lettersHolder = new List&lt;string&gt;(); lettersHolder.Add(letters[0].ToString().ToUpper()); for (int i = 1; i &lt; letters.Length; i++) { lettersHolder.Add(letters[i].ToString().ToLower()); } foreach (var letter in lettersHolder) { resultBuilder.Append(letter); } resultBuilder.Append(" "); for (int i = 1; i &lt; words.Length; i++) { resultBuilder.Append(words[i].ToLower()); resultBuilder.Append(" "); } return resultBuilder.ToString(); } } </code></pre> <p>The first method, is supposed to correctly capitalize each word in a sentence. I don't think there's much room for improvement in that one.</p> <p>The second method, seems a little confusing and even after I've written it and tested it, I cannot seem to fully put what it's doing into my buffer. That's a sign of code smell.</p> <p>If I <em>kinda</em> get it now, what will happen down the line when I have to change it or something. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T16:26:14.083", "Id": "38729", "Score": "0", "body": "`ToTitleCase()` won't *uncapitalize* words that are in all caps. You should call it on the `.ToLower()` version of the string." } ]
[ { "body": "<p>You're right, your second method is way too complicated. It also doesn't handle the case where the string starts with a space (in which case <code>words[0]</code> will be the empty string and <code>letters[0]</code> will be out of bounds). Since all your method seems to be doing is to capitalize the first letter of the string and lower case everything else, why not just do that?</p>\n\n<pre><code>public static string CapitalizeFirstWord(this string sentence)\n{\n if (String.IsNullOrEmpty(sentence))\n {\n return String.Empty;\n }\n\n String firstLetter = sentence.Substring(0,1);\n String rest = sentence.Substring(1);\n return firstLetter.ToUpper() + rest.ToLower();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T17:32:15.387", "Id": "1641", "Score": "0", "body": "Wow, why didn't I think of that! :D" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T17:12:10.640", "Id": "903", "ParentId": "900", "Score": "10" } }, { "body": "<p>I don't like how they will convert a null into an empty string. Seems like a good way to hide errors until they pop up later. I would do something like:</p>\n\n<pre><code>public static string CapitalizeEachWord(this string sentence)\n{\n if (String.IsNullOrEmpty(sentence))\n {\n return sentence;\n }\n\n CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;\n TextInfo textInfo = cultureInfo.TextInfo;\n\n return textInfo.ToTitleCase(sentence);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T08:21:07.357", "Id": "38707", "Score": "0", "body": "You could just do `if (String.IsNullOrEmpty(sentence)) { return sentence; }`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-12T10:05:59.947", "Id": "38711", "Score": "0", "body": "@MattDavey Good point. I've updated my answer to include that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-26T16:14:29.137", "Id": "1475", "ParentId": "900", "Score": "9" } }, { "body": "<p>How about adding a parameter of type <code>CultureInfo</code> to the first method?</p>\n\n<p>That way consumers of your method can decide which <code>CultureInfo</code> to use.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-25T10:20:44.870", "Id": "14003", "ParentId": "900", "Score": "3" } } ]
{ "AcceptedAnswerId": "903", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-21T16:25:14.313", "Id": "900", "Score": "8", "Tags": [ "c#", "strings", "extension-methods" ], "Title": "Capitalize words in sentence" }
900
<p>I wrote as an exercise in Test-Driven Development a piece of Python code that contains two functions:</p> <ul> <li><code>roman2dec(roman)</code>, that converts a roman number (string) into a decimal number (int)</li> <li><code>dec2roman(dec)</code>, that converts a decimal number (int) into a roman number (string)</li> </ul> <p>I'd like to read your comments on this code, if there are bad practices, if you would sign it for shipping or if you'd change anything.</p> <pre><code>import re import math # Regular expression used to validate and parse Roman numbers roman_re = re.compile("""^ ([M]{0,9}) # thousands ([DCM]*) # hundreds ([XLC]*) # tens ([IVX]*) # units $""", re.VERBOSE) # This array contains valid groups of digits and encodes their values. # The first row is for units, the second for tens and the third for # hundreds. For example, the sixth element of the tens row yields the # value 50, as the first is 0. d2r_table = [ ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'], ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'], ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM']] def roman2dec(roman): """Converts a roman number, encoded in a string, to a decimal number.""" roman = roman.upper() match = roman_re.match(roman) if not match: raise ValueError thousands, hundreds, tens, units = match.groups() result = 1000 * len(thousands) result += d2r_table[2].index(hundreds) * 100 result += d2r_table[1].index(tens) * 10 result += d2r_table[0].index(units) return result def dec2roman(dec): """Converts a positive decimal integer to a roman number.""" if dec == 0: return '' digit = 0 rem = dec result = '' # Length in digits of the number dec dec_len = int(math.ceil(math.log10(dec)) + 1) # Scan the number digit-by-digit, starting from the MSD (most-significant # digit) while dec_len &gt; 0: # Let's take the current digit factor = 10 ** (dec_len - 1) digit = rem / factor # And remove it from the number rem = rem - digit * factor if dec_len &gt;= 4: # Thousands result = result + digit * 'M' else: # Look in the look-up table result = result + d2r_table[dec_len - 1][digit] dec_len -= 1 return result </code></pre> <p><strong>EDIT</strong>: Here is the test suite for dec2roman:</p> <pre><code>class DecToRoman(unittest.TestCase): def testZeroIsEmpty(self): self.checkString(0, "") def testSingleDigits(self): self.checkString(1, "I") self.checkString(10, "X") self.checkString(50, "L") self.checkString(100, "C") self.checkString(500, "D") self.checkString(1000, "M") def testSimpleRepeats(self): self.checkString(1, "I") self.checkString(2, "II") self.checkString(3, "III") self.checkString(10, "X") self.checkString(20, "XX") self.checkString(30, "XXX") def testSubtraction(self): self.checkString(4, "IV") self.checkString(9, "IX") self.checkString(40, "XL") self.checkString(90, "XC") def testOther(self): self.checkString(89, "LXXXIX") self.checkString(145, "CXLV") self.checkString(691, "DCXCI") self.checkString(1983, "MCMLXXXIII") self.checkString(2412, "MMCDXII") self.checkString(3309, "MMMCCCIX") def checkString(self, decimal, expected_string): self.assertEqual(expected_string, new_dec2roman(decimal)) </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T10:03:21.253", "Id": "1661", "Score": "0", "body": "Make this into an extension module? http://www.ioccc.org/1987/wall.c (izajoke)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T10:56:05.373", "Id": "1663", "Score": "0", "body": "It would be easier to just type `import roman` ;) but it's just an exercise!" } ]
[ { "body": "<p>First of all you should document the fact that your code does not work with numbers above 9999.</p>\n\n<p>Then I think your code will become a bit simpler, if you add a fourth row to your <code>d2r_table</code> for the thousands. To avoid repetition you can use a list comprehension:</p>\n\n<pre><code>d2r_table = [\n ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'],\n ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'],\n ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'],\n ['M' * i for i in xrange(0,10) ]]\n</code></pre>\n\n<p>This allows you to not treat the thousands as a special case. So instead of:</p>\n\n<pre><code>thousands, hundreds, tens, units = match.groups()\nresult = 1000 * len(thousands)\nresult += d2r_table[2].index(hundreds) * 100\nresult += d2r_table[1].index(tens) * 10\nresult += d2r_table[0].index(units)\n</code></pre>\n\n<p>you can write:</p>\n\n<pre><code>thousands, hundreds, tens, units = match.groups()\nresult = d2r_table[3].index(thousands) * 1000\nresult += d2r_table[2].index(hundreds) * 100\nresult += d2r_table[1].index(tens) * 10\nresult += d2r_table[0].index(units)\nreturn result\n</code></pre>\n\n<p>Now you can easily notice the common pattern here: For each number from 0 to 3 you're taking the <code>i</code>th row of <code>d2r_table</code>, calling <code>index</code> on it with the <code>3-i</code>th element of <code>groups</code> as the argument, then multiplying it with <code>10**i</code> and lastly summing the results. You can abstract the common pattern like this if you want:</p>\n\n<pre><code>def value_for_group(i):\n group = match.groups[3-i]\n return d2r_table[i].index(group) * 10**i\n\nreturn sum(value_for_group(i) for i in xrange(0,4))\n</code></pre>\n\n<p>You can also replace the magic numbers 3 and 4, with something more meaningful:</p>\n\n<pre><code>num_rows = len(d2r_table)\n\ndef value_for_group(i):\n group = match.groups[num_rows - 1 - i]\n return d2r_table[i].index(group) * 10**i\n\nreturn sum(value_for_group(i) for i in xrange(0, num_rows))\n</code></pre>\n\n<p>This way your code will work without modification if you ever change <code>d2r_table</code> to account for extended roman numerals.</p>\n\n<hr>\n\n<p>In your <code>dec2roman</code> function you're using integer arithmetic to iterate over the digits of the number. I think it'd be easier and clearer to just convert the number to a string and iterate over the digits with a for loop. By reversing the <code>d2r_table</code>, you can use <code>zip</code> to iterate over the table and the digits in parallel without any index based loops. This way your <code>dec2roman</code> function would look like this:</p>\n\n<pre><code>result = ''\n# Make digits four digits long so it has the same number of digits\n# as d2r_table has rows, then convert each digit to an int\ndigits = [int(digit) for digit in \"%04d\" % dec]\n\nfor digit, d2r_row in zip(digits, reversed(d2r_table)):\n result += d2r_row[ digit ]\n\nreturn result\n</code></pre>\n\n<p>You can also use <code>join</code> with a generator expression instead of updating <code>result</code> imperatively:</p>\n\n<pre><code>digits = [int(digit) for digit in \"%04d\" % dec]\ntable = reversed(d2r_table)\nreturn ''.join( d2r_row[ digit ] for digit, d2r_row in zip(digits, table) )\n</code></pre>\n\n<p>Again you might also want to replace the 4 in <code>%04d</code> with <code>len(d2r_table)</code>, so your code will automatically adapt to a longer <code>d2r_table</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T18:49:04.853", "Id": "905", "ParentId": "902", "Score": "11" } } ]
{ "AcceptedAnswerId": "905", "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T16:54:18.110", "Id": "902", "Score": "10", "Tags": [ "python", "unit-testing", "converting" ], "Title": "Conversion from/to roman numbers" }
902
<p>I've gone back and forth a few times recently on my Perl coding style when it comes to module subroutines. If you have an object and you want to call the method <code>bar</code> with no arguments, then you can either do <code>$foo-&gt;bar()</code> or <code>$foo-&gt;bar</code>. At one point I started favoring the latter because I felt it cleaned up the code and made it more readable. However, sometimes I question whether it would be better to be fully explicit, especially considering the possibility that someone else will have to look at my code later — someone who almost certainly will <em>not</em> be an expert Perl programmer.</p> <p>For example, consider this block of code. For the method calls that require arguments (<code>get_tag_values</code> and <code>has_tag</code>), there is no question about the parentheses. But what about <code>next_feature</code> and <code>primary_tag</code>? Is the readability I gain from dropping the parens worth losing the explicit syntax? Is one better than the other for long term maintainability? Or is this simply a subjective judgment call?</p> <pre><code>while( my $feature = $gff3-&gt;next_feature ) { if($type eq "cds") { if( $feature-&gt;primary_tag eq "mRNA" ) { my($gene_id) = $feature-&gt;get_tag_values("Parent"); my($mRNA_id) = $feature-&gt;get_tag_values("ID"); next unless( $list eq '' or $genes_to_extract-&gt;{$gene_id} ); $subseq_locations-&gt;{ $feature-&gt;seq_id }-&gt;{ $mRNA_id } = Bio::Location::Split-&gt;new(); } elsif( $feature-&gt;primary_tag eq "CDS" ) { my($mRNA_id) = $feature-&gt;get_tag_values("Parent"); if( $subseq_locations-&gt;{ $feature-&gt;seq_id }-&gt;{ $mRNA_id } ) { $subseq_locations-&gt;{ $feature-&gt;seq_id }-&gt;{ $mRNA_id }-&gt;add_sub_Location( $feature-&gt;location ); } } } else { if( $feature-&gt;primary_tag eq $type ) { my $feat_id; if( $list ne '') { ($feat_id) = $feature-&gt;get_tag_values("ID") if($feature-&gt;has_tag("ID")); next unless( $feature-&gt;has_tag("ID") and $genes_to_extract-&gt;{$feat_id} ); } $subseq_locations-&gt;{ $feature-&gt;seq_id }-&gt;{ $feat_id } = Bio::Location::Split-&gt;new(); $subseq_locations-&gt;{ $feature-&gt;seq_id }-&gt;{ $feat_id }-&gt;add_sub_Location( $feature-&gt;location ); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-08T21:15:13.767", "Id": "23449", "Score": "0", "body": "It's a very good idea not to underestimate the importance of readability to others, most probably not so informed about the aim of the program and/or the language. **Especially** because most of the time, the other person is *future you*." } ]
[ { "body": "<p>Because either is technically acceptable, you are right that it is a style issue and simply a case of choosing a coding convention.</p>\n\n<p>However, I think that you have hit a very important point. So few other languages that use parentheses for functions allow a parameterless function call without parentheses that it can be very surprising for developers unfamiliar to perl.</p>\n\n<p>This point would sway me in favour of always using them and, indeed, I always do so out of habit because I use other languages a lot and it just comes naturally.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T22:08:47.990", "Id": "911", "ParentId": "906", "Score": "10" } }, { "body": "<p>To me, it is a no-brainer (for all it is a style question); retain the empty parentheses for the function call.</p>\n\n<p>The language I've used that allows (requires?) functions with no arguments to be called without parentheses was Pascal, and I always found such calls confusing - doubly so when invoked in the argument list to another function.</p>\n\n<p>Perl no longer requires the <code>&amp;</code> in front of functions as it once did. I think it is still worth distinguishing between a variable reference and a function call by providing the parentheses, at least when the call could be confused with a variable reference.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T22:56:10.133", "Id": "914", "ParentId": "906", "Score": "3" } }, { "body": "<p>I prefer to make a distinction on semantic level: there are no functions or methods, but instead there are properties and actions. Every property is an object (in real-world sense) and an action is something done <em>on</em> an object. A good mnemonic is probably to read <code>()</code> as <code>do it!</code>.</p>\n\n<p>Consider a variable:</p>\n\n<pre><code>$document\n</code></pre>\n\n<p>You know by the name it's an object, since it's a noun.</p>\n\n<pre><code>$document-&gt;author\n</code></pre>\n\n<p>Even though <code>author</code> is probably a function/method, an author is an object and a noun, so it's a property and thus no parens here.</p>\n\n<pre><code>$document-&gt;send()\n$document-&gt;author-&gt;write_book()\n</code></pre>\n\n<p>Again, <code>send</code> and <code>write_book</code> are functions/methods, but since those are actions (as designated by verbs), we write parens behind them. </p>\n\n<pre><code>$document-&gt;author_count\n$document-&gt;has_reviews\n</code></pre>\n\n<p>Again, a function/method, but a property of a document object, not an action, so no parens. A boolean value or an integer is strictly speaking not a real-world object, but it's more <em>like</em> an object than an action.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T10:04:35.347", "Id": "919", "ParentId": "906", "Score": "13" } }, { "body": "<p>It depends on the purpose. I prefer parenthesis for \"real\" methods, doing something. For properties with at most small getter/setter and simple checks I use the shorter version.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-27T15:05:20.373", "Id": "13053", "Score": "0", "body": "Setters have to have parenthesis. Only parameterless method calls can omit the parenthesis." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T21:15:15.607", "Id": "929", "ParentId": "906", "Score": "2" } }, { "body": "<p>I appreciate code that is more explicit, and having those\nparentheses would help me to use your code. I am learning more\nabout Perl, and any hints that help me to understand the\nmeaning of the letters, numbers, and symbols in a program are\nwelcome. Adding the extra notation will help beginners, and\nwon't stop experts. </p>\n\n<p>On the other hand, many Perl idioms can be\nefficient, but are terse and often obscure; their use can\ndelay or stop a beginner. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-08T17:35:50.500", "Id": "2312", "ParentId": "906", "Score": "2" } }, { "body": "<p>There really are very few things that can follow <code>-&gt;</code>, that I don't think of it as much of an issue.</p>\n\n<ul>\n<li><code>$obj-&gt;method</code></li>\n<li><code>$obj-&gt;method()</code></li>\n<li><code>$code-&gt;()</code></li>\n<li><code>$hash-&gt;{element}</code></li>\n<li><code>$array-&gt;[0]</code></li>\n<li><code>m&lt;-&gt;xmsg</code></li>\n<li><code>q&lt;-&gt;.'text'</code></li>\n</ul>\n\n<p>The only reasonably possible confusion that I can come up with is that someone might think that methods and subroutine calls are parsed the same.</p>\n\n<pre><code>$obj-&gt;method(subroutine());\n$obj-&gt;method subroutine(); # error\n\nsubroutine $obj-&gt;method;\nsubroutine($obj-&gt;method); # same as above (usually)\n</code></pre>\n\n<p>Most beginners start by looking at example code they find on the internet. Those examples may very well have both styles in them. So people wanting to learn Perl, will eventually need to know that they are equivalent. Probably sooner, rather than later.</p>\n\n<hr>\n\n<p>That being said, go ahead and standardize on one style or the other. Do it because you like that style, not because it might possibly one-day help people learn Perl.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-08T21:11:13.067", "Id": "23447", "Score": "0", "body": "\"Do it because you like that style, not because it might possibly one-day help people learn Perl.\" I'd rather say: Do it (and like it) because it can help people read your code. Most importantly, do not forget that the other person reading code *will be you*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-09T00:09:16.827", "Id": "23492", "Score": "0", "body": "@AloisMahdal If you like a style, it is probably because you find it easier to understand." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T23:33:15.333", "Id": "6930", "ParentId": "906", "Score": "3" } } ]
{ "AcceptedAnswerId": "911", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-21T20:25:26.630", "Id": "906", "Score": "9", "Tags": [ "perl", "bioinformatics" ], "Title": "Analyzing genetic tags" }
906
<p>I am creating a tab plugin. I want to know if there is a better way of doing this or if what I have is good. It works just fine, but there may be some shortcuts or a more optimized way of accomplishing this. I plan to replace the <code>startTab</code> variable with an options set, but I am not quite there yet.</p> <p><a href="http://www.mail-apps.com/tabplugin/TabPluginWorkFile.html" rel="nofollow">View the current updated version here</a></p> <p>Here is what I have so far:</p> <pre class="lang-html prettyprint-override"><code> &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;style&gt; ul.tabNavigation { list-style: none; margin: 0; padding: 0; } ul.tabNavigation li { display: inline; } ul.tabNavigation li a { text-decoration: none; color:#000; } .tabViews { width: 100%; border: #8db2e3 solid 1px; clear:both; height:18px; margin-top: -12px; background: url(css/tabs/images/tabs_Lower_Header_Background.png) repeat-x; } .tab { height: 25px; font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-size:14px; float:left; padding-left: 4px; position: relative; top: 1px } .tab .right { float:left; background:url(css/tabs/images/tab_Selected_Right.png) no-repeat; height:25px; width: 8px; } .tab .content { float:left; background:url(css/tabs/images/tab_Selected_Content.png) repeat-x; height:25px; text-align: center; padding-left: 5px; padding-right: 5px; padding-top: 4px; } .tab .left { float:left; background:url(css/tabs/images/tab_Selected_Left.png) no-repeat; height:25px; width: 6px; } .tabHover { height: 25px; font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-size:14px; float:left; padding-left: 4px; position: relative; top: 1px; cursor: pointer; } .h1 { float:left; height:25px; width: 14px; } .h2 { float:left; height:25px; text-align: center; padding-left: 7px; padding-right: 5px; padding-top: 4px; } .h3 { float:left; height:25px; width: 10px; } .tabHover:hover .h1 { background:url(css/tabs/images/tab_Hover_Right.png) no-repeat; } .tabHover:hover .h2 { background:url(css/tabs/images/tab_Hover_Content.png) repeat-x; } .tabHover:hover .h3 { background:url(css/tabs/images/tab_Hover_Left.png) no-repeat; } &lt;/style&gt; &lt;script type="text/javascript" src="javascript/jquery/jquery.js"&gt;&lt;/script&gt; &lt;script&gt; $.fn.tabs = function(startTab){ //Set currentIndex var currentIndex = 0; //Get all tab views var tabViews = $('.tabViews &gt; div',$(this)); //Current tab container var tabsContainer = $(this); //Hide all tabView containers tabViews.hide(); //Get all tabs var $tabs = $('ul &gt; li', tabsContainer); $tabs.each(function(index){ $('a',$(this)).click(function(){ changeTab(index); }); }); //call the changeTab method for the first time and selected the starting tab. changeTab(startTab); function changeTab(selectedIndex){ if(selectedIndex != currentIndex){ switchClass(selectedIndex); var previousSelectedTab = $('a',$tabs[currentIndex]); var currentSelectedTab = $('a',$tabs[selectedIndex]); $(previousSelectedTab.attr('href')).hide(); $(currentSelectedTab.attr('href')).show(); currentIndex = selectedIndex; } } //Method to switch the calles for selected and non selected tabs. function switchClass(selectedIndex){ $tabs.each(function(index){ //Get Child Left, Content, right divs var classBuilder = $('div &gt; div',$(this)) //Current Selected Tab if(index == selectedIndex){ var tabContainer = $('a &gt; div',$(this)) tabContainer.removeClass('tabHover'); tabContainer.addClass('tab'); $(classBuilder[0]).removeClass('h3'); $(classBuilder[0]).addClass('left'); $(classBuilder[1]).removeClass('h2'); $(classBuilder[1]).addClass('content'); $(classBuilder[2]).removeClass('h1'); $(classBuilder[2]).addClass('right'); } //Previously selected tab if(index == currentIndex){ var tabContainer = $('a &gt; div',$(this)) tabContainer.removeClass('tab'); tabContainer.addClass('tabHover'); $(classBuilder[0]).removeClass('left'); $(classBuilder[0]).addClass('h3'); $(classBuilder[1]).removeClass('content'); $(classBuilder[1]).addClass('h2'); $(classBuilder[2]).removeClass('right'); $(classBuilder[2]).addClass('h1'); } }); } } $(function() { $('#rfiTabs').tabs(0); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="rfiTabs"&gt; &lt;ul class="tabNavigation"&gt; &lt;li&gt;&lt;a href="#rfiBasic"&gt; &lt;div class="tab"&gt; &lt;div class="left"&gt;&lt;/div&gt; &lt;div class="content"&gt;Basic&lt;/div&gt; &lt;div class="right"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#rfiHome"&gt; &lt;div class="tabHover"&gt; &lt;div style="" class="h3"&gt;&lt;/div&gt; &lt;div style="" class="h2"&gt;Home&lt;/div&gt; &lt;div class="h1"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="tabViews" style=""&gt; &lt;div id="rfiBasic"&gt;Test&lt;/div&gt; &lt;div id="rfiHome"&gt;test this&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I realized I can optimize the left, content, and center part of the tabs by updating the CSS and jQuery for the hover section:</p> <pre class="lang-html prettyprint-override"><code>.tabHover .right { float:left; height:25px; width: 14px; } .tabHover .content { float:left; height:25px; text-align: center; padding-left: 7px; padding-right: 5px; padding-top: 4px; } .tabHover .left { float:left; height:25px; width: 10px; } .tabHover:hover .right { background:url(css/tabs/images/tab_Hover_Right.png) no-repeat; } .tabHover:hover .content { background:url(css/tabs/images/tab_Hover_Content.png) repeat-x; } .tabHover:hover .left { background:url(css/tabs/images/tab_Hover_Left.png) no-repeat; } function switchClass(selectedIndex){ $tabs.each(function(index){ //Get Child Lef, Content, right divs var classBuilder = $('div &gt; div',$(this)) if(index == selectedIndex){ var tabContainer = $('a &gt; div',$(this)) tabContainer.removeClass('tabHover'); tabContainer.addClass('tab'); //$(classBuilder[0]).removeClass('h3'); // $(classBuilder[0]).addClass('left'); // $(classBuilder[1]).removeClass('h2'); // $(classBuilder[1]).addClass('content'); // $(classBuilder[2]).removeClass('h1'); // $(classBuilder[2]).addClass('right'); } if(index == currentIndex){ var tabContainer = $('a &gt; div',$(this)) tabContainer.removeClass('tab'); tabContainer.addClass('tabHover'); //$(classBuilder[0]).removeClass('left'); // $(classBuilder[0]).addClass('h3'); // $(classBuilder[1]).removeClass('content'); // $(classBuilder[1]).addClass('h2'); // $(classBuilder[2]).removeClass('right'); // $(classBuilder[2]).addClass('h1'); } }); } </code></pre>
[]
[ { "body": "<p>You could remove tab navigation from html and create it dynamically in plugin so the html will look like this:</p>\n\n<pre><code>&lt;div id=\"rfiTabs\"&gt;\n &lt;div class=\"tabViews\" style=\"\"&gt;\n &lt;div id=\"rfiBasic\"&gt;Test&lt;/div&gt;\n &lt;div id=\"rfiHome\"&gt;test this&lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>you don't need to call</p>\n\n<pre><code>var tabsContainer = $(this);\n</code></pre>\n\n<p>this is already jQuery object</p>\n\n<p>inside switchClass function you call $(this) 3 times you can call it once and stor the value</p>\n\n<pre><code>var $this = $(this);\n</code></pre>\n\n<p>you get element from jQuery object and then wrap it again.</p>\n\n<pre><code>$(classBuilder[0]).removeClass('h3');\n</code></pre>\n\n<p>you could use eq jquery method</p>\n\n<pre><code>classBuilder.eq(0).removeClass('h3');\n</code></pre>\n\n<p>instead </p>\n\n<pre><code>if(index == selectedIndex){\n\n} \nif(index == currentIndex){\n\n}\n</code></pre>\n\n<p>use</p>\n\n<pre><code>if(index == selectedIndex){\n\n} else if(index == currentIndex){\n\n}\n</code></pre>\n\n<p>you don't need to check if <code>index == currentIndex</code> if <code>index == selectedIndex</code></p>\n\n<p>this code is repeaded twice but with different class names create a function for it (it looks almost the same — if you see something like this always create new function)</p>\n\n<pre><code>$(classBuilder[0]).removeClass('h3');\n$(classBuilder[0]).addClass('left');\n$(classBuilder[1]).removeClass('h2');\n$(classBuilder[1]).addClass('content');\n$(classBuilder[2]).removeClass('h1');\n$(classBuilder[2]).addClass('right');\n</code></pre>\n\n<p>and you can chain jquery methods:</p>\n\n<pre><code>classBuilder.eq(0).removeClass('h3').addClass('left');\nclassBuilder.eq(1).removeClass('h2').addClass('content');\nclassBuilder.eq(2).removeClass('h1').addClass('right');\n</code></pre>\n\n<p>you don't need to iterate over $tabs</p>\n\n<pre><code>function switchClass(selectedIndex){ \n $tabs.eq(selectedIndex) \n</code></pre>\n\n<p>and I think that this:</p>\n\n<pre><code>var classBuilder = $tabs.eq(selectedIndex).find('div &gt; div');\n</code></pre>\n\n<p>will be the same as</p>\n\n<pre><code>var classBuilder = $('div &gt; div',$(this))\n</code></pre>\n\n<p>and this:</p>\n\n<pre><code>if(index == currentIndex){\n var tabContainer = $('a &gt; div',$(this))\n tabContainer.removeClass('tab');\n tabContainer.addClass('tabHover');\n</code></pre>\n\n<p>is the same as </p>\n\n<p>$tabs.eq(currentIndex).find('a > div').removeClass('tab').addClass('tabHover');</p>\n\n<p>and at the end of the script you should return <code>this</code> so it could be chained </p>\n\n<pre><code>$('#rfiTabs').tabs(0).css('background-color', 'red');\n</code></pre>\n\n<p>you can also do this:</p>\n\n<p>return this.each(function() {\n var $this = $(this);\n //and create your tabs here\n });</p>\n\n<p>so if you call it </p>\n\n<pre><code>$('.myalltabs').tabs(0);\n</code></pre>\n\n<p>it will create tabs for every element that have <code>.myalltabs</code> class</p>\n\n<p><strong>Update</strong></p>\n\n<p>if you your jquery object have multiple elements (But this is Something Completely Different)</p>\n\n<pre><code>$.fn.tabs = function(n) {\n\n var = tabcontainer = $('&lt;div/&gt;').attr('class', 'mainTabClass')\n .appendTo($('body'));\n\n var nav = $('&lt;ul&gt;').addClass('navigation').appendTo(tabcontainer);\n this.each(function() {\n var $this = $(this);\n var id = $this.attr('id');\n $('&lt;li&gt;').append('&lt;a&gt;').appendTo(nav).children().\n attr('href', '#' + id).html($this.attr('name'));\n }).addClass('tabContent').detach().appendTo(tabcontainer);\n\n nav.find('li a').click(function() {\n tabcontainer.find('tabContent').removeClass('selected');\n tabcontainer.find($(this).attr('href')).addClass('selected');\n }).eq(n).addClass('selected');\n};\n</code></pre>\n\n<p>in this case you need only</p>\n\n<pre><code>.selected {\n display: block;\n}\n.mainTabClass .tabContent {\n display: none;\n}\n\n ....\n &lt;div id=\"home\" name=\"Home Page\"&gt;this is home&lt;/div&gt;\n ....\n &lt;div id=\"about\" name=\"About me\"&gt;this is about&lt;/div&gt;\n ....\n</code></pre>\n\n<p>name attribute in case you won't different name than id.</p>\n\n<pre><code>$('#home, #about').tabs(1);\n</code></pre>\n\n<p>and you will have</p>\n\n<pre><code>&lt;div class=\"mainTabClass\"&gt;\n &lt;ul class=\"navigation\"&gt;\n &lt;li&gt;&lt;a href=\"#home\"&gt;Home Page&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#about\"&gt;About me&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;div class=\"tabContent\" id=\"home\"&gt;this is home&lt;/div&gt;\n &lt;div class=\"tabContent selected\" id=\"about\"&gt;this is about&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>I don't know why you have repeated <code>left</code>, <code>right</code> and <code>content</code> for every tab, if you need to use those - create one instance and change it on click (in case you will have 100 tabs you will have 3 DOM elements instead of 300)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T22:23:58.197", "Id": "1653", "Score": "0", "body": "Do you think I should pass a tab array into the plugin? So instead of creating the tabs in a list format just create them inside the Jquery?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T22:35:59.220", "Id": "1655", "Score": "0", "body": "You can created it from jquery objects - $('ul li').tabs(0) this will create tabs from all li elements instead of creating multiply tabs from children inside li element, in this case you can use something like this $('div.foo, div.bar, div#baz').tabs(0) and it will create tabs from whatever are in `this` inside the plugin, so panels from your tabs can be in different palaces in the DOM." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T03:35:16.420", "Id": "1656", "Score": "0", "body": "I don't quite understand how my left,conent,right div structure would fit into your suggestion. Would you mind showing me an example of what you are saying?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T10:47:15.247", "Id": "1662", "Score": "0", "body": "you create tabNavigation and left,content,right divs dynamically and call `this.hide().detach().appendTo($('<div>').addClass('tabViews').appendTo(dynamicly_created_rfiTabs));`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T10:59:16.680", "Id": "1664", "Score": "0", "body": "or `this.hide().detach().wrapAll('<div class=\"tabViews\"/>'). parent().appendTo(dynamicly_created_rfiTabs);` if you create a plugin you should minimize the amount of code that is needed to use it." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T11:34:34.657", "Id": "1666", "Score": "0", "body": "Agreed. Thanks!!!! I think I will still add, into the options, a way to pass in an array of tabs (Name, selected, tab view to display onclick). Thoughts?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T11:52:39.343", "Id": "1667", "Score": "0", "body": "\"I don't know why you have repeated left, right and content for every tab\"...I used these divs for the graphics on the tab. This is so the content area will be dynamic. If anyone has a better suggestion, please let me know." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T12:30:37.843", "Id": "1669", "Score": "0", "body": "if you want to set a graphic in the tab you could use background-image for link you can also use sprites (image for all tabs in two states and changing background-position css attribute on hover), and if left and right are images for arrows and content is image for button - then put those one this and on hover change the class for the content `nav_content.addClass('selected');` and in css `.nav .selected { background-position: <position in sprite for selected tab image> }` you can read about sprites here http://goo.gl/ofScM and here http://css-tricks.com/css-sprites/" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T17:38:19.477", "Id": "1677", "Score": "0", "body": "Thanks a ton, jcubic. I have avoided using CSS sprites for far too long. I guess it is time to go that toute! Thanks again for all your comments!" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-21T21:47:29.087", "Id": "910", "ParentId": "908", "Score": "6" } } ]
{ "AcceptedAnswerId": "910", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-21T20:42:20.877", "Id": "908", "Score": "5", "Tags": [ "javascript", "optimization", "jquery", "css", "plugin" ], "Title": "Creating a tab plugin" }
908
<p>Here is a snippet of code that generates a thumbnail from a given file. It works well, but is much slower than desired. Without using an external library (which I'm trying to avoid for learning purposes), is there anything that can be done to increase the speed?</p> <p>I know the fastest way would be to retrieve the stored thumbnail. I've looked into reading for any EXIF thumbnail data by parsing out the embedded information, but gave up since it was taking me a lot of effort with no finished end result. Again, I'd prefer not to rely on a library specifically because I want to learn more about the format itself.</p> <p>I know many will state right away I shouldn't be messing with EXIF data unless I use an external library, so as an alternative, what can be done specifically with this snippet to make things (significantly) faster?</p> <p>Feel free to give me feedback about my coding style as well, except for the use of JavaDoc comments.</p> <pre><code>class ThumbIcon extends ImageIcon implements Runnable { public int thumbWidth; public int thumbHeight; Image image; Graphics2D g2dBuffer; ThumbButton parent; BufferedImage scaledImage; public ThumbIcon(final ThumbButton theParent) { super(); parent = theParent; } // End ThumbIcon(ThumbButton, String) public void run() { image = Toolkit.getDefaultToolkit().getImage(filePath); final MediaTracker tracker = new MediaTracker(new Container()); tracker.addImage(image, 0); try { tracker.waitForID(0); } catch (InterruptedException e) { System.out.println("Interrupted getting thumb"); } // End try // Get dimensions from the now-loaded image final int width = image.getWidth(null); final int height = image.getHeight(null); // Use the width to determine if the image is legitimate and loaded // Limit importable images to &lt;54MiB or &lt;51.5MP (9000px x 6000px) if ((width &gt; 0) &amp;&amp; (width * height &lt; 54000000)) { // This is an actual image, so display on screen // Set the thumbnail size depending on image orientation // We are assuming a square thumbnail if (width &gt; height) { // Landscape thumbWidth = THUMBS_SIZE; thumbHeight = (int)((double)height / (double)width * THUMBS_SIZE); } else { // Portrait thumbWidth = (int)((double)width / (double)height * THUMBS_SIZE); thumbHeight = THUMBS_SIZE; } // End if scaledImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); // Simultaneously load image into g2d buffer and scale to desired size g2dBuffer = scaledImage.createGraphics(); g2dBuffer.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); //g2dBuffer.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // RenderingHints.VALUE_ANTIALIAS_ON); // Size image (no matter initial size) to destWidth x destHeight g2dBuffer.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); ... // Create the thumbnail setImage(Toolkit.getDefaultToolkit().createImage(scaledImage.getSource())); scaledImage.flush(); image.flush(); //g2dBuffer.finalize(); g2dBuffer = null; } else { ... } // End if } // End run() ... } // End ThumbIcon </code></pre> <p>I shaved off some time by disabling anti-aliasing. It looks nasty, but it serves its purpose.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T13:07:59.917", "Id": "1672", "Score": "0", "body": "Have you tried `image.getScaledInstance(thumbWidth, thumbHeight, Image.SCALE_FAST);`?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T18:41:20.397", "Id": "1713", "Score": "0", "body": "If I recall correctly, that's what I started out with. I switched away from it because this version was MUCH faster." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-14T07:08:11.240", "Id": "2233", "Score": "0", "body": "are the images all jpeg?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-14T13:13:26.677", "Id": "2238", "Score": "0", "body": "They aren't necessarily, but in general, they are. I wouldn't be too concerned with thumbnail generation of non-JPG images, as the program would *primarily* dictate the use of JPG, but not require it." } ]
[ { "body": "<p>You probably reached the maximum speed you can achieve with the API you are using. You could try the following extra hints, just in case they’re not the default values:</p>\n\n<pre><code>g2dBuffer.setRenderingHint(RenderingHints.KEY_RENDERING,\n RenderingHints.VALUE_RENDER_SPEED);\ng2dBuffer.setRenderingHint(RenderingHints.KEY_ANTIALIASING, \n RenderingHints.VALUE_ANTIALIAS_OFF);\ng2dBuffer.setRenderingHint(RenderingHints.KEY_DITHERING, \n RenderingHints.VALUE_DITHER_DISABLE);\ng2dBuffer.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, \n RenderingHints.VALUE_COLOR_RENDER_SPEED);\n</code></pre>\n\n<p>Also, try replacing <code>TYPE_INT_RGB</code> with <code>TYPE_INT_BGR</code> or <code>TYPE_3BYTE_BGR</code> to experiment with how efficiently the Java graphics libraries do their byte packing. But it’s pretty unlikely you’ll see a noticeable difference.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-13T16:29:48.993", "Id": "2224", "Score": "0", "body": "Hmm, great suggestions. I'll give 'em a go and do some benchmarks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-13T02:06:03.403", "Id": "1278", "ParentId": "912", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-21T22:11:42.180", "Id": "912", "Score": "6", "Tags": [ "java", "optimization", "image" ], "Title": "Optimized thumbnail generation" }
912
<p>I am using the JSON output of the MediaWiki API documented <a href="https://www.mediawiki.org/wiki/API:Main_page" rel="nofollow noreferrer">here</a> and <a href="https://en.wikipedia.org/w/api.php" rel="nofollow noreferrer">here</a>, and I have found that for Boolean values, it often returns an empty string if true and omits it if false. Thus, I want to "rationalize" the response.</p> <p>(Historical context: This was before a <a href="https://www.mediawiki.org/wiki/API:JSON_version_2" rel="nofollow noreferrer">new output format</a> was added that uses native JSON <code>true</code> and <code>false</code>.)</p> <p>My current code to do so (written some months ago) is located in a giant anonymous function:</p> <pre><code>user = query.users[0]; invalid = typeof user.invalid != "undefined"; missing = typeof user.missing != "undefined"; groups = (typeof user.groups == "object") ? user.groups : []; editcount = (typeof user.editcount == "number") ? user.editcount : null; registration = (typeof user.registration == "string") ? UserinfoJsParseDate(user.registration) : null; blocked = typeof user.blockedby != "undefined"; gender = (typeof user.gender == "string") ? user.gender : null; lastEdited = (typeof query.usercontribs[0] == "object") &amp;&amp; (typeof query.usercontribs[0].timestamp == "string") ? UserinfoJsParseDate(query.usercontribs[0].timestamp) : null; </code></pre> <p>I am trying to clean this up, breaking the script's main components into separate functions:</p> <pre><code>/** * Extract relevant information from the server's response. * @param data The server's response to the AJAX request * @return An object containing the user's information */ function processResponse( data ) { var query = data.query, info = {}; if ( query &amp;&amp; query.users &amp;&amp; query.users[0] ) { var user = query.users[0]; info.invalid = 'invalid' in user; info.missing = 'missing' in user; info.groups = user.groups || []; info.editcount = ( 'editcount' in user ) ? user.editcount : null; info.registration = ( 'registration' in user ) ? parseDate( user.registration ) : null; info.blocked = 'blockexpiry' in user; info.gender = ( 'gender' in user &amp;&amp; user.gender != 'unknown' ) ? user.gender : null; info.lastEdited = null; if ( query.usercontribs &amp;&amp; query.usercontribs[0] ) { var contribs = query.usercontribs[0]; if ( contribs.timestamp ) { user.lastEdited = parseDate( contribs.timestamp ); } } } return info; } </code></pre> <p>Is this better, or have I just written more messy code?</p>
[]
[ { "body": "<p>It is certainly better. You can improve it further:</p>\n\n<ol>\n<li>Use early exits to reduce arrow code.</li>\n<li>Use a JSON initializer for the result.</li>\n<li>Prefix boolean names with 'is'.</li>\n<li>Fix the 'user.lastEdited' bug.</li>\n</ol>\n\n<p>.</p>\n\n<pre><code>function processResponse(data) {\n if (!data.query || !data.query.users || !data.query.users[0]) return {};\n\n var user = data.query.users[0];\n\n return {\n isInvalid: 'invalid' in user,\n isMissing: 'missing' in user,\n groups: user.groups || [],\n editCount: ('editcount' in user) ? user.editcount : null,\n registration: ('registration' in user) ? parseDate(user.registration) : null,\n isBlocked: 'blockexpiry' in user,\n gender: ('gender' in user &amp;&amp; user.gender != 'unknown') ? user.gender : null,\n lastEdited: (data.query.usercontrib\n &amp;&amp; data.query.usercontribs[0] \n &amp;&amp; data.query.usercontribs[0].timestamp)\n ? parseDate(data.query.usercontribs[0].timestamp) : null\n };\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T09:54:04.453", "Id": "1035", "ParentId": "916", "Score": "5" } } ]
{ "AcceptedAnswerId": "1035", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-22T04:03:59.627", "Id": "916", "Score": "8", "Tags": [ "javascript", "json" ], "Title": "Processing an API's JSON response" }
916
<p>I have been generating English-language text from some machine-readable data, but now I want internationalization of my script to be relatively easy. The challenge is that some data might be missing and thus should be omitted from the output, possibly precluding any approach involving just "plugging in" numbers.</p> <p>Currently, I have functions like these, the output concatenated together in the main program:</p> <pre><code>function UserinfoJsFormatQty(qty, singular, plural) { return String(qty).replace(/\d{1,3}(?=(\d{3})+(?!\d))/g, "$&amp;,") + "\u00a0" + (qty == 1 ? singular : plural); } function UserinfoJsFormatDateRel(old) { // The code below requires the computer's clock to be set correctly. var age = new Date().getTime() - old.getTime(); var ageNumber, ageRemainder, ageWords; if(age &lt; 60000) { // less than one minute old ageNumber = Math.floor(age / 1000); ageWords = UserinfoJsFormatQty(ageNumber, "second", "seconds"); } else if(age &lt; 3600000) { // less than one hour old ageNumber = Math.floor(age / 60000); ageWords = UserinfoJsFormatQty(ageNumber, "minute", "minutes"); } else if(age &lt; 86400000) { // less than one day old ageNumber = Math.floor(age / 3600000); ageWords = UserinfoJsFormatQty(ageNumber, "hour", "hours"); ageRemainder = Math.floor((age - ageNumber * 3600000) / 60000); } else if(age &lt; 604800000) { // less than one week old ageNumber = Math.floor(age / 86400000); ageWords = UserinfoJsFormatQty(ageNumber, "day", "days"); } // ... return ageWords; } </code></pre> <p>It is supposed to generate output like:</p> <blockquote> <p>A reviewer and rollbacker, 2 years 9 months old, with 8,624 edits. Last edited 7 hours ago.</p> </blockquote> <p>The age, edit count, date of last edit, or all of them could be missing. How could I improve my current design without resorting to a tabular display format? (All the information needs to nicely fit into a single status line.)</p>
[]
[ { "body": "<p>I see a couple of potential issues with regards to internationalization:</p>\n\n<ul>\n<li><p>pluralization is more complex than <code>(qty == 1 ? singular : plural)</code>. What about the value 0? Also in some languages, <a href=\"http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html\" rel=\"nofollow\">different plural forms are in use depending on the number</a>.</p></li>\n<li><p>numbers should be formatted according to language, <a href=\"http://en.wikipedia.org/wiki/Decimal_mark\" rel=\"nofollow\">using appropriate separators</a></p></li>\n<li><p>concatenation (that you mention is done in main program) must be avoided because the order of words and phrases will often vary in translations in different languages</p></li>\n</ul>\n\n<p>I would advise to :</p>\n\n<ul>\n<li><p>localize translations using named parameters to be replaced: this solves the ordering issue, and avoids concatenation.</p></li>\n<li><p>format values, for number formatting and pluralization, using a separate function localized for each language</p></li>\n<li><p>replace parameters with formatted values in parameterized translations using a template engine: this should keep some potentially buggy regular expressions out of your code :)</p></li>\n</ul>\n\n<p>You may be interested in having a look at:</p>\n\n<ul>\n<li><a href=\"http://24ways.org/2007/javascript-internationalisation\" rel=\"nofollow\">JavaScript Internationalisation</a>, a post by Matthew Somerville on 24 Ways</li>\n<li><a href=\"https://github.com/jquery/jquery-global\" rel=\"nofollow\">jQuery-global</a>, \"a jQuery plugin for the globalization of string, date, and number formatting and parsing\"</li>\n</ul>\n\n<p>and last but not least, the i18n API part of the Scalable JavaScript Application framework, which I designed for Legal-Box :)</p>\n\n<ul>\n<li><a href=\"https://github.com/eric-brechemier/lb_js_scalableApp\" rel=\"nofollow\">eric-brechemier/lb_js_scalableApp</a>, the project home page on GitHub</li>\n<li><a href=\"https://github.com/eric-brechemier/lb_js_scalableApp/blob/master/src/lb.core.Sandbox.js\" rel=\"nofollow\">lb.core.Sandbox.js</a>, check the i18n part of the API, methods starting with \"i18n.\"</li>\n</ul>\n\n<p>I may be able to provide more practical suggestions if you show more of your code, especially at the \"top\", part of the main program.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-26T14:37:35.740", "Id": "1013", "ParentId": "917", "Score": "5" } } ]
{ "AcceptedAnswerId": "1013", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-22T04:17:43.040", "Id": "917", "Score": "8", "Tags": [ "javascript" ], "Title": "Generating readable text in a human language from machine-readable data" }
917
<p>The following extension method is being used in our code base:</p> <pre><code>public static bool ToBool(this object src) { return src != null &amp;&amp; ((string) src).ToBool(false); } </code></pre> <p>It leverages off another extension method:</p> <pre><code>public static bool ToBool(this string src, bool defaultValue) { if (src.IsEmpty()) return defaultValue; if (src.IsNumeric()) return src.ToInt() != 0; var ret = false; if (bool.TryParse(src, out ret)) return ret; return defaultValue; } </code></pre> <p>(where the ToInt and all the Is* methods are wrappers around the appropriate objects IsNullEmpty / Parse method)</p> <p>This does not 'feel' right but I cannot explain it to the author. Besides for the obvious problem of passing an object that cannot be cast to a string what other reasons are there to justify this as bad code?</p> <p>Are there any other concrete reasons why this code may be good or bad?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T11:04:19.297", "Id": "1665", "Score": "1", "body": "This does seem rather strange and unconventional - so you're basically treating null, 0, \"\", and \"0\" as false, and all other numbers as true. What is the reasoning behind this? And how is it being used in the rest of the code?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T12:32:28.250", "Id": "1670", "Score": "0", "body": "I think the only reason this code exists is to try and create a more dynamic type system (as mentioned by @martin) or 'fluent' interface. In an attempt to make prettier code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-27T16:44:07.267", "Id": "8510", "Score": "0", "body": "In this case, prettier == confusing. Don't try to turn C# into Ruby, it just won't work well." } ]
[ { "body": "<p>I'd criticize:</p>\n\n<ul>\n<li>Extension methods on \"object\" should be avoided because of the broad scope, except for special cases (which such a \"ToBool\" method is not one). It also feels like an overuse of extension methods.</li>\n<li>The first one takes an \"object\", but really wants a string, and will blow up with an <code>InvalidCastException</code> at runtime.</li>\n<li>The second one does not check for <code>null</code> (which wouldn't be a problem in itself, but having overloads for default values with differing behavior is bad).</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T11:11:06.650", "Id": "921", "ParentId": "920", "Score": "7" } }, { "body": "<p>Creating and extension method for <code>object</code> that will throw an exception if the actual object isn't a <code>string</code> is asking for trouble.</p>\n\n<p>Also, the general approach looks very much like an attempt to create a dynamic type system where you can use any type and call <code>ToXxx</code> to convert to whatever type you need using \"sensible\" rules. Is that really what you want in a strongly typed language like C#?</p>\n\n<p>Do you have any guarantees that <code>ToBool</code> will not throw exceptions even if it is passed a string? What if <code>IsNumeric</code> returns true but <code>ToInt</code> throws an exception? None of this code seems to take culture settings into account even though it parses strings to number and may break unexpectedly if run in a different culture.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T12:37:28.607", "Id": "1671", "Score": "0", "body": "All of your points are 100% valid, thanks for the feedback." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-22T11:11:58.723", "Id": "922", "ParentId": "920", "Score": "6" } } ]
{ "AcceptedAnswerId": "921", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-22T10:50:10.730", "Id": "920", "Score": "8", "Tags": [ "c#", "extension-methods" ], "Title": "Converting objects to type Bool" }
920
<p>I am implementing the command pattern in a project that I am working on and I have an interface, <code>ICommandFactory</code> that all of my commands are implementing. </p> <p>When I run the application I want to dynamically gather all classes in the current assembly that implement that interface, thus producing a list of all possible commands.</p> <p>So I came up with the method below. This was the first thing that I could get to work. Is there a better way to do this?</p> <pre><code> private static IEnumerable&lt;ICommandFactory&gt; GetAvailableCommands() { var interfaceType = typeof (ICommandFactory); var implementors = Assembly.GetExecutingAssembly().GetTypes().Where( i =&gt; interfaceType.IsAssignableFrom(i) &amp;&amp; i != interfaceType); var commands = new List&lt;ICommandFactory&gt;(); foreach(var implementor in implementors) { var ctor = implementor.GetConstructor(Type.EmptyTypes); if (ctor == null) continue; var instance = ctor.Invoke(null) as ICommandFactory; if (instance == null) continue; commands.Add(instance); } return commands; } </code></pre>
[]
[ { "body": "<p>Your code seems to do what it is supposed to do.</p>\n\n<p>I'm worried about the fact that you're hinting at the possibility of having multiple <code>CommandFactory</code> classes. Why would you want that? (I'm just asking. You might have very valid reasons.)</p>\n\n<p>I'm also wondering if you actually meant <em>Factory</em>, since the variable name you use for the list inside your method is just <code>commands</code>, which makes me believe that you are looking for just that: types that implement <code>ICommand</code>, not <code>ICommandFactory</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T01:55:34.593", "Id": "1689", "Score": "0", "body": "Lette - You are right, Factory is a bad naming convention. These classes implement both the ICommandFactory and ICommand interface. Where the ICommandFactory has methods that are used to build a ICommand that is implemented. Probably renaming to something like, ICommandBuilder might be better. I really appreciate you reviewing this method for me." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T22:08:51.453", "Id": "933", "ParentId": "928", "Score": "2" } }, { "body": "<p>You can use the Activator to create an instance:</p>\n\n<pre><code>commands.Add( Activator.CreateInstance(implementor) as ICommandFactory );\n</code></pre>\n\n<p>or even a fancy <a href=\"http://bloggingabout.net/blogs/vagif/archive/2010/04/02/don-t-use-activator-createinstance-or-constructorinfo-invoke-use-compiled-lambda-expressions.aspx\" rel=\"nofollow\">Compiled Lamdba Expression</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T17:04:30.213", "Id": "1705", "Score": "0", "body": "Thanks for the feedback. I will look into the Compliled Lambada Expressions as they are intriguing." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T17:24:55.787", "Id": "1799", "Score": "0", "body": "You don’t seriously think that using a compiled lambda expression would be better in this case? It is harder to read, less maintainable, and probably also slower. (The graph in your link only shows the invocation time, not the construction time, but in this example it is invoked only once...)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T02:16:38.390", "Id": "939", "ParentId": "928", "Score": "0" } }, { "body": "<p>I only have a few minor comments about your code:</p>\n\n<ol>\n<li><p>This code:</p>\n\n<pre><code>var ctor = implementor.GetConstructor(Type.EmptyTypes);\nif (ctor == null) continue;\n</code></pre>\n\n<p>has the potential to mask a bug. Imagine you add a constructor to one of your command-factory types and accidentally forget that this implicitly removes the default constructor. This code will then silently swallow this mistake and simply not list that particular command factory. It would be preferable to throw in this case so that you notice it immediately. Even better, of course, would be to <a href=\"http://timwi.blogspot.com/2010/03/ensure-code-quality-using-post-build.html\" rel=\"nofollow\">use a post-build event to turn this error into a compile-time check</a> so that you can’t even run the program when it is invalid.</p></li>\n<li><p>This code:</p>\n\n<pre><code>var instance = ctor.Invoke(null) as ICommandFactory;\nif (instance == null) continue;\n</code></pre>\n\n<p>has exactly the same problem, but the consequences are much more subtle. The <code>if (instance == null)</code> condition <em>should</em> never fire because the code was written so that the instance cannot be of any other type. Imagine you have a bug in that code. This code swallows this bug and you won’t notice it directly. You will only notice some subtle/weird effects that occur much later, and it will be a pain to trace it back to this code here. You could make it throw like above, but personally I think you should change this to <code>var instance = (ICommandFactory) ctor.Invoke(null);</code> so that it will automatically throw if it’s not of the right type.</p></li>\n<li><p>Your code does not allow for a class that implements <code>ICommandFactory</code> but is not intended to appear in your UI. If you are sure that you don’t want that to be possible, then your code is fine. Otherwise, I would declare a custom attribute — either one that allows you to explicitly <em>exclude</em> an <code>ICommandFactory</code> from appearing in the UI, or one that is required on all the <code>ICommandFactory</code> types to be <em>included</em>.</p></li>\n<li><p>Very very minor nitpick:</p>\n\n<pre><code>i =&gt; interfaceType.IsAssignableFrom(i) &amp;&amp; i != interfaceType\n</code></pre>\n\n<p>You should perform the simpler check first:</p>\n\n<pre><code>i =&gt; i != interfaceType &amp;&amp; interfaceType.IsAssignableFrom(i)\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T12:54:54.220", "Id": "1788", "Score": "0", "body": "Thanks @Timwi for your comments. I had not even realized that I would be swallowing the mistakes in points 1 & 2 above." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T17:58:17.063", "Id": "954", "ParentId": "928", "Score": "5" } } ]
{ "AcceptedAnswerId": "933", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T20:57:16.000", "Id": "928", "Score": "6", "Tags": [ "c#", "design-patterns" ], "Title": "IEnumerable of classes that implement a given interface at runtime" }
928
<p>I am stuck with this horrible object model coming back from a 3rd party product. It's six levels of objects deep, and I have to loop through the collection in each level, to get the values I need, in order to produce a small object model that I actually require.</p> <p>The code ends up looking like this (with variable and type names changed). How can I clean up this mess when I can't modify the structure of the <code>rootObject</code>?</p> <p>(This is .NET 3.5.)</p> <pre><code>var levelOneEnumerator = rootObject.GetEnumerator(); while (levelOneEnumerator.MoveNext()) { var levelOneItem = levelOneEnumerator.Current as Foo_LevelOneItem; if (levelOneItem == null) continue; var levelTwoItemsEnumerator = levelOneItem.LevelTwoItems.GetEnumerator(); while (levelTwoItemsEnumerator.MoveNext()) { var LevelTwoItemsItem = levelTwoItemsEnumerator.Current as Foo_LevelTwoItem; if (LevelTwoItemsItem == null) continue; var foobars = new List&lt;FooBar&gt;(); var levelThreeItemsEnumerator = LevelTwoItemsItem.LevelThreeItems.GetEnumerator(); while (levelThreeItemsEnumerator.MoveNext()) { var levelThreeItem = levelThreeItemsEnumerator.Current as Foo_LevelThreeItem; if (levelThreeItem == null) continue; var levelFourItemsEnumerator = levelThreeItem.LevelFourItems.GetEnumerator(); while (levelFourItemsEnumerator.MoveNext()) { var levelFourItem = levelFourItemsEnumerator.Current as Foo_LevelFourItem; if (levelFourItem == null) continue; var levelFiveItemsEnumerator = levelFourItem.LevelFiveItems.GetEnumerator(); while (levelFiveItemsEnumerator.MoveNext()) { var levelFiveItem = levelFiveItemsEnumerator.Current as Foo_LevelFiveItem; if (levelFiveItem == null) continue; var levelSixItemsEnumerator = levelFiveItem.LevelSixItems.GetEnumerator(); while (levelSixItemsEnumerator.MoveNext()) { var levelSixItem = levelSixItemsEnumerator.Current as Foo_LevelSixItem; if (levelSixItem == null) continue; var levelSixKey = levelSixItem.Key; var foobar = foobars.Where(x =&gt; x.Key == levelSixKey).FirstOrDefault(); if (foobar == null) { foobar = new FooBar { LevelSixKey = levelSixKey, TransDate = levelFiveItem.TransDate, PaidAmount = 0 }; foobars.Add(foobar); } // * -1 because value should be positive, while product reports a negative (and vice versa) foobar.PaidAmount += (levelFiveItem.PaidAmount ?? 0) * -1; } } } } yield return new FooBarsCollection { Prop1 = levelTwoItemsItem.Prop1, Prop2 = levelTwoItemsItem.Prop2, Prop3 = levelTwoItemsItem.Prop3, FooBars = foobars }; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T22:13:05.133", "Id": "1684", "Score": "0", "body": "Is it safe to assume that each layer does not implement `IEnumerable<T>`?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T22:40:18.610", "Id": "1686", "Score": "0", "body": "@ChaosPandion, each layer is simply an Array. I've rewritten it using `foreach ()` loops, which is slightly better. But it's still the nesting that's driving me nuts, it just looks bad." } ]
[ { "body": "<p>If you extract the innermost nested part as its own method that takes a LevelSixKey as its parameter, then create your own Enumerator over levelSixItems, the product of which is the same as all your nesting (and, honestly, simply moved all the nesting into it - or added to a list at the inside of the innermost loop, and returned that list's enumerator), then what you see for the foobar-building is simply iterating over the enumerator and doing what you do - and all the ugly nested stuff is hidden away out of sight. It doesn't exactly <em>solve</em> the problem, but maybe it makes it more manageable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T23:08:40.067", "Id": "1687", "Score": "0", "body": "Method extraction will also make more detailed refactorings stand out." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-22T22:15:23.190", "Id": "934", "ParentId": "931", "Score": "2" } }, { "body": "<p>I would probably refactor out the two innermost loops into a method returning a <code>FooBarCollection</code>. You could then collapse the other loops with LINQs <code>SelectMany</code>:</p>\n\n<pre><code>foreach (var level2 in rootObject.SelectMany(l1 =&gt; l1.LevelTwoItems)) {\n var items = level2.LevelThreeItems\n .SelectMany(l3 =&gt; l3.LevelFourItems)\n .SelectMany(l4 =&gt; l4.LevelFiveItems);\n yield return CollectFooBars(level2, items);\n}\n</code></pre>\n\n<p>Edit: I took out the filtering for <code>null</code> values because that seem to be a result of non-generic enumerators in your example (and I assume there aren't any <code>null</code> values in those arrays).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T01:07:32.740", "Id": "938", "ParentId": "931", "Score": "5" } }, { "body": "<p>First of all, I would realise that</p>\n\n<pre><code>var levelOneEnumerator = rootObject.GetEnumerator();\nwhile (levelOneEnumerator.MoveNext())\n{\n var levelOneItem = levelOneEnumerator.Current as Foo_LevelOneItem;\n if (levelOneItem == null) continue;\n</code></pre>\n\n<p>is equivalent to the much shorter</p>\n\n<pre><code>foreach (var levelOneItem in rootObject.OfType&lt;Foo_LevelOneItem&gt;())\n{\n</code></pre>\n\n<p>Then you will realise that you have several nested <code>foreach</code> loops which make for nicely-readable single-line nestings. So factor all the multi-line code into methods of its own. The end-result I got looks like this:</p>\n\n<pre><code>foreach (var levelOneItem in rootObject.OfType&lt;Foo_LevelOneItem&gt;())\n foreach (var levelTwoItem in levelOneItem.LevelTwoItems.OfType&lt;Foo_LevelTwoItem&gt;())\n yield return new FooBarsCollection\n {\n Prop1 = levelTwoItem.Prop1,\n Prop2 = levelTwoItem.Prop2,\n Prop3 = levelTwoItem.Prop3,\n FooBars = getFoobars(levelTwoItem)\n };\n\n[...]\n\nprivate static List&lt;FooBar&gt; getFoobars(Foo_LevelTwoItem levelTwoItem)\n{\n var foobars = new List&lt;FooBar&gt;();\n\n foreach (var levelThreeItem in levelTwoItem.LevelThreeItems.OfType&lt;Foo_LevelThreeItem&gt;())\n foreach (var levelFourItem in levelThreeItem.LevelFourItems.OfType&lt;Foo_LevelFourItem&gt;())\n foreach (var levelFiveItem in levelFourItem.LevelFiveItems.OfType&lt;Foo_LevelFiveItem&gt;())\n foreach (var levelSixItem in levelFiveItem.LevelSixItems.OfType&lt;Foo_LevelSixItem&gt;())\n processLevelSixItem(foobars, levelFiveItem, levelSixItem.Key);\n\n return foobars;\n}\n\nprivate static void processLevelSixItem(List&lt;FooBar&gt; foobars, Foo_LevelFiveItem levelFiveItem, Foo_LevelSixItemKey levelSixKey)\n{\n var foobar = foobars.Where(x =&gt; x.Key == levelSixKey).FirstOrDefault();\n if (foobar == null)\n {\n foobar = new FooBar\n {\n LevelSixKey = levelSixKey,\n TransDate = levelFiveItem.TransDate,\n PaidAmount = 0\n };\n foobars.Add(foobar);\n }\n\n // * -1 because value should be positive, while product reports a negative (and vice versa)\n foobar.PaidAmount += (levelFiveItem.PaidAmount ?? 0) * -1;\n}\n</code></pre>\n\n<p>Of course, you could further change this into a much more LINQy expression involving either <code>SelectMany</code> or the <code>from</code> query syntax, but to be honest, in your particular case I would leave it like this. It is very clear. In case you still want the query syntax, here is just <code>getFoobars</code> to give you the idea:</p>\n\n<pre><code>private static List&lt;FooBar&gt; getFoobars(Foo_LevelTwoItem levelTwoItem)\n{\n var foobars = new List&lt;FooBar&gt;();\n\n var query =\n from levelThreeItem in levelTwoItem.LevelThreeItems.OfType&lt;Foo_LevelThreeItem&gt;()\n from levelFourItem in levelThreeItem.LevelFourItems.OfType&lt;Foo_LevelFourItem&gt;()\n from levelFiveItem in levelFourItem.LevelFiveItems.OfType&lt;Foo_LevelFiveItem&gt;()\n from levelSixItem in levelFiveItem.LevelSixItems.OfType&lt;Foo_LevelSixItem&gt;()\n select new { LevelFiveItem = levelFiveItem, Key = levelSixItem.Key };\n\n foreach (var info in query)\n processLevelSixItem(foobars, info.LevelFiveItem, info.Key);\n\n return foobars;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T03:57:16.860", "Id": "942", "ParentId": "931", "Score": "16" } }, { "body": "<p>What we have here is a tree data structure. Unfortunately it is an implicit tree structure which means we can't easily write some generic code to search the tree.</p>\n\n<p><strong>Make the tree structure explicit</strong></p>\n\n<p>So, what we first need is an adapter that can help to make things more generic. I don't know if these classes share a common base class, so everything will have to use <strong>object</strong>. If there is a common base class this will make things much tidier..</p>\n\n<p>We can have a class like so :</p>\n\n<pre><code>public static class BranchExtensions\n{\n public static Dictionary&lt;Type, Func&lt;object, IEnumerable&gt;&gt; NextLevels = new Dictionary&lt;Type, Func&lt;object, IEnumerable&gt;&gt; ();\n\n private static IEnumerable NextLevel ( object branch )\n {\n Func&lt;object, IEnumerable&gt; nextLevel;\n if (NextLevels.TryGetValue(branch.GetType (), out nextLevel))\n return nextLevel ( branch );\n else\n return null;\n }\n}\n</code></pre>\n\n<p>Then we need some initialization code somewhere :</p>\n\n<pre><code>BranchExtensions.NextLevels.Add ( typeof ( Foo_LevelOneItem ), level =&gt; ( (Foo_LevelOneItem) level ).Level2Items );\nBranchExtensions.NextLevels.Add ( typeof ( Foo_LevelTwoItem ), level =&gt; ( (Foo_LevelTwoItem) level ).Level3Items );\n</code></pre>\n\n<p>Now, given any item in the heirarchy I can call <code>NextLevel</code> and get an Enumerator for its next level.</p>\n\n<p><strong>Write some general utility functions</strong></p>\n\n<p>This enables us to write some generic code.</p>\n\n<p>What we need to do is walk the tree, collecting the objects we want along the way. When we read a leaf node, we want to process.</p>\n\n<p>So we add the following to our BranchExtensions :</p>\n\n<pre><code> private static IEnumerable&lt;Dictionary&lt;Type, object&gt;&gt; Flatten ( object branch, Predicate&lt;object&gt; collect, Dictionary&lt;Type, object&gt; collection )\n {\n IEnumerable nextLevel = NextLevel ( branch );\n if ( nextLevel != null )\n {\n foreach ( object next in nextLevel )\n {\n if ( next != null )\n {\n // Do we want to collect this type\n if ( collect ( next.GetType () ) )\n collection[next.GetType ()] = next;\n\n if ( NextLevel ( next ) == null )\n {\n // This is a leaf node.\n yield return collection;\n collection.Remove (next.GetType ());\n }\n else\n {\n // This is a branch, so recurse down the tree.\n foreach ( var more in Flatten ( next, collect, collection ) )\n {\n if ( more != null )\n {\n yield return more;\n collection.Remove ( more.GetType () );\n }\n }\n }\n }\n }\n }\n }\n\n public static IEnumerable&lt;Dictionary&lt;Type, object&gt;&gt; Flatten ( this Predicate&lt;object&gt; collect, object branch )\n {\n return Flatten ( branch, collect, new Dictionary&lt;Type, object&gt; () );\n }\n\n public static Predicate&lt;object&gt; Collect ( Predicate&lt;object&gt; collect )\n {\n return collect;\n }\n</code></pre>\n\n<p>The first Flatten method does all the work. It is pretty horrendous and I'm sure it could be tidied up and refactored, I just hacked it together to demonstrate the point.</p>\n\n<p>The second Flatten method is the entry point method. This creates a new Dictionary to collect our values and passes the call along. It should do some validation here as well really. </p>\n\n<p>As a slight frill - this is an extension method on Predicate. The Collect method following is even stranger and does nothing really. It is just there to enable a more fluent interface when coming to use it.</p>\n\n<p><strong>Use the code</strong></p>\n\n<p>The Nested loops can then be converted to something like the following :</p>\n\n<pre><code>foreach ( var collection in BranchExtensions.Collect( type =&gt; type == typeof(Foo_LevelFiveItem) || type == typeof(Foo_LevelSixItem)).Flatten ( rootObject ) )\n{\n var levelFiveItem = collection[typeof(Foo_LevelFiveItem)] as Foo_LevelFiveItem;\n var levelSixItem = collection[typeof(Foo_LevelSixItem)] as Foo_LevelSixItem\n\n // Do stuff on our items...\n}\n</code></pre>\n\n<p>It looks like a lot of work to acheive a small thing. It all depends on how much you need to use this stuff. If you have only got a single nested loop in your entire application, then none of this makes sense and I would just suck up the nested loop and carry on.</p>\n\n<p>But,</p>\n\n<p>If you have nested loops all over your code, then a few utility methods like this would make a lot of sense to abstract the complexity away and allow you to focus on the meaning of what you are trying to do.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-12T19:17:08.280", "Id": "176733", "Score": "0", "body": "Great code and explanation!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T15:43:49.610", "Id": "951", "ParentId": "931", "Score": "4" } }, { "body": "<p>I've not tested it properly, but this LINQ query should do the same:</p>\n\n<pre><code>foreach (var levelOneItem in rootObject.OfType&lt;Foo_LevelOneItem&gt;()) {\n foreach (var levelTwoItemsItem in levelOneItem.LevelTwoItems.OfType&lt;Foo_LevelTwoItem&gt;()) {\n\n var foobars = (from levelThreeItem in levelTwoItemsItem.LevelThreeItems.OfType&lt;Foo_LevelThreeItem&gt;()\n from levelFourItem in levelThreeItem.LevelFourItems.OfType&lt;Foo_LevelFourItem&gt;()\n from levelFiveItem in levelFourItem.LevelFiveItems.OfType&lt;Foo_LevelFiveItem&gt;()\n from levelSixItem in levelFiveItem.LevelSixItems.OfType&lt;Foo_LevelSixItem&gt;()\n group levelSixItem by levelSixItem.levelSixKey into groupedLevelSixItems\n select new FooBar() {\n LevelSixKey = groupedLevelSixItems.Key,\n TransDate = levelFiveItem.TransDate,\n PaidAmount = (-levelFiveItem.PaidAmount ?? 0) * groupedLevelSixItems.Count()\n }).ToList();\n\n yield return new FooBarsCollection\n {\n Prop1 = levelTwoItemsItem.Prop1,\n Prop2 = levelTwoItemsItem.Prop2,\n Prop3 = levelTwoItemsItem.Prop3,\n FooBars = foobars\n };\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-26T16:04:23.170", "Id": "1474", "ParentId": "931", "Score": "0" } } ]
{ "AcceptedAnswerId": "942", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-22T21:41:01.967", "Id": "931", "Score": "11", "Tags": [ "c#", ".net" ], "Title": "Deep nesting when looping over an object model coming from a 3rd part" }
931
<p>I implemented a multistep form with the method described by Ryan Bates in <a href="http://www.asciicasts.com/episodes/217-multistep-forms" rel="nofollow">ep217</a> but I had some weird behavior when refreshing or moving between the steps <a href="http://rubyglasses.blogspot.com/2007/08/actsasgoodstyle.html" rel="nofollow">Acts_as_good_style</a> (old but still good) has a tip <strong>redirect when moving on</strong> that lead me to the change in the code that follows.</p> <p>In a nutshell, it says that if you're in the <code>create</code> action you should not render <code>new</code> (as I was doing).</p> <p>This solved the problem. But I had to manage the case of errors in the form, so I ended up with this code.</p> <pre><code>#profiles_controller.rb def create # [...] save etc [...] # render if @profile.new_record? # render 'new' # OLD session[:profile_valid] = @profile.errors.blank? # NEW redirect_to new_profile_path # NEW else # [...] end end def new @profile = Profile.new(session[:profile_params]) # [...] # rebuild errors (see create) # check false because first time is nil and no error have to be displayed @profile.valid? if session[:profile_valid] == false session[:profile_valid] = true end </code></pre> <p>Where in the <code>new</code> action I reload the errors otherwise lost depending on <code>session[:profile_valid]</code>, that works fine.</p> <p>BUT this way doesn't look very good to me and I would appreciate to have your opinion, OR how do you manage your controllers in multispets forms?</p> <p>What was the strange behavior? Refreshing or going back and forth through the steps sometimes you jump to the wrong page, not clear what the logic is, probably depends on the validations in the model and the params hash.</p>
[]
[ { "body": "<p>I can't speak for that particular Railscast episode, but rails provides an idiomatic way to deal with validation errors. Taking your code as an example, I'd change it to look like this (using Rails 4.2):</p>\n\n<p><strong>app/controllers/profiles_controller.rb:</strong></p>\n\n<pre><code>class ProfilesController &lt; ActionController::Base\n def show\n @profile = Profile.find(...)\n end\n\n def new \n @profile = Profile.new(profile_params)\n end\n\n def create\n @profile = Profile.new(profile_params)\n\n if @profile.save\n redirect_to profile_path(@profile)\n\n else\n render :new\n end\n end\n\n def edit\n @profile = Profile.find(...)\n end\n\n def update\n @profile = Profile.find(...)\n\n if @profile.update_attributes(profile_params)\n redirect_to profile_path(@profile)\n\n else\n render :edit\n end\n end\n\n private\n\n def profile_params\n # call params.require(:profile).permit(...) to whitelist attributes as needed\n params.require(:profile)\n end\nend\n</code></pre>\n\n<p><strong>app/views/profiles/new.html.haml:</strong></p>\n\n<pre><code>%h2 New Profile\n= render partial: 'form'\n</code></pre>\n\n<p><strong>app/views/profiles/edit.html.haml:</strong></p>\n\n<pre><code>%h2 Edit Profile\n= render partial: 'form'\n</code></pre>\n\n<p><strong>app/views/profiles/_form.html.haml:</strong></p>\n\n<pre><code>= form_for(@profile) do |f|\n - # Display any form errors, if any\n - if @profile.errors.any?\n .errors\n %h2 Errors\n %ul\n - @profile.errors.full_messages do |message|\n %li= message\n\n - # Assuming profiles have first_name and last_name as attributes\n %section\n = f.label :first_name\n = f.text_field :first_name\n\n %section\n = f.label :last_name\n = f.text_field :first_name\n\n %section\n = f.submit\n</code></pre>\n\n<p>This is a very common pattern in rails apps that you can also see being used in the <a href=\"http://guides.rubyonrails.org/form_helpers.html#dealing-with-model-objects\">rails guides</a>. The <code>form_for</code> helper is smart enough to generate the correct path to submit the form to depending on weather or not the <code>@profile</code> instance variable contains a record that has or has not been persisted. Persisted records (new ones or those with errors) will be posted to create. Records being updated will be set to whatever the <code>update</code> action/path for that controller is.</p>\n\n<p>Whenever updating or saving a record fails, the controller will render the appropriate view (<code>new</code> or <code>edit</code>) and use the record that failed validation when rendering the form. From here, your view can inspect the record and display any errors if they exist (<code>@profile.errors</code>).</p>\n\n<p>This won't fix an issue of a user navigating backwards and forwards through your form, but it should reduce the need to do so and it'll let you avoid weirdness you may have encountered while persisting form data within the <code>session</code> variable (which gets serialized and de-serialized into whatever your session store is during each request).</p>\n\n<hr/>\n\n<p>PS: I find that thinking of multi-step forms with more than one or two steps as <a href=\"http://en.wikipedia.org/wiki/Finite-state_machine\">state machines</a> helps greatly in trying to conceptualize the different states and transitions you need to handle when you need to determine at what point in a form a particular session should be in. To that effect, I would highly recommend checking out the <a href=\"https://github.com/schneems/wicked\">wicked</a> gem which does a lot of this grunt work for you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-19T20:18:17.207", "Id": "134945", "Score": "0", "body": "I like your answer! I'll wait a day or two before granting the bounty. Thanks for looking it over!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-02T07:47:41.397", "Id": "137269", "Score": "0", "body": "Thanks. Relatively simple question though, I'm surprised nobody has chimed in yet." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-19T05:35:45.707", "Id": "74135", "ParentId": "935", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-22T22:16:02.330", "Id": "935", "Score": "7", "Tags": [ "ruby", "ruby-on-rails", "form" ], "Title": "Developing a multistep form" }
935
<p>This is some Erlang code I wrote to output a string of all the IP addresses of the machine. The string is simply printed to the user for him to read.</p> <pre><code>-module(ip). -export([get_ip_address_string/0]). get_ip_address_string() -&gt; {ok, IPAddress} = inet:getif(), filter_ip_address(IPAddress). filter_ip_address(IPAddress) -&gt; filter_ip_address(IPAddress, []). filter_ip_address([], Acc) -&gt; Acc; filter_ip_address([{{127,0,0,1}, _Broadcast, _Mask} | Tail], Acc) -&gt; %Do not include the loopback address. filter_ip_address(Tail, Acc); filter_ip_address([Head | Tail], Acc) -&gt; {{Oct1, Oct2, Oct3, Oct4}, _Broadcast, _Mask} = Head, IPString = io_lib:format("~b.~b.~b.~b ", [Oct1, Oct2, Oct3, Oct4]), filter_ip_address(Tail, IPString ++ Acc). </code></pre> <p>Comments on how to write this in a more Erlang way, make it more readable, or anything you would do different are welcome.</p>
[]
[ { "body": "<p>First of all your variable <code>IPAddress</code> is misnamed. It sounds as if it contained a single IP address, but in fact it contains a list of multiple triples, where each one does not only contain an IP address, but also the corresponding broadcast address and netmask. You should probably call it something like <code>IPTriples</code>.</p>\n\n<p>If you look at your code it's basically doing three things:</p>\n\n<ol>\n<li>Filtering out localhost</li>\n<li>Replacing each ip address with a string representation</li>\n<li>Concatenating the thus created list of strings, separating them with spaces.</li>\n</ol>\n\n<p>For each of these 3 steps there's already an erlang function, which can be used to do it:</p>\n\n<ol>\n<li><code>lists:filter</code> which takes a predicate and a list and returns a list only containing elements that match this predicate.</li>\n<li><code>lists:map</code> which takes a function and a list and returns a list containing the result of the function for each element.</li>\n<li><code>string:join</code> which takes a list of strings and a separator and returns a string with each item in the list separated by the separator.</li>\n</ol>\n\n<p>Usually it it is good style to reuse existing functionality as much as possible instead of reimplementing it. So using these functions, your <code>get_ip_address_string</code> can be rewritten to something like this:</p>\n\n<pre><code>get_ip_address_string() -&gt;\n {ok, IPTriples} = inet:getif(),\n FilteredIPTriples = lists:filter(fun is_not_localhost/1), IPTriples),\n IPAddresses = lists:map(fun ip_triple_to_string/1, FilteredIPTriples),\n string:join(IPAddresses, \" \").\n\nis_not_localhost({{127,0,0,1}, _Broadcast, _Mask}) -&gt; false;\nis_not_localhost({_IP, _Broadcast, _Mask}) -&gt; true.\n\nip_triple_to_string({{Oct1, Oct2, Oct3, Oct4}, _Broadcast, _Mask}) -&gt;\n io_lib:format(\"~b.~b.~b.~b\", [Oct1, Oct2, Oct3, Oct4]).\n</code></pre>\n\n<p>Note that this has also the benefit that the logic for filtering out localhost, the logic for turning the IP addresses into strings and the logic for building the result string from that are now no longer intertwined, which should make the code more manageable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T12:36:16.763", "Id": "944", "ParentId": "940", "Score": "6" } }, { "body": "<p>My solution is close to sepp2k's:</p>\n\n<p>First a simpler conversion routine:</p>\n\n<pre><code>ip_triple_to_string(Tup) -&gt;\n io_lib:format(\"~b.~b.~b.~b\", tuple_to_list(Tup)).\n</code></pre>\n\n<p>Then the meat:</p>\n\n<pre><code>get_ip_address_string() -&gt;\n {ok, IPTriples} = inet:getif(),\n</code></pre>\n\n<p>Not much you can do here. You have to assert that you really got data from the <code>getif/0</code> call.</p>\n\n<pre><code> Strings = [ip_triple_to_string(IP) || {IP, _, _} &lt;- IPTriples,\n IP =/= {127,0,0,1}],\n string:join(Strings, \" \").\n</code></pre>\n\n<p>The list comprehension captures the map and filter in one go over the list. Otherwise, it is much like the other definition.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T14:08:01.530", "Id": "945", "ParentId": "940", "Score": "6" } } ]
{ "AcceptedAnswerId": "944", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T02:21:09.943", "Id": "940", "Score": "7", "Tags": [ "functional-programming", "erlang", "ip-address" ], "Title": "Erlang code to list all IP addresses" }
940
<p>I have written an Android application which downloads pdf files through web service. I am using kSoap2 android library to parse the response of web service which basically contains file name &amp; file data. </p> <p>I have written following code. Please review &amp; tell how to increase the speed I think there is some small defect in code which reduces the speed. I am using version 2.5.1 of kSoap2.</p> <pre><code>public void downloadPdfFiles(File fileDocsDir, int noOfFiles) throws NullPointerException, SoapFault, XmlPullParserException, FileNotFoundException, IOException, Exception { System.gc(); // Download files from web service and save them in the folder. soapObject = new SoapObject(NAMESPACE, METHOD_NAME); soapObject.addProperty("startingFile", noOfFiles); soapObject.addProperty("deviceId", deviceId); soapObject.addProperty("loginId", loginId); soapObject.addProperty("byoinId", "1"); envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(soapObject); // Calling the web service System.gc(); androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.call(SOAP_ACTION, envelope); // Getting Response through xml mainly generated as soap:reponse. responseBean = (SoapObject) envelope.getResponse(); // Array of PDFInfoBean. list = (SoapObject) responseBean.getProperty(0); FileOutputStream outputStream = null; BufferedOutputStream bufferedOutputStream = null; // Get Individual PDF Details from Array. SoapObject pdfDetails = null; mIncrement = noOfFiles; // Log.i("Increment Values", String.valueOf(mIncrement)); File pdfFile = null; for (int i = 0; i &lt; list.getPropertyCount(); i++) { pdfDetails = (SoapObject) list.getProperty(i); // Get PDF File Name. pdfDocName = pdfDetails.getProperty(1).toString(); Log.i(TAG, "File Name: " + pdfDocName); // Check for last file. if (pdfDocName.equalsIgnoreCase("EOF")) { mFlag = false; break; } // Creating PDF File. pdfFile = new File(fileDocsDir, pdfDocName); // Writing PDF file received through web service. if (pdfFile.exists()) { Log.i(TAG, pdfFile.getName() + " File Already Exists"); } else { outputStream = new FileOutputStream(pdfFile); bufferedOutputStream = new BufferedOutputStream(outputStream); bufferedOutputStream.write(Base64Coder.decode(pdfDetails .getProperty(0).toString())); mIncrement = mIncrement + 1; bufferedOutputStream.close(); outputStream.close(); bufferedOutputStream = null; outputStream = null; } pdfDetails = null; pdfDocName = null; pdfFile = null; System.gc(); } soapObject = null; envelope = null; responseBean = null; list = null; androidHttpTransport = null; System.gc(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-14T07:12:54.743", "Id": "2234", "Score": "2", "body": "what are the sizes of these pdf's? you're buffering the entire things in memory before writing them out; I suspect even without your System.gc's to spice things up, you observe lots of gc activity and possibly OOME's." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-14T07:34:53.277", "Id": "2235", "Score": "0", "body": "Basically the size of pdf's that are to be received at client side are of 1 mb from 533mb folder at server side." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T02:04:35.560", "Id": "15711", "Score": "0", "body": "can you post server side web service code also. Thanks\nSampath" } ]
[ { "body": "<ol>\n<li><p>Forcing <code>System.gc()</code> isn't a good practice.</p></li>\n<li><pre><code>outputStream = new FileOutputStream(pdfFile);\n bufferedOutputStream = new BufferedOutputStream(outputStream);\n</code></pre>\n\n<p>should be wrapped into 1 variable to do a single <code>close()</code> afterwards:</p>\n\n<pre><code>outputStream = new BufferedOutputStream(new FileOutputStream(pdfFile));\n</code></pre></li>\n<li><p>All operations with <code>outputStream</code> should be put in <code>try-finally</code> block:</p>\n\n<pre><code>outputStream = new ...\ntry {\n outputStream.write(...);\n ...\n} finally {\n outputStream.close();\n}\n</code></pre></li>\n<li><p>Agree with the first comment: your file may simply not fit in memory. In SOAP API there should be some mean of getting the <code>InputStream</code> instead of an in-memory string.</p></li>\n</ol>\n\n<p>Sorry for the formatting, couldn't fight the editor.</p>\n\n<p>Good luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-25T10:07:25.293", "Id": "2518", "Score": "0", "body": "Thanks for your answer.I already overcome the problem of OutOfMemory issue,here I posted it for just get better review from sharp programmers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-10T19:15:07.737", "Id": "15733", "Score": "1", "body": "I agree with 3., but it should be mentioned that if Java 7 is available, ARM-blocks can deal with that pain." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-26T23:24:09.523", "Id": "28671", "Score": "0", "body": "@Landei also known as [try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-25T09:25:03.670", "Id": "1445", "ParentId": "943", "Score": "5" } }, { "body": "<p>@weekens noted: </p>\n\n<blockquote>\n <p>Forcing System.gc() isn't a good practice.</p>\n</blockquote>\n\n<p>This is so true. In fact, calling <code>System.gc()</code> is likely to have a <em>major</em> impact on the performance of your application.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-26T06:08:51.190", "Id": "1470", "ParentId": "943", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-23T10:16:10.800", "Id": "943", "Score": "7", "Tags": [ "java", "android", "soap" ], "Title": "How to increase download speed using the following method?" }
943
<p>Trying to refactor this code and can't seem to think of a way to make it cleaner. <code>Type</code> is a property in my <code>Person</code> class.</p> <pre><code>foreach (var item in list) { if (person.Type != PersonType.Employee &amp;&amp; person.Type != PersonType.Manager &amp;&amp; person.Type != PersonType.Contractor &amp;&amp; person.Type != PersonType.Executive) { DoSomething(); } } public enum PersonType : int { Employee = 0, Manager = 1, Contractor = 2, President = 3, Executive = 4 } </code></pre> <p>I should note that there are other types in the <code>PersonType</code> class which I don't want to show.</p>
[]
[ { "body": "<p>I would probably go with code that looked like this.</p>\n\n<pre><code>list.ForEach(c =&gt; \n {\n if (DoAction(c.Type))\n {\n DoSomething();\n }\n });\n\n\nprivate static bool DoAction(PersonType personType)\n {\n switch (personType)\n {\n case PersonType.Employee: \n case PersonType.Manager: \n case PersonType.Contractor: \n case PersonType.Executive:\n return false;\n default:\n return true;\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T15:26:56.310", "Id": "1701", "Score": "0", "body": "That won't `DoSomething` if `c.Type` is 3." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T15:31:45.213", "Id": "1703", "Score": "0", "body": "Fixed a glaring error." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T15:21:06.110", "Id": "947", "ParentId": "946", "Score": "2" } }, { "body": "<p>You could use Enum.IsDefined. It has some disadvantages. It can be slow, and it is not strongly typed, but I do like how it reads.</p>\n\n<pre><code>foreach (var item in list)\n{\n if (!Enum.IsDefined(typeof(PersonType), person.Type))\n {\n DoSomething();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T15:50:19.573", "Id": "1704", "Score": "0", "body": "Sorry for the confusion. You're right that this would work, but there are types that I don't want to show (updated question)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T15:31:16.510", "Id": "949", "ParentId": "946", "Score": "2" } }, { "body": "<p>[Edit] Corrected given edit to question</p>\n\n<p>Try something more like this</p>\n\n<pre><code>[Flags]\npublic enum PersonType\n{\n None = 0,\n Employee = 1 &lt;&lt; 0,\n Manager = 1 &lt;&lt; 1,\n Contractor = 1 &lt;&lt; 2,\n President = 1 &lt;&lt; 3,\n Executive = 1 &lt;&lt; 4\n}\n\nforeach (var item in list)\n{\n if ((person.Type &amp; PersonType.President) == 0)\n {\n DoSomething();\n }\n}\n</code></pre>\n\n<p>You can now also add combined values such as</p>\n\n<pre><code>[Flags]\npublic enum PersonType\n{\n None = 0,\n Employee = 1 &lt;&lt; 0,\n Manager = 1 &lt;&lt; 1,\n Contractor = 1 &lt;&lt; 2,\n President = 1 &lt;&lt; 3,\n Executive = 1 &lt;&lt; 4,\n NotPresident = Employee | Manager | Contractor | Executive,\n Boss = Manager | President | Executive\n}\n</code></pre>\n\n<p>Given this enumeration, this NUnit test passes</p>\n\n<pre><code>[Test]\npublic void TestEnum()\n{\n var personType = PersonType.Manager | PersonType.Contractor;\n Assert.That(personType == PersonType.None, Is.Not.True);\n Assert.That((personType &amp; PersonType.Manager) != 0, Is.True);\n Assert.That((personType &amp; PersonType.Boss) != 0, Is.True);\n Assert.That((personType &amp; PersonType.Employee) != 0, Is.Not.True);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T17:29:59.543", "Id": "1709", "Score": "0", "body": "I would consider this bad design. You are using a Flags enum just to make the comparisons more convenient, but this goes against the semantics of the enum. Your design suggests that it is possible for someone to be a Manager and a Contractor at the same time, while explicitly *not* being an Employee..." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T17:57:23.997", "Id": "1710", "Score": "0", "body": "@Timwi - FWIW, a Contractor probably isn't going to be an Employee. However, I do see your point. The original question had only 0, 1, 2, 4 so I was thrown in the direction of Flags. If the question had been written as it is now, I might have given the same answer you did" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T15:41:13.607", "Id": "950", "ParentId": "946", "Score": "5" } }, { "body": "<p>If this is just a one shot test, then I would use something like this. If this was used in multiple places, I would probably use flags like pdr.</p>\n\n<pre><code>PersonType[] ignoredPersonTypes = \n{\n PersonType.Employee,\n PersonType.Manager,\n PersonType.Contractor,\n PersonType.Executive,\n}\n\nforeach (var item in list)\n{\n if (ignoredPersonTypes.Contains(person.Type) == false)\n {\n DoSomething();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T17:30:28.110", "Id": "952", "ParentId": "946", "Score": "0" } }, { "body": "<p><strong>If the “allowedness” of a <code>PersonType</code> value is specific to the particular algorithm you are writing,</strong> I usually write this as an array:</p>\n\n<pre><code>var disallowedTypes = new[] {\n PersonType.Employee,\n PersonType.Manager,\n PersonType.Contractor,\n PersonType.Executive\n};\n\nforeach (var item in list.Where(p =&gt; !disallowedTypes.Contains(p.Type)))\n DoSomething(item);\n</code></pre>\n\n<p><strong>If this set of disallowed types is central to your application</strong> (or to a particular class), I would declare it as a static field in a static class (or the relevant class). That way your entire program (or that class) has convenient access to it, and you only need to update it in a single place if the business logic changes:</p>\n\n<pre><code>public static class Data\n{\n public static readonly PersonType[] DisallowedTypes = {\n PersonType.Employee,\n PersonType.Manager,\n PersonType.Contractor,\n PersonType.Executive\n };\n}\n\n// [ ... ]\n\nforeach (var item in list.Where(p =&gt; !Data.DisallowedTypes.Contains(p.Type)))\n DoSomething(item);\n</code></pre>\n\n<p><strong>If the set of disallowed types is inherent in the semantics of the <code>PersonType</code> enum itself,</strong> I would make this very explicit by using custom attributes in the enum type itself. Of course you should think up a more descriptive name than <code>IsAllowed</code> and fix the XML comment on the attribute type to explain what it <em>really</em> means:</p>\n\n<pre><code>/// &lt;summary&gt;Specifies that a &lt;see cref=\"PersonType\"/&gt; value is allowed.&lt;/summary&gt;\npublic sealed class IsAllowedAttribute : Attribute { }\n\npublic enum PersonType\n{\n Employee,\n Manager,\n Contractor,\n Executive,\n\n [IsAllowed]\n President\n}\n\npublic static class Data\n{\n /// &lt;summary&gt;This array is automatically prefilled with the\n /// PersonType values that do not have an [IsAllowed] custom attribute.\n /// To change this array, change the custom attributes in the\n /// &lt;see cref=\"PersonType\"/&gt; enum instead.&lt;/summary&gt;\n public static readonly PersonType[] DisallowedTypes;\n\n static Data()\n {\n DisallowedTypes = typeof(PersonType)\n .GetFields(BindingFlags.Public | BindingFlags.Static)\n .Where(f =&gt; !f.IsDefined(typeof(IsAllowedAttribute), false))\n .Select(f =&gt; f.GetValue(null))\n .ToArray();\n }\n}\n</code></pre>\n\n<p>This way the information whether any particular enum value is allowed or not is stored in the enum itself and no-where else. That makes the code very explicit, easy to follow, and easy to modify in obviously-correct ways.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T20:17:27.730", "Id": "1721", "Score": "0", "body": "Thanks to you and PDR for your comments. Both seem like logical choices, but as you mentioned, this is central to my app, so your solution works better in my case." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T17:34:44.890", "Id": "953", "ParentId": "946", "Score": "13" } }, { "body": "<p>This is such a perfect match for the <a href=\"http://Refactoring.Com/catalog/replaceConditionalWithPolymorphism.html\"><em>Replace Conditional with Polymorphism</em> Refactoring</a> that it even looks as if it was specifically designed to demonstrate the Replace Conditional with Polymorphism Refactoring. I mean, the field it is basing its behavior on is even <em>called</em> <code>Type</code>!</p>\n\n<pre><code>interface Person { void DoSomething(); }\n\nclass PrivilegedPerson : Person {\n public void DoSomething() {\n // do something\n }\n}\n\nclass UnprivilegedPerson : Person {\n public void DoSomething() {} // literally do nothing\n}\n\nclass Employee : UnprivilegedPerson {}\nclass Manager : UnprivilegedPerson {}\nclass Contractor : UnprivilegedPerson {}\nclass President : UnprivilegedPerson {}\nclass Executive : UnprivilegedPerson {}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-20T03:07:19.377", "Id": "135002", "Score": "2", "body": "This may not be the accepted answer, but it's the right one in my opinion." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T18:18:26.177", "Id": "955", "ParentId": "946", "Score": "15" } }, { "body": "<p>Assuming you don't want to turn <code>PersonType</code> into an actual polymorphic class, a simple cleanup is:</p>\n\n<pre><code>foreach (var item in list)\n{\n switch (person.Type) {\n case PersonType.Employee:\n case PersonType.Manager:\n case PersonType.Contractor:\n case PersonType.Executive:\n // Do nothing.\n break;\n default:\n DoSomething();\n }\n}\n</code></pre>\n\n<p>You have to be careful with enums, though. If a new <code>PersonType</code> is added, is <code>DoSomething()</code> the correct behavior for that type? A safer implementation won't rely on <code>default</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T14:12:50.707", "Id": "1727", "Score": "0", "body": "+1 for a clean switch statement. I personally like the look of those. I also agree that the safer implementation would not rely on default, especially with an enum, I tend to use the default case to throw an invalid value exception." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T04:12:32.207", "Id": "963", "ParentId": "946", "Score": "3" } } ]
{ "AcceptedAnswerId": "953", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-23T15:10:37.940", "Id": "946", "Score": "8", "Tags": [ "c#", ".net" ], "Title": "Refactoring a bunch of and statements" }
946
<p>I am not very good with thread-safety and often fall prey to subtle issues in concurrency. Therefore, I hope that someone here might be able to tell me whether there is a subtle concurrency issue (race condition etc.) in the following code, or whether it’s fine. In particular, have I used <code>Monitor.Wait</code> and <code>Monitor.PulseAll</code> correctly?</p> <p>Of course, if you can reason about the code and come to the conclusion that it is already correct, that would be a welcome answer too.</p> <p>This code is intended to implement the <code>costreams</code> pattern (I invented that name, so you won’t find it in Google). It runs two methods (passed in as delegates) in parallel. It provides one of those methods with a write-only stream and the other with a read-only stream. The idea is for one of them to generate data and write it to the stream, and the other one to read from the stream and consume the data. (The reading/writing methods intended to be passed in could be anything that reads to/writes from a stream; they are not likely to be specifically written to be used with costreams. If they were, they could probably be rewritten so that they wouldn’t need to use streams at all.)</p> <p>While reviewing the <code>Read</code> method, remember that the contract for <code>Stream.Read</code> is slightly counterintuitive: it is allowed to read and return fewer bytes than requested (as long as it returns the number of bytes actually read). Thus the fact that it sometimes returns fewer bytes than the <code>count</code> parameter requests is not a bug. Of course it must not return 0 except when the end of the stream is reached.</p> <pre><code>using System; using System.Collections.Generic; using System.IO; using System.Threading; namespace MyLibrary { public static class Costreams { /// &lt;summary&gt;Runs the two specified processes in parallel, allowing one to generate data by writing it to a stream, and the other to consume the data by reading it from a stream.&lt;/summary&gt; /// &lt;param name="writingAction"&gt;An action that generates data and writes it to a stream.&lt;/param&gt; /// &lt;param name="readingAction"&gt;An action that will want to read information from a stream.&lt;/param&gt; public static void RunCostreams(Action&lt;Stream&gt; writingAction, Action&lt;Stream&gt; readingAction) { // Everything the writingAction writes will be enqueued in here and dequeued by the readingAction var queue = new Queue&lt;byteChunk&gt;(); writingCostream writer = new writingCostream(queue); readingCostream reader = new readingCostream(queue); // Start reading in a new thread. The first call to reader.Read() will block until there is something in the queue to read. var thread = new Thread(() =&gt; readingAction(reader)); thread.Start(); // Start writing. Calls to writer.Write() will place the data in the queue and signal the reading thread. writingAction(writer); // Insert a null at the end of the queue to signal to the reader that this is where the data ends. queue.Enqueue(null); // Wait for the reader to consume all the remaining data. thread.Join(); } private sealed class byteChunk { public byte[] Buffer; public int Offset; public int Count; } private sealed class readingCostream : Stream { private Queue&lt;byteChunk&gt; _queue; public readingCostream(Queue&lt;byteChunk&gt; queue) { _queue = queue; } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override void Flush() { } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override int Read(byte[] buffer, int offset, int count) { lock (_queue) { // If there is no data waiting to be read, wait for it. while (_queue.Count == 0) Monitor.Wait(_queue); var peeked = _queue.Peek(); // A null element in the queue signals the end of the stream. Don't dequeue this item. if (peeked == null) return 0; if (peeked.Count &lt;= count) { // If we can return the complete item, dequeue it Buffer.BlockCopy(peeked.Buffer, peeked.Offset, buffer, offset, peeked.Count); _queue.Dequeue(); return peeked.Count; } else { // If we can only return part of the item, modify it accordingly Buffer.BlockCopy(peeked.Buffer, peeked.Offset, buffer, offset, count); peeked.Offset += count; peeked.Count -= count; return count; } } } } private sealed class writingCostream : Stream { private Queue&lt;byteChunk&gt; _queue; public writingCostream(Queue&lt;byteChunk&gt; queue) { _queue = queue; } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override void Flush() { } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { // Ignore zero-length writes if (count == 0) return; lock (_queue) { // We have to take a copy of the data because the calling thread might re-use the same buffer multiple times. var bufferCopy = new byte[count]; Buffer.BlockCopy(buffer, offset, bufferCopy, 0, count); // Put the data in the queue _queue.Enqueue(new byteChunk { Buffer = bufferCopy, Offset = 0, Count = count }); // Signal the reading thread(s) that the queue has changed (in case it's waiting) Monitor.PulseAll(_queue); } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T18:56:24.593", "Id": "1714", "Score": "0", "body": "This seems instinctively to be a serious misuse of Streams. When you start calling NotImplementedException in so many places, you need to question your approach. Given that you can't call Seek, Length, Position or Flush, why does your readingAction need a Stream at all? If you add the calling code to the question, someone might have a much better design." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T18:58:40.257", "Id": "1715", "Score": "0", "body": "@pdr I see no `NotImplementedException`s in this code at all. As for `NotSupportedException` - standard streams do this too. It's ok for Seek to throw as long as `CanSeek` is false - it's explicitly part of the contract." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T19:12:34.247", "Id": "1716", "Score": "0", "body": "@romkyns You're right, of course, that it's NotSupportedException. And also that it's ok to do so in the right circumstances. I'm just suggesting that if everything about a stream is unsupported except Read/Write then there has to be a question over what use the Stream class is to the calling code" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T19:15:25.093", "Id": "1717", "Score": "0", "body": "@pdr: This is reusable library code which is supposed to work for any `readingAction`/`writingAction` that fulfills the contract (`readingAction` should only read and `writingAction` should only write). I assure you that I am perfectly able to avoid using costreams in cases where my particular reading/writing actions don’t actually need streams." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T19:30:29.637", "Id": "1718", "Score": "0", "body": "@Timwi Fair enough" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T16:05:54.727", "Id": "1734", "Score": "0", "body": "@Timwi, the standard name for this is **pipe**. If you're using .Net 3.5 then they're in the library." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T16:23:21.023", "Id": "1735", "Score": "0", "body": "@Peter: Specifically which class(es)?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T18:05:15.280", "Id": "1742", "Score": "0", "body": "@Timwi, the System.IO.Pipes namespace has two different types. See http://msdn.microsoft.com/en-us/library/bb546102%28VS.90%29.aspx for an example with AnonymousPipeServerStream and AnonymousPipeClientStream" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T18:27:34.887", "Id": "1743", "Score": "0", "body": "This may be helpful http://stdcxx.apache.org/doc/stdlibug/34-3.html" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T18:40:30.410", "Id": "1745", "Score": "0", "body": "@Peter: Those are for inter-process communication; also, I’m told the writing pipe will wait for the reading pipe to consume it. Thus, it is not like costreams." } ]
[ { "body": "<p>Depends what you're trying to do. Is it really possible to have multiple Read threads, as the comment suggests? If so then you're going to run a risk of having several Reads released at once and return in the wrong order. If not then why use <code>PulseAll</code> as opposed to <code>Pulse</code>?</p>\n\n<p>It feels wrong to me that if Read is called and there are items on the Queue then further calls to Write are locked out, but if Read Waits until Write releases it, then Write is called again, Write will be able to lock the Queue and use it. That said, it shouldn't be a problem given that Read will be dealing with another item at the time.</p>\n\n<p>But that raises the question, why bother with the Wait? Why not replace the whole thing with a <code>ManualResetEvent</code>? That way, you only have to lock the queue while you're updating it, so that you can <code>Set</code> the event when you add data, <code>Reset</code> it when you remove the last item.</p>\n\n<p>I haven't tested it, but it will look a lot like this:</p>\n\n<pre><code>public static class Costreams\n{\n /// &lt;summary&gt;Runs the two specified processes in parallel, allowing one to generate data by writing it to a stream, and the other to consume the data by reading it from a stream.&lt;/summary&gt;\n /// &lt;param name=\"writingAction\"&gt;An action that generates data and writes it to a stream.&lt;/param&gt;\n /// &lt;param name=\"readingAction\"&gt;An action that will want to read information from a stream.&lt;/param&gt;\n public static void RunCostreams(Action&lt;Stream&gt; writingAction, Action&lt;Stream&gt; readingAction)\n {\n // Everything the writingAction writes will be enqueued in here and dequeued by the readingAction\n var queue = new Queue&lt;byteChunk&gt;();\n using (var hasData = new ManualResetEvent(false))\n {\n writingCostream writer = new writingCostream(queue, hasData);\n readingCostream reader = new readingCostream(queue, hasData);\n\n // Start reading in a new thread. The first call to reader.Read() will block until there is something in the queue to read.\n var thread = new Thread(() =&gt; readingAction(reader));\n thread.Start();\n\n // Start writing. Calls to writer.Write() will place the data in the queue and signal the reading thread.\n writingAction(writer);\n\n // Insert a null at the end of the queue to signal to the reader that this is where the data ends.\n lock(queue)\n {\n queue.Enqueue(null);\n hasData.Set();\n }\n\n // Wait for the reader to consume all the remaining data.\n thread.Join();\n }\n }\n\n private sealed class byteChunk\n {\n public byte[] Buffer;\n public int Offset;\n public int Count;\n }\n\n private sealed class readingCostream : Stream\n {\n private Queue&lt;byteChunk&gt; _queue;\n private ManualResetEvent _hasData;\n\n public readingCostream(Queue&lt;byteChunk&gt; queue, ManualResetEvent hasData)\n {\n _queue = queue;\n _hasData = hasData;\n }\n\n public override bool CanRead { get { return true; } }\n public override bool CanSeek { get { return false; } }\n public override bool CanWrite { get { return false; } }\n public override void Flush() { }\n public override long Length { get { throw new NotSupportedException(); } }\n public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } }\n public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }\n public override void SetLength(long value) { throw new NotSupportedException(); }\n public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }\n\n public override int Read(byte[] buffer, int offset, int count)\n {\n // If there is no data waiting to be read, wait for it.\n _hasData.WaitOne();\n\n byteChunk peeked;\n lock(_queue)\n peeked = _queue.Peek();\n\n // A null element in the queue signals the end of the stream. Don't dequeue this item.\n if (peeked == null)\n return 0;\n\n if (peeked.Count &lt;= count)\n {\n // If we can return the complete item, dequeue it\n Buffer.BlockCopy(peeked.Buffer, peeked.Offset, buffer, offset, peeked.Count);\n lock(_queue)\n {\n _queue.Dequeue();\n // If this has emptied the queue, tell the next call to read\n if (_queue.Count == 0)\n _hasData.Reset();\n }\n\n return peeked.Count;\n }\n\n // If we can only return part of the item, modify it accordingly\n Buffer.BlockCopy(peeked.Buffer, peeked.Offset, buffer, offset, count);\n peeked.Offset += count;\n peeked.Count -= count;\n return count;\n }\n }\n\n private sealed class writingCostream : Stream\n {\n private Queue&lt;byteChunk&gt; _queue;\n private ManualResetEvent _hasData;\n public writingCostream(Queue&lt;byteChunk&gt; queue, ManualResetEvent _hasData)\n {\n _queue = queue;\n _hasData = hasData;\n }\n\n public override bool CanRead { get { return false; } }\n public override bool CanSeek { get { return false; } }\n public override bool CanWrite { get { return true; } }\n public override void Flush() { }\n public override long Length { get { throw new NotSupportedException(); } }\n public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } }\n public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }\n public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); }\n public override void SetLength(long value) { throw new NotSupportedException(); }\n\n public override void Write(byte[] buffer, int offset, int count)\n {\n // Ignore zero-length writes\n if (count == 0)\n return;\n\n // We have to take a copy of the data because the calling thread might re-use the same buffer multiple times.\n var bufferCopy = new byte[count];\n Buffer.BlockCopy(buffer, offset, bufferCopy, 0, count);\n\n // Put the data in the queue\n lock (_queue)\n {\n _queue.Enqueue(new byteChunk { Buffer = bufferCopy, Offset = 0, Count = count });\n\n // Inform the reading thread that the queue now has data\n _hasData.Set();\n }\n }\n }\n}\n</code></pre>\n\n<p>A couple of other comments from a Review standpoint:</p>\n\n<ul>\n<li>Microsoft's Naming Standards for C# suggest that class names should be PascalCase</li>\n<li>You might also want to look at another <code>ManualResetEvent</code> for memory overloads - if Write gets called many times and you run out of memory, you may want to wait until Read has removed some data from the Queue, rather than failing with an <code>OutOfMemoryException</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T18:44:15.807", "Id": "1746", "Score": "0", "body": "I guess I can reduce the time spent inside a `lock` in my original to exactly the same as yours. Apart from that, what is the advantage of using `ManualResetEvent` over `Monitor.Pulse`?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T18:46:55.447", "Id": "1747", "Score": "0", "body": "(BTW your code is missing a `lock` around the call to `Peek`, which causes a subtle bug.)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T19:29:36.183", "Id": "1751", "Score": "0", "body": "@Timwi Using a ResetEvent is much easier to understand and manage. It's like a door in your code and you can only come through it if a certain condition is Set, which is exactly what you're trying to achieve. Using Wait and Pulse is different, it's using a complex dual queue system, making it buggy and fragile and leading to subtle situations like Write being locked out while Read completes. Plus, I don't think you can shorten your locks, at least not all of them" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T19:34:47.143", "Id": "1752", "Score": "0", "body": "I'm not sure why you'd need to lock the Queue to Peek at it, assuming there is only one Read thread (as I said, if you have more than one, you will have bigger problems to solve). As there must be one item in the Queue on the line before that, the first item will not change if the Write thread adds another item." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T22:22:58.713", "Id": "1754", "Score": "0", "body": "@pdr: You need a lock around the `Peek` because `Queue<T>` is not thread-safe and cannot handle it interleaving with a simultaneous `Enqueue`. In particular, if the `Enqueue` needs to grow the queue, which it does in `SetCapacity`, and the `Peek` happens after the `_array = destinationArray;` but before the `_head = 0;`, then `Peek` will return the wrong item." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T15:01:54.257", "Id": "1792", "Score": "0", "body": "Oh! You're right. I'd forgotten that. It's `queue.Synchronized` which is thread-safe, but that would cause unnecessary locking in all the other cases. I'll correct that." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-23T22:09:04.240", "Id": "959", "ParentId": "956", "Score": "5" } } ]
{ "AcceptedAnswerId": "959", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-23T18:31:05.457", "Id": "956", "Score": "7", "Tags": [ "c#", "multithreading", "thread-safety", "stream" ], "Title": "Implementation of costreams" }
956
<p>I have to generate a sequential number for <strong>groovy-grails</strong> app wide use and came up with the following. However, is there a better way to do this?</p> <p>Domain classes:</p> <pre><code>class RoastIdCounter { int counter =0 static constraints = { } } </code></pre> <p>This one has no views or controller associated with it. It's purely for db interaction in a service class.</p> <pre><code>class RoastId { Family family Integer nextId long timeCreated = new Date().time static constraints = { family() nextId() } static belongsTo = [ Family ] } class Family extends { String farmId; String welcome; String familyName; String ourFarm; String howMuchDoWeGetPaid; SortedSet pictureAlbums; SortedSet pictures; Integer pictureAlbumsCount = 0; Integer picturesCount = 0; Date dateCreated = new Date() Date lastUpdated = new Date() static hasMany = [ roastIds : RoastId, pictureAlbums : PictureAlbum, pictures : Picture ] static constraints = { farmId() familyName( ) welcome( widget:'textarea' ) ourFarm( widget:'textarea' ) howMuchDoWeGetPaid( widget:'textarea' ) dateCreated() lastUpdated() } String toString() { "$farmId - $familyName" } } // Family </code></pre> <p>Service class for dealing with the number generation:</p> <pre><code>class RoastIdCounterService { static transactional = true def getNextRoastId() { def ric = RoastIdCounter.list()[-1] if( ric != null ){ ric.lock() ric.counter = ric.counter + 1 ric.save() return ric.counter } else { return -1 } } } </code></pre> <p>Controller:</p> <p>Here I'm just sending the object all pre-populated:</p> <pre><code>def create = { def roastIdInstance = new RoastId() roastIdInstance.properties = params roastIdInstance.nextId = roastIdCounterService.getNextRoastId() return [roastIdInstance: roastIdInstance] } </code></pre> <p>Environment: Grails 1.3.7, PostgreSql 8.4</p> <p>Would there be a better way to do this? What potential problems am I overlooking?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-30T23:43:53.077", "Id": "68201", "Score": "0", "body": "Can you not simply declare the column in the db as auto increment?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T12:02:54.837", "Id": "68301", "Score": "0", "body": "Normally yes. I don't remember why exactly we opted not to do that though. I think we had to have it BEFORE persisting the details of the roast. It was not an ordinary ID column." } ]
[ { "body": "<p>Have you considered using an <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicLong.html\" rel=\"nofollow\">AtomicLong</a> instead of the RoastIdCounterService? You can then call <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicLong.html#incrementAndGet%28%29\" rel=\"nofollow\">AtomicLong.incrementAndGet()</a> to get the next value. The atomic long will take care of the locking required for safe concurrent access.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T20:18:24.650", "Id": "70255", "Score": "0", "body": "No, I don't think so, good point." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T19:56:05.263", "Id": "40997", "ParentId": "958", "Score": "3" } } ]
{ "AcceptedAnswerId": "40997", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-23T20:04:32.897", "Id": "958", "Score": "9", "Tags": [ "groovy", "grails" ], "Title": "Generating a sequential number for app-wide use" }
958
<p>I have a hierarchy of of groups, and I want to get a collection of all the lowest level groups (or leaves if we'll look at this as a tree).</p> <p>I wrote the following code. Is it inefficient?</p> <pre><code>public static class FeatureWeightGroupExtensions { public static IEnumerable&lt;IFeatureWeightGroup&gt; GetLeafGroups(this IFeatureWeightGroup featureWeightGroup) { return GetLeafGroupsRecursive(featureWeightGroup).ToList(); } private static IEnumerable&lt;IFeatureWeightGroup&gt; GetLeafGroupsRecursive(IFeatureWeightGroup featureWeightGroup) { if (!featureWeightGroup.ChildGroups.Any()) return Enumerable.Repeat(featureWeightGroup, 1); return featureWeightGroup.ChildGroups.Aggregate(Enumerable.Empty&lt;IFeatureWeightGroup&gt;(), (allGroups, group) =&gt; allGroups.Concat(GetLeafGroupsRecursive(group))); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T15:35:19.190", "Id": "1728", "Score": "1", "body": "Wow, I kept reading it as *feather weight* until I realised it says **feature** :-D" } ]
[ { "body": "<pre><code>return featureWeightGroup.ChildGroups.Aggregate(Enumerable.Empty&lt;IFeatureWeightGroup&gt;(),\n (allGroups, group) =&gt;\n allGroups.Concat(GetLeafGroupsRecursive(group)));\n</code></pre>\n\n<p>It looks like it can be replaced with: </p>\n\n<pre><code>return featureWeightGroup.ChildGroups\n .SelectMany(g =&gt; GetLeafGroupsRecursive(group));\n</code></pre>\n\n<p>Which probably will not be much better from performance point of view, but looks cleaner.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T15:36:45.960", "Id": "1729", "Score": "3", "body": "Actually it *would* be much better performance. The `Aggregate` version would instantiate many `Concat` iterators, which would constantly forward `MoveNext()` calls to each other, while your improvement instantiates only one `SelectMany` iterator." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T13:14:40.377", "Id": "969", "ParentId": "966", "Score": "5" } }, { "body": "<p>As already pointed out by <em>Snowbear</em> and my comment on his answer, you can improve the performance <em>and</em> readability by using <code>SelectMany</code> instead of <code>Concat</code>.</p>\n\n<p>However, I notice that you are using <code>ToList()</code> at the end anyway. This pulls into question the benefit of using LINQ and all those <code>SelectMany</code> iterators in the first place. Using LINQ sacrifices performance at the benefit of lazy evaluation, but you are not using the lazy-evaluation aspect. Therefore, if performance is what you are after, then don’t use LINQ that much:</p>\n\n<pre><code>public static class FeatureWeightGroupExtensions\n{\n public static IEnumerable&lt;IFeatureWeightGroup&gt; GetLeafGroups(this IFeatureWeightGroup featureWeightGroup)\n {\n var list = new List&lt;IFeatureWeightGroup&gt;();\n populateList(list, featureWeightGroup);\n return list;\n }\n\n private static void populateList(List&lt;IFeatureWeightGroup&gt; list, IFeatureWeightGroup featureWeightGroup)\n {\n if (!featureWeightGroup.ChildGroups.Any())\n list.Add(featureWeightGroup);\n else\n foreach (var childGroup in featureWeightGroup.ChildGroups)\n populateList(list, childGroup);\n }\n}\n</code></pre>\n\n<p>This is the most performance-optimised way I can think of, while at the same time also being significantly easier to read than the original <em>or</em> the <code>SelectMany</code> alternative.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T22:51:28.823", "Id": "1755", "Score": "0", "body": "+1 for the answer. -0.5 for lack of curly braces in your if and foreach statements (which still rounds up to +1). IMO, curly braces are never optional." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T20:08:43.690", "Id": "1803", "Score": "2", "body": "@Saeed: It’s totally fine for you to have that opinion, but try not to let that turn into intolerance of other people’s opinions." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T21:42:59.460", "Id": "1805", "Score": "0", "body": "last I checked, this is a code review forum where style comments are encouraged. I was merely pointing out that I don't agree with that style point in your answer, so my vote should not be seen as condoning it. Not sure how that qualifies as intolerance." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T02:11:06.163", "Id": "1809", "Score": "0", "body": "@Saeed: I’m just saying. No harm done. :) Thanks for the upvote, anyway!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T15:42:37.983", "Id": "973", "ParentId": "966", "Score": "5" } } ]
{ "AcceptedAnswerId": "969", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-24T10:04:59.017", "Id": "966", "Score": "5", "Tags": [ "c#", "linq", "recursion" ], "Title": "Is this Recursion + Linq example inefficient?" }
966
<p>I need to parse an invalid JSON string in which I find many repetitions of the same key, like the following snippet:</p> <pre><code>[...] "term" : {"Entry" : "value1", [.. other data ..]}, "term" : {"Entry" : "value2", [.. other data ..]}, [...] </code></pre> <p>I thought of appending a suffix to each key, and I do it using the following code:</p> <pre><code>word = "term" offending_string = '"term" : {"Entry"' replacing_string_template = '"%s_d" : {"Entry"' counter = 0 index = 0 while index != -1: # result is the string containing the JSON data index = result.find(offending_string, index) result = result.replace(offending_string, replacing_string_template % (word, counter), 1) counter += 1 </code></pre> <p>It works, but I'd like to know if it is a good approach and if you would do this in a different way.</p>
[]
[ { "body": "<pre><code>import json\n\ndef fixup(pairs):\n return pairs\n\ndecoded = json.loads(bad_json, object_pairs_hook = fixup)\n</code></pre>\n\n<p>object_pairs_hook is a more recent addition. If you have an older version of python you may not have it. The resulting python object will contain lists of pairs (including duplicates) rather then dictionaries. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T17:32:37.650", "Id": "1739", "Score": "0", "body": "+1 great! But I doubt it will work, because this code is deployed under Google App Engine, that uses an old version of python that doesn't even contain the json module. I have to `import simplejson as json` from django." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T17:36:53.890", "Id": "1740", "Score": "0", "body": "@Andrea, the current version of simplejson does support the object_pairs_hook. Even if Google App Engine doesn't have the latest version, you can probably download and install your own copy of simplejson for your project." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T17:19:37.210", "Id": "974", "ParentId": "968", "Score": "4" } } ]
{ "AcceptedAnswerId": "974", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T13:03:07.473", "Id": "968", "Score": "5", "Tags": [ "python", "parsing", "strings", "json" ], "Title": "Substitution of different occurrences of a string with changing patterns" }
968
<p>I'm quite new to JavaScript, and I'd like a review of the code structure and syntax. It serves <a href="http://florent2.github.com/test-regexp-online/" rel="nofollow">this little online regexp test</a> (still a work in progress).</p> <p>The whole code (JavaScript, CSS &amp; HTML) <a href="https://github.com/Florent2/test-regexp-online" rel="nofollow">is on GitHub</a>.</p> <p>application.js:</p> <pre><code>function update_result_for(input, regexp_value) { var input_value = input.val(); var result_spans = input.parent().children('span'); if(!input_value || !$('#regexp').val()) { result_spans.hide(); } else { var regexp = new RegExp(regexp_value); var result = regexp.exec(input_value); if(result) { var matched_string = result.shift(); var submatches_list_string = jQuery.map(result, function(submatch, index) { return '$' + (index + 1) + ' = ' + submatch; }).join('; '); var regexp_to_highlight_matched_string = new RegExp('(.*)' + matched_string + '(.*)'); var regexp_to_highlight_matched_string_result = regexp_to_highlight_matched_string.exec(input_value); var before_matched_string = regexp_to_highlight_matched_string_result[1]; var after_matched_string = regexp_to_highlight_matched_string_result[2]; var input_value_with_matched_string_highlighted = 'matched: ' + before_matched_string + '&lt;span class="matched"&gt;' + matched_string + '&lt;/span&gt;' + after_matched_string; result_spans.filter(".submatches").text(submatches_list_string); result_spans.filter(".match").html(input_value_with_matched_string_highlighted); result_spans.filter(".ok").show('fast'); result_spans.filter(".not_ok").hide(); } else { result_spans.filter(".not_ok").show('fast'); result_spans.filter(".ok").hide(); } } } // from http://www.scottklarr.com/topic/126/how-to-create-ctrl-key-shortcuts-in-javascript/ var isCtrl = false; $(document).keyup(function (e) { if(e.which === 17) isCtrl=false; }).keydown(function (e) { if(e.which === 17) isCtrl=true; if(e.which === 69 &amp;&amp; isCtrl) { $('#regexp').focus(); return false; } }); $(document).ready(function() { $('#regexp').focus(); $('span.result').hide(); $('input:not(#regexp)').live("keyup", function() { update_result_for($(this), $('#regexp').val()); }); $('input#regexp').keyup(function() { $('input:not(#regexp)').each(function(i) { update_result_for($(this), $('#regexp').val()); }); }); $('a.add_example').click(function() { new_example = $('div#examples p:last').clone(); new_example.children('input').attr('value', ''); new_example.children('span').hide(); new_example.insertBefore($(this)); new_example.children("input").focus(); }); }); </code></pre>
[]
[ { "body": "<p>This code looks fine to me for a toy project. I especially appreciate the long names for identifiers.</p>\n\n<p>Now, it could look better:</p>\n\n<ul>\n<li><p>with more comments. You should describe the intent (the why behind the how) and the expected use case for the function: type and range of values in parameters, one line to describe what it does, and one more paragraph for details if needed.</p></li>\n<li><p>my personal preference would be to use camelCase instead of underscore_between_words for long names. Although this is <a href=\"https://stackoverflow.com/questions/921133/javascript-naming-conventions\">open to discussion</a>.</p></li>\n<li><p>a little trick: end the if branch with <code>return;</code> to avoid nesting all remaining code in the else branch:</p>\n\n<pre><code>function update_result_for(input, regexp_value) {\n var input_value = input.val();\n var result_spans = input.parent().children('span'); \n if(!input_value || !$('#regexp').val()) {\n result_spans.hide();\n return; // return as soon as possible to avoid deep nesting\n }\n // no need for else\n var regexp = new RegExp(regexp_value);\n var result = regexp.exec(input_value);\n // ...\n}\n</code></pre></li>\n<li><p>in the same vein, treat exceptional cases first and normal cases after. This is a useful convention which helps the reader, and the exception handling is usually shorter (or should be extracted to a separate function if longer) which avoids long runs of nested code:</p>\n\n<pre><code>if (!result) {\n result_spans.filter(\".not_ok\").show('fast');\n result_spans.filter(\".ok\").hide();\n return;\n}\n// reduced nesting\nvar matched_string = result.shift();\n// ...\n</code></pre></li>\n<li><p>only use anonymous functions when you actually need a closure with access to the context: the intent of the function will be clearer with a name, you will avoid nesting, and may reuse the function more easily including for unit testing. There are many anonymous functions in your code, which makes it harder to understand:</p>\n\n<pre><code>function(submatch, index) {\n return '$' + (index + 1) + ' = ' + submatch;\n})\n\nfunction(e) {\n if(e.which === 17) isCtrl=false;\n}\n\nfunction(e) {\n if(e.which === 17) isCtrl=true;\n if(e.which === 69 &amp;&amp; isCtrl) {\n $('#regexp').focus(); \n return false;\n }\n})\n\nfunction() {\n $('#regexp').focus();\n $('span.result').hide();\n // ...\n}\n\nfunction() {\n update_result_for($(this), $('#regexp').val());\n}\n\nfunction() {\n $('input:not(#regexp)').each(function(i) {\n update_result_for($(this), $('#regexp').val());\n }); \n}\n\nfunction() {\n new_example = $('div#examples p:last').clone();\n new_example.children('input').attr('value', '');\n new_example.children('span').hide();\n new_example.insertBefore($(this));\n new_example.children(\"input\").focus();\n}\n</code></pre></li>\n<li><p>once you define more than one function, you should wrap your code in a closure to avoid cluttering the global namespace, following the <a href=\"http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth\" rel=\"nofollow noreferrer\">Module Pattern</a>:</p>\n\n<pre><code>(function(){\n // private scope for your code\n}());\n</code></pre></li>\n<li><p>break long lines to fit in about 80 characters to avoid the need for scrolling horizontally in typical console windows and in code areas on this site:</p>\n\n<pre><code>var regexp_to_highlight_matched_string =\n new RegExp('(.*)' + matched_string + '(.*)');\nvar regexp_to_highlight_matched_string_result =\n regexp_to_highlight_matched_string.exec(input_value);\nvar before_matched_string =\n regexp_to_highlight_matched_string_result[1];\nvar after_matched_string =\n regexp_to_highlight_matched_string_result[2];\nvar input_value_with_matched_string_highlighted =\n 'matched: ' +\n before_matched_string +\n '&lt;span class=\"matched\"&gt;' + matched_string + '&lt;/span&gt;' +\n after_matched_string;\n</code></pre></li>\n</ul>\n\n<p>To go further, my advice would be to read \"<a href=\"http://rads.stackoverflow.com/amzn/click/0596517742\" rel=\"nofollow noreferrer\">JavaScript: The Good Parts</a>\" and start using <a href=\"http://www.jslint.com/\" rel=\"nofollow noreferrer\">JSLint</a>, in this order: this is an enlightening experience on your way to mastering JavaScript. The other way round, using the tool without understanding the mindset of its author, is very frustrating.</p>\n\n<p>I ran JSLint on your code. It has one critical complaint hidden among hair splittings: the declaration of new_example is missing, it is therefore a global variable which is susceptible to result in unexpected bugs.</p>\n\n<pre><code> // var keyword added:\n var new_example = $('div#examples p:last').clone();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T15:58:47.807", "Id": "1860", "Score": "0", "body": "Merci beaucoup Éric ! That's exactly the kind of feedback I was looking for :) I've updated the code on GitHub with your advices, except for the anonymous functions I've not yet removed (I'll do that when I add tests). I had tried to use JSLind but you're right, it will be more understandable after I read the Good Parts." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T15:46:52.843", "Id": "1014", "ParentId": "972", "Score": "4" } }, { "body": "<p>Another tool you can use today:</p>\n\n<p>Google's own <strong><a href=\"http://code.google.com/closure/compiler/\" rel=\"nofollow\">Closure Compiler</a></strong> from Google, which is a tool for making JavaScript download and run faster. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what's left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.</p>\n\n<p>There's a <a href=\"http://closure-compiler.appspot.com\" rel=\"nofollow\">online version</a> of this tool too, a Firebug plugin, and is already part of <a href=\"http://code.google.com/speed/page-speed/\" rel=\"nofollow\">PageSpeed</a> and there's also a <a href=\"http://code.google.com/closure/utilities/\" rel=\"nofollow\">JavaScript Linter</a> as part of the <a href=\"http://code.google.com/closure/\" rel=\"nofollow\">Closure Tools</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-21T13:14:46.657", "Id": "1366", "ParentId": "972", "Score": "0" } } ]
{ "AcceptedAnswerId": "1014", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-24T15:41:31.883", "Id": "972", "Score": "7", "Tags": [ "javascript", "jquery" ], "Title": "JavaScript portion of regexp tester" }
972
<p>As I'm creating a 3D Tic-Tac-Toe game, I'm having several modules inside my JavaScript application. For example, there is a 3D module which handles perspective calculations, whereas a Multiplayer module manages everything with relation to online playing.</p> <p>Is it good practice to put functions of each module in its separate object?</p> <p>I currently have:</p> <p>multiplayer.js:</p> <pre><code>var Multiplayer = { socket: new Socket("ws://192.168.0.100:123/test"), // Relevant variables concerning multiplayer stuff createSession: function() { //... } } </code></pre> <p>renderer.js:</p> <pre><code>var Renderer = { f: 200, // Relevant variables concerning 3D rendering stuff g: 200; render: function() { //... } } </code></pre> <p>and so on.</p> <p>Is this a good practice of organising my project? Or is there a more efficient way?</p>
[]
[ { "body": "<p>I would recommend you use a closure like this:</p>\n\n<pre><code>var Obj = (function() {\n var privateState = null;\n return {\n A: 1,\n B: true,\n C: function() {\n return privateState; \n } \n };\n})();\n</code></pre>\n\n<p>The biggest reason why this is a good idea is that it adds the ability to keep private state within the closure. Normally you can define private properties by convention but as the complexity of an object increases the better it is to keep certain things private.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T06:39:21.577", "Id": "1762", "Score": "0", "body": "Looks less organised, but surely has its advantages." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T16:40:44.807", "Id": "1795", "Score": "0", "body": "@pimvdb - How so? One would think that allowing extra protection for your private state qualifies as improving organization." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T19:55:38.810", "Id": "1801", "Score": "0", "body": "That's true, but just defining a module as `var someModule = { ... }` is clearer in my opinion. Nevertheless, I'm going to use the closure way - thanks." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T19:58:39.320", "Id": "1802", "Score": "0", "body": "@pimvdb - Oh I see, you are thinking more in terms of clarity rather than a literal interpretation of organized." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T18:38:17.540", "Id": "976", "ParentId": "975", "Score": "7" } }, { "body": "<p>I chose for the closures: <a href=\"http://jsfiddle.net/raXQT/4/\" rel=\"nofollow\">http://jsfiddle.net/raXQT/4/</a>.</p>\n\n<p>Now it's possible to safely and more easily access variables. Also I love the fact that Chrome supports JavaScript getters and setters like this (it's going to be Chrome-only anyway).</p>\n\n<pre><code>var t=(function() {\n var a = 0;\n return {\n get val() {\n return a;\n },\n set val(v) {\n a = v;\n },\n alertA: function() {\n window.alert(\"alertA() shows a: \" + a);\n }\n }\n})();\n\nalert(\"t.val: \" + t.val);\nt.val = 2;\nalert(\"t.val = 2\\n\\nt.val: \" + t.val);\nt.alertA();\nt.a = 6;\nalert(\"t.a = 6\\n\\nt.val: \" + t.val);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T10:42:21.720", "Id": "1051", "ParentId": "975", "Score": "1" } } ]
{ "AcceptedAnswerId": "976", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-24T18:30:22.743", "Id": "975", "Score": "10", "Tags": [ "javascript" ], "Title": "Separating and organising modules with objects?" }
975
<p>I am building a query that could end up look like this:</p> <pre><code>SELECT "patients".* FROM "patients" INNER JOIN "users" ON "users"."id" = "patients"."user_id" WHERE (users.username LIKE '%Bob%' AND users.last_name LIKE '%Smith%' AND users.active = '1' AND users.disabled = '1') ORDER BY users.first_name DESC LIMIT 10 OFFSET 0 </code></pre> <p>Below is code to create a complex query such as:</p> <pre><code>conditions = [] where = '' where_parameters = [] order = 'users.last_name ASC' per_page = 20 if is_admin? if defined?(params[:username]) and !params[:username].blank? where += 'users.username LIKE ? AND ' where_parameters.push("%#{params[:username]}%") end if defined?(params[:last_name]) and !params[:last_name].blank? where += 'users.last_name LIKE ? AND ' where_parameters.push("%#{params[:last_name]}%") end if defined?(params[:active]) and !params[:active].blank? where += 'users.active = ? AND ' where_parameters.push(params[:active]) end if defined?(params[:disabled]) and !params[:disabled].blank? where += 'users.disabled = ? AND ' where_parameters.push(params[:disabled]) end if !where.empty? where = where[0, where.length - 5] conditions = [where, *where_parameters] end if defined?(params[:order_by]) and !params[:order_by].blank? order = params[:order_by] + ' ' end if defined?(params[:order]) and !params[:order].blank? order += params[:order] end if defined?(params[:per_page]) and !params[:per_page].blank? per_page = params[:per_page].to_i end @patients = Patient.joins(:user).paginate(:all, :include =&gt;:user, :conditions =&gt; conditions, :order =&gt; order, :page =&gt; params[:page], :per_page =&gt; per_page) </code></pre> <p>Is there a better way to do this, this is just ugly?</p>
[]
[ { "body": "<p>First of all be very careful when building queries from request data. When building your <code>where</code> string, you're using parametrized queries, so that's fine. But in your <code>order</code> string, you're building actual SQL code from data you directly take out of <code>params</code>. Do NOT do that. This is a big risk of SQL injection.</p>\n\n<p>What you should do instead is take the order string apart (splitting at the comma), then check that each element is a column name optionally followed by <code>ASC</code> or <code>DESC</code>, then put the string back together accordingly.</p>\n\n<p>A method for this could look something like this:</p>\n\n<pre><code>def safe_order_from_param(collection, order_string)\n tokens = order_string.split(/ *, */)\n tokens.each do |token|\n column, direction = token.match(/^(\\w+)(? +(\\w+))?$/).captures\n if Patient.column_names.include? column\n # if direction is nil, it will just be turned into the empty\n # string, so no problem there\n collection = collection.order(\"#{column} #{direction}\")\n else\n raise ArgumentError, \"No such column: #{column}\"\n end\n end\nend\n</code></pre>\n\n<hr>\n\n<p>Second of all <code>defined?(params[:foo])</code> does is check that <code>params</code> is defined. It does <em>not</em> check that <code>params</code> is a hash and has the key <code>:foo</code>. Since <code>params</code> will always exist, there really is no need for the check. Checking <code>params[:foo].blank?</code> is entirely sufficient.</p>\n\n<hr>\n\n<p>Now to the main part of your question: the ugly building of the query string:</p>\n\n<p>I assume from the fact that you're using the <code>joins</code> method that this is rails 3. In rails 3 options like <code>:include</code>, <code>:conditions</code> and <code>:order</code> are deprecated in favor of the corresponding query methods. The beauty of those methods is that they're chainable. So instead of building a query string using concatenation, it is much cleaner to just chain together multiple <code>where</code>s.</p>\n\n<pre><code>if is_admin?\n @patients = Patient.joins(:user).includes(:user).order('users.last_name ASC')\n\n unless params[:username].blank?\n @patients = @patients.where(\"users.username LIKE ?\", params[:username])\n end\n\n # same for :last_name\n\n unless params[:active].blank?\n @patients = @patients.where(\"users.active\" =&gt; params[:active])\n end\n\n # same for disabled\n\n unless params[:order_by].blank?\n @patients = safe_order_from_param(@patients, params[:order_by])\n end\n\n # same for order\n\n per_page = params[:per_page].blank? ? 20 : params[:per_page].to_i\n @patients = @patients.paginate(:page =&gt; params[:page], :per_page =&gt; per_page)\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T00:13:44.240", "Id": "1757", "Score": "0", "body": "Thank you! that was very helpful! What would I do in the case that I wanted to OR instead of AND? I guess I am probably in trouble..." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T00:17:00.337", "Id": "1759", "Score": "1", "body": "@chris: Yes, if you want `OR`, you can't just chain `where`s. However you can still improve your string concatenation method by building an array instead of a string and then using `join(' OR ')` on it. That way you don't have to remove the trailing `OR` at the end like you're doing now with `AND`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T23:53:04.243", "Id": "979", "ParentId": "977", "Score": "8" } } ]
{ "AcceptedAnswerId": "979", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-24T22:49:56.587", "Id": "977", "Score": "5", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Ruby on rails complex select statement...there has to be a better way!" }
977
<pre><code>&lt;% i = 0 %&gt; &lt;% @patients.each do |patient| %&gt; &lt;tr class="&lt;%= i % 2 == 0 ? 'Even' : 'Odd' %&gt;"&gt; &lt;td&gt;&lt;%= link_to patient.id, patient %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= patient.user.username %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= patient.user.first_name %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= patient.user.last_name %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= patient.user.email %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= patient.user.active %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= patient.user.disabled %&gt;&lt;/td&gt; &lt;td&gt; &lt;ul class="Horizlist"&gt; &lt;li&gt;&lt;%= link_to 'Detail', patient %&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/td&gt; &lt;/tr&gt; &lt;% i += 1 %&gt; </code></pre> <p>I don't like that I have to define an i variable, is there a better way?</p>
[]
[ { "body": "<p>First of all ruby has an <code>each_with_index</code> method, so you can do <code>@patients.each_with_index do |patient, i|</code> instead of keeping a counter manually.</p>\n\n<p>However with the conditional inside the loop that is still too much logic for the view in my opinion. What I'd do is define a helper for this, which might look like this:</p>\n\n<pre><code># For each item in the given collection, yield that item and embed the\n# result in the given tag. The class attribute of that tag alternates\n# between class1 and class2\ndef alternating(collection, tag, class1, class2, html =&gt; {})\n collection.each_with_index do |item, i|\n html[:class] = i % 2 == 0 ? class1 : class2\n content_tag(tag, html, false) do\n yield item\n end\n end\nend\n</code></pre>\n\n<p>And then call it like this:</p>\n\n<pre><code>&lt;% alternating(@patients, :tr, 'Even', 'Odd') do |patient| %&gt; \n &lt;td&gt;&lt;%= link_to patient.id, patient %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= patient.user.username %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= patient.user.first_name %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= patient.user.last_name %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= patient.user.email %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= patient.user.active %&gt;&lt;/td&gt;\n &lt;td&gt;&lt;%= patient.user.disabled %&gt;&lt;/td&gt;\n &lt;td&gt;\n &lt;ul class=\"Horizlist\"&gt;\n &lt;li&gt;&lt;%= link_to 'Detail', patient %&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/td&gt;\n&lt;% end %&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T00:06:25.737", "Id": "980", "ParentId": "978", "Score": "3" } }, { "body": "<p>Rails has a built in method, <a href=\"http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-cycle\"><code>cycle</code></a>, which will cycle between two more more options for you, so you don't have to manage the \"Even\"/\"Odd\" selection.</p>\n\n<pre><code>&lt;% @patients.each do |patient| %&gt;\n &lt;%= content_tag :tr, :class =&gt; cycle('Even', 'Odd') do %&gt;\n &lt;%= content_tag :td, link_to(patient.id, patient) %&gt;\n &lt;% [:username, :first_name, :last_name, :email, :active, :disabled].each do |property| %&gt;\n &lt;%= content_tag :td, patient.user.send(property) %&gt;\n &lt;% end %&gt;\n &lt;td&gt;\n &lt;ul class=\"Horizlist\"&gt;\n &lt;%= content_tag :li, link_to('Detail', patient) %&gt;\n &lt;/ul&gt;\n &lt;/td&gt;\n &lt;% end %&gt;\n&lt;% end %&gt;\n</code></pre>\n\n<p>If you happen to use Haml, it looks quite nice. :)</p>\n\n<pre><code>- @patients.each do |patient|\n %tr{:class =&gt; cycle('Even', 'Odd')}\n %td= link_to(patient.id, patient)\n - [:username, :first_name, :last_name, :email, :active, :disabled].each do |property|\n %td= patient.user.send(property)\n %td\n %ul.Horizlist\n %li= link_to('Detail', patient)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T10:08:33.117", "Id": "1784", "Score": "0", "body": "Damn, how did I not know that? This is of course better than defining your own helper. +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-31T19:43:39.067", "Id": "13311", "Score": "0", "body": "Also, if this is just for styling purposes: [you can do that with CSS without `class`es](http://www.w3.org/Style/Examples/007/evenodd.en.html)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T05:14:49.333", "Id": "982", "ParentId": "978", "Score": "12" } } ]
{ "AcceptedAnswerId": "982", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-24T23:18:49.393", "Id": "978", "Score": "6", "Tags": [ "ruby", "html", "ruby-on-rails" ], "Title": "Rails view to list users in a zebra-striped table" }
978
<p>Basically, I'm uploading an excel file and parsing the information then displaying what was parsed in a view.</p> <pre><code>using System.Data; using System.Data.OleDb; using System.Web; using System.Web.Mvc; using QuimizaReportes.Models; using System.Collections.Generic; using System; namespace QuimizaReportes.Controllers { public class UploadController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(HttpPostedFileBase excelFile) { if (excelFile != null) { //Save the uploaded file to the disc. string savedFileName = "~/UploadedExcelDocuments/" + excelFile.FileName; excelFile.SaveAs(Server.MapPath(savedFileName)); //Create a connection string to access the Excel file using the ACE provider. //This is for Excel 2007. 2003 uses an older driver. var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;", Server.MapPath(savedFileName)); //Fill the dataset with information from the Hoja1 worksheet. var adapter = new OleDbDataAdapter("SELECT * FROM [Hoja1$]", connectionString); var ds = new DataSet(); adapter.Fill(ds, "results"); DataTable data = ds.Tables["results"]; var people = new List&lt;Person&gt;(); for (int i = 0; i &lt; data.Rows.Count - 1; i++) { Person newPerson = new Person(); newPerson.Id = data.Rows[i].Field&lt;double?&gt;("Id"); newPerson.Name = data.Rows[i].Field&lt;string&gt;("Name"); newPerson.LastName = data.Rows[i].Field&lt;string&gt;("LastName"); newPerson.DateOfBirth = data.Rows[i].Field&lt;DateTime?&gt;("DateOfBirth"); people.Add(newPerson); } return View("UploadComplete", people); } return RedirectToAction("Error", "Upload"); } public ActionResult Error() { return View(); } } } </code></pre> <p>Not feeling so confident this is the best approach. Any suggestion any of you MVC3 vets have for this aspiring senior programmer? :)</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T02:26:26.883", "Id": "1761", "Score": "0", "body": "Should I call another Action, \"UploadComplete\" and **have that** callthe UploadComplete view instead of calling a View directly from the [POST]Index action? When do I know whether to use one approach or the other?" } ]
[ { "body": "<p>The logic for reading the Excel file (i.e. everything from <code>var connectionString</code> until before the <code>return</code>) belongs in a model method, not the controller.</p>\n\n<p>You might also want to handle the case when the uploaded file isn't an Excel file or it doesn't have the columns you expect it to. Depending on how you use this or who uses it, this might not be necessary, but if normal users are allowed to upload files, they might very well upload the wrong file even if you tell them not to. And in that case a meaningful error message leads to a better user experience.</p>\n\n<p>Regarding the question in your comment: As I said, I don't know how this is going to be used, but I can't think of a situation where it would be helpful for the user to be able to re-upload the file by hitting the refresh button. So yes, redirecting to an <code>UploadComplete</code> action makes sense.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T10:34:02.353", "Id": "987", "ParentId": "981", "Score": "10" } }, { "body": "<p>What I like to do is create <code>Service</code> classes for my controllers. For your example, I'd do something like this:</p>\n\n<p><strong>UploadControllerService</strong></p>\n\n<pre><code>public class UploadControllerService\n{\n public IList&lt;Person&gt; GetPeopleFromFile(HttpPostedFileBase excelFile, HttpServerUtilityBase server)\n {\n if (excelFile == null)\n {\n return null;\n }\n\n string savedFileName = SaveFileToDisk(excelFile, server);\n\n // Create a connection string to access the Excel file using the ACE provider.\n // This is for Excel 2007. 2003 uses an older driver.\n string connectionString = CreateConnectionString(server, savedFileName);\n\n var people = GetPeopleDataFromFile(connectionString);\n\n return people;\n }\n\n private static string SaveFileToDisk(HttpPostedFileBase excelFile, HttpServerUtilityBase server)\n {\n string savedFileName = \"~/UploadedExcelDocuments/\" + excelFile.FileName;\n\n excelFile.SaveAs(server.MapPath(savedFileName));\n\n return savedFileName;\n }\n\n private static string CreateConnectionString(HttpServerUtilityBase server, string savedFileName)\n {\n return string.Format(\"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0;\", server.MapPath(savedFileName));\n }\n\n private static IList&lt;Person&gt; GetPeopleDataFromFile(string connectionString)\n {\n DataSet ds = new DataSet();\n\n using (var adapter = new OleDbDataAdapter(\"SELECT * FROM [Hoja1$]\", connectionString))\n {\n adapter.Fill(ds, \"results\");\n }\n\n DataTable data = ds.Tables[\"results\"];\n\n var people = new List&lt;Person&gt;();\n\n for (int i = 0; i &lt; data.Rows.Count - 1; i++)\n {\n Person newPerson = new Person\n {\n Id = data.Rows[i].Field&lt;double?&gt;(\"Id\"),\n Name = data.Rows[i].Field&lt;string&gt;(\"Name\"),\n LastName = data.Rows[i].Field&lt;string&gt;(\"LastName\"),\n DateOfBirth = data.Rows[i].Field&lt;DateTime?&gt;(\"DateOfBirth\")\n };\n\n people.Add(newPerson);\n }\n\n return people;\n }\n}\n</code></pre>\n\n<p><strong>Upload Controller</strong></p>\n\n<pre><code>public partial class UploadController : Controller\n{\n private readonly UploadControllerService uploadControllerService;\n\n public UploadController(UploadControllerService uploadControllerService)\n {\n this.uploadControllerService = uploadControllerService;\n }\n\n public UploadController()\n {\n // Or this if you're not using Dependency Injection.\n uploadControllerService = new UploadControllerService();\n }\n\n [HttpPost]\n public virtual ActionResult Index(HttpPostedFileBase excelFile)\n {\n var people = this.HomeControllerService.GetPeopleFromFile(excelFile, this.Server);\n\n if (people == null)\n {\n return this.View(\"Error\", \"Upload\");\n }\n\n return View(\"UploadComplete\", people);\n }\n}\n</code></pre>\n\n<p>I like to keep my controllers as lean as possible, and using <code>Service</code> classes has helped me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-07T21:51:44.817", "Id": "3949", "ParentId": "981", "Score": "8" } }, { "body": "<p>I would look at seperating the different modules out much like Jason and sepp2k have already mentioned. Your controller action seems to have way too much different knowledge so I would try and seperate the responsibilities out. I like to think of the controller as having no knowledge on how something is done but knows what to use in order to get it done.</p>\n\n<ol>\n<li>Data access for reading excel file, containing the connection string details etc</li>\n<li>Logic for reading from a data source and building your model</li>\n<li>Logic for taking your model and putting it in a format for supplying back to the view (only really if your using viewmodels)</li>\n</ol>\n\n<p>Each of these would be provide a different service and so you should be able to provide specific unit tests for each different functionality provided.</p>\n\n<p>The controller then just needs to put all the pieces together.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-09T05:41:56.253", "Id": "3980", "ParentId": "981", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T02:25:03.077", "Id": "981", "Score": "6", "Tags": [ "c#", "mvc", "asp.net-mvc-3", "controller" ], "Title": "Not feeling 100% about my Controller design." }
981
<p>I am been using a code pattern for recursive database actions in my applications.</p> <p>I create two class objects of a database table, singular one (e.g Agent) for holding single record with all fields definition, plural one (e.g Agents) for database actions of that records like, select, insert, delete, update etc. I find it easy using the code pattern.</p> <p>But as the time runs I find it somewhat laborious to define same database action functions in different classes only differing in datatype.</p> <p>How can I make it good and avoid defining it again and again?</p> <p>Sample code of a class file representing the class definition:</p> <pre class="lang-vb prettyprint-override"><code>Imports EssenceDBLayer Public Class Booking #Region "Constants" Public Shared _Pre As String = "bk01" Public Shared _Table As String = "bookings" #End Region #Region " Instance Variables " Private _UIN As Integer = 0 Private _Title As String = "" Private _Email As String = "" Private _contactPerson As String = "" Private _Telephone As String = "" Private _Mobile As String = "" Private _Address As String = "" Private _LastBalance As Double = 0 #End Region #Region " Constructor " Public Sub New() 'Do nothing as all private variables has been initiated' End Sub Public Sub New(ByVal DataRow As DataRow) _UIN = CInt(DataRow.Item(_Pre &amp; "UIN")) _Title = CStr(DataRow.Item(_Pre &amp; "Title")) _Email = CStr(DataRow.Item(_Pre &amp; "Email")) _contactPerson = CStr(DataRow.Item(_Pre &amp; "contact_person")) _Telephone = CStr(DataRow.Item(_Pre &amp; "Telephone")) _Mobile = CStr(DataRow.Item(_Pre &amp; "Mobile")) _Address = CStr(DataRow.Item(_Pre &amp; "Address")) _LastBalance = CDbl(DataRow.Item(_Pre &amp; "Last_Balance")) End Sub #End Region #Region " Properties " Public Property UIN() As Integer Get Return _UIN End Get Set(ByVal value As Integer) _UIN = value End Set End Property Public Property Title() As String Get Return _Title End Get Set(ByVal value As String) _Title = value End Set End Property Public Property Email() As String Get Return _Email End Get Set(ByVal value As String) _Email = value End Set End Property Public Property ContactPerson() As String Get Return _contactPerson End Get Set(ByVal value As String) _contactPerson = value End Set End Property Public Property Telephone() As String Get Return _Telephone End Get Set(ByVal value As String) _Telephone = value End Set End Property Public Property Mobile() As String Get Return _Mobile End Get Set(ByVal value As String) _Mobile = value End Set End Property Public Property Address() As String Get Return _Address End Get Set(ByVal value As String) _Address = value End Set End Property Public Property LastBalance() As Double Get Return _LastBalance End Get Set(ByVal value As Double) _LastBalance = value End Set End Property #End Region #Region " Methods " Public Sub [Get](ByRef DataRow As DataRow) DataRow(_Pre &amp; "Title") = _Title DataRow(_Pre &amp; "Email") = _Email DataRow(_Pre &amp; "Contact_person") = _contactPerson DataRow(_Pre &amp; "Telephone") = _Telephone DataRow(_Pre &amp; "Mobile") = _Mobile DataRow(_Pre &amp; "Address") = _Address DataRow(_Pre &amp; "last_balance") = _LastBalance End Sub #End Region End Class Public Class Bookings Inherits DBLayer #Region "Constants" Public Shared _Pre As String = "bk01" Public Shared _Table As String = "bookings" #End Region #Region " Standard Methods " Public Shared Function GetData() As List(Of Booking) Dim QueryString As String = String.Format("SELECT * FROM {0}{1} ORDER BY {0}UIN;", _Pre, _Table) Dim Dataset As DataSet = New DataSet() Dim DataList As List(Of Booking) = New List(Of Booking) Try Dataset = Query(QueryString) For Each DataRow As DataRow In Dataset.Tables(0).Rows DataList.Add(New Booking(DataRow)) Next Catch ex As Exception DataList = Nothing SystemErrors.Create(New SystemError(ex.Message, ex.StackTrace)) End Try Return DataList End Function Public Shared Function GetData(ByVal uin As String) As Booking Dim QueryString As String = String.Format("SELECT * FROM {0}{1} WHERE {0}uin = {2};", _Pre, _Table, uin) Dim Dataset As DataSet = New DataSet() Dim Data As Booking = New Booking() Try Dataset = Query(QueryString) If Dataset.Tables(0).Rows.Count = 1 Then Data = New Booking(Dataset.Tables(0).Rows(0)) Else Data = Nothing End If Catch ex As Exception Data = Nothing SystemErrors.Create(New SystemError(ex.Message, ex.StackTrace)) End Try Return Data End Function Public Shared Function Create(ByVal Data As Booking) As Boolean Dim QueryString As String = String.Format("SELECT * FROM {0}{1} WHERE {0}uin = Null;", _Pre, _Table) Dim Dataset As DataSet = New DataSet() Dim Datarow As DataRow Dim Result As Boolean = False Try Dataset = Query(QueryString) If Dataset.Tables(0).Rows.Count = 0 Then Datarow = Dataset.Tables(0).NewRow() Data.Get(Datarow) Dataset.Tables(0).Rows.Add(Datarow) Result = UpdateDB(QueryString, Dataset) Else Result = False End If Catch ex As Exception Result = False SystemErrors.Create(New SystemError(ex.Message, ex.StackTrace)) End Try Return Result End Function Public Shared Function Update(ByVal Data As Booking) As Boolean Dim QueryString As String = String.Format("SELECT * FROM {0}{1} WHERE {0}uin = {2};", _Pre, _Table, Data.UIN) Dim Dataset As DataSet = New DataSet() Dim Result As Boolean = False Dim DataRow As DataRow = Nothing Try Dataset = Query(QueryString) If Dataset.Tables(0).Rows.Count = 1 Then DataRow = Dataset.Tables(0).Rows(0) Data.Get(DataRow) Result = UpdateDB(QueryString, Dataset) Else Result = False End If Catch ex As Exception Result = False SystemErrors.Create(New SystemError(ex.Message, ex.StackTrace)) End Try Return Result End Function Public Shared Function UpdateBulk(ByRef DataList As List(Of Booking)) As Boolean Dim Result As Boolean = False Try For Each Data As Booking In DataList Update(Data) Next Result = True Catch ex As Exception SystemErrors.Create(New SystemError(ex.Message, ex.StackTrace)) End Try Return Result End Function Public Shared Function FillGrid() As List(Of Booking) Return GetData() End Function #End Region End Class </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-02T13:58:13.827", "Id": "16819", "Score": "1", "body": "Just for clean up: 1. to see how to do generics in VB.Net ( see http://msdn.microsoft.com/en-us/library/w256ka79(v=vs.100).aspx ) and 2. if you would KoolKabin, if you believe pdr's answer about ORM is the solution to your question, please click accept answer." } ]
[ { "body": "<p>What you're talking about is called object-relational mapping.</p>\n\n<p>You could do this, but it will be a fair amount of effort. Luckily many people have run into this same question before, answered it and open-sourced that solution. I suggest looking at using one of those solutions.</p>\n\n<p><a href=\"http://www.nhibernate.com/\" rel=\"noreferrer\">nHibernate</a> is just one example but is a popular and mature solution.</p>\n\n<p>Edit: More accurately, object-relational mapping is mapping fields to columns, objects to tables and object relationships to table relationships, so it does exactly what you want and (optionally) much more.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T20:26:49.653", "Id": "998", "ParentId": "984", "Score": "5" } }, { "body": "<p>To add a little to PDR's answer, since you have mentioned VB.NET, if you're using .NET 3.5 or higher you can use the <a href=\"https://msdn.microsoft.com/en-gb/data/ef.aspx\" rel=\"nofollow\">Entity Framework</a> to generate all of the basic classes and the supporting CRUD methods of those classes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T03:11:47.000", "Id": "1811", "Score": "0", "body": "its greatful when we have some of your favourite site link for information on Entity Framework" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-01T04:57:42.657", "Id": "160271", "Score": "0", "body": "http://www.nuget.org/packages/EntityFramework/5.0.0" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-25T20:36:24.210", "Id": "999", "ParentId": "984", "Score": "4" } } ]
{ "AcceptedAnswerId": "998", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-25T06:24:22.873", "Id": "984", "Score": "7", "Tags": [ "object-oriented", ".net", "database", "vb.net" ], "Title": "Recursive database actions" }
984
<p>I generally encounter a lot of <code>if</code>/<code>else</code>. I would like to get some suggestions on my code:</p> <pre><code>if( $blnLogged &amp;&amp; isset( $_POST['postReview'] ) ) { if( $_SESSION['REVIEW']['SUBMITTED'] != '' ) { $arrSharedData['blnRetSave'] = $_SESSION['REVIEW']['SUBMITTED']; $blnShowForm = false; $blnReviewPosted = true; }else{ if( $arrData['captcha'] != $_SESSION['REVIEW']['CODE'] ) { $strErrMsg = 'Invalid Captcha Code...'; }else{ if( empty( $arrData['review_title'] ) || empty( $arrData[ 'review_description' ] ) || empty( $arrData[ 'overall_review' ] ) || empty( $arrData[ 'cleanliness' ] ) || empty( $arrData[ 'facilities' ] ) || empty( $arrData[ 'location' ] ) || empty( $arrData[ 'quality_of_service' ] ) || empty( $arrData[ 'room' ] ) || empty( $arrData[ 'value_of_money' ]) ) { $strErrMsg = 'Required field missing...'; }else{ //do we need any processing... $arrData['business_id'] = $bID; $arrData['client_id'] = $_SESSION['site_user']; $arrData['website_id'] = WEBSITE_ID; $arrData['review_date'] = date('Y-m-d'); //If field Transformation required do it... $objTripReview = SM_Loader::loadClass('Class_Reviews'); $blnRetSave = $objTripReview-&gt;saveReview( $arrData ); $_SESSION['REVIEW']['SUBMITTED'] = $blnRetSave; $arrSharedData['blnRetSave'] = $_SESSION['REVIEW']['SUBMITTED']; $blnShowForm = false; $blnReviewPosted = true; } } } } if( $blnShowForm === true ) { $_SESSION['REVIEW']['CODE'] = rand(9999,99999); $_SESSION['Review']['SUBMITTED'] = ''; } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T08:05:50.150", "Id": "1765", "Score": "0", "body": "For a minor readability improvement you can omit `=== true` since you control `$blnShowForm` and `!= ''` if `$_SESSION['REVIEW']['SUBMITTED']` will always be a string or `null`." } ]
[ { "body": "<p>One simple way to improve this is to package it in a function, and return (or throw an exception) after each <code>$strErrMsg = ...</code> line. This will flatten the function, and allow you to put the main functionality at the \"top level\" of the function.</p>\n\n<p>Even better might be to move all the validation code to a separate function that throws an exception, and then handle it in the function that called it with the wrong parameters.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T07:45:08.297", "Id": "986", "ParentId": "985", "Score": "6" } }, { "body": "<p>Instead of</p>\n\n<pre><code>if (x)\n{\n // ...\n}\nelse\n{\n if (y)\n {\n // ...\n }\n}\n</code></pre>\n\n<p>you can just write</p>\n\n<pre><code>if (x)\n{\n // ...\n}\nelse if (y)\n{\n // ...\n}\n</code></pre>\n\n<p>In addition to that, I would put the list of required fields in an array somewhere where it is easily maintainable, so it’s not buried somewhere deep in the complex code:</p>\n\n<pre><code>$requiredFields = array( 'review_title', 'review_description',\n 'overall_review', 'cleanliness', 'facilities', 'location',\n 'quality_of_service', 'room', 'value_of_money' );\n</code></pre>\n\n<p>Then your code will look like this:</p>\n\n<pre><code>if( $blnLogged &amp;&amp; isset( $_POST['postReview'] ) )\n{\n $requiredFieldsPresent = true;\n foreach( $requiredFields as $field )\n if( empty( $arrData[$field] ) )\n $requiredFieldsPresent = false;\n\n if( $_SESSION['REVIEW']['SUBMITTED'] != '' )\n {\n $arrSharedData['blnRetSave'] = $_SESSION['REVIEW']['SUBMITTED'];\n $blnShowForm = false;\n $blnReviewPosted = true;\n }\n else if( $arrData['captcha'] != $_SESSION['REVIEW']['CODE'] )\n {\n $strErrMsg = 'Invalid Captcha Code...';\n }\n else if( !$requiredFieldsPresent )\n {\n $strErrMsg = 'Required field missing...';\n }\n else\n {\n // do we need any processing...\n // etc.\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T14:10:18.647", "Id": "989", "ParentId": "985", "Score": "4" } } ]
{ "AcceptedAnswerId": "986", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-25T06:46:56.983", "Id": "985", "Score": "4", "Tags": [ "php" ], "Title": "Submitting client reviews" }
985
<p>This class handles HTTP requests. It's a singleton class that parses URI to get the controller, method and parameters and then executes the controller's method.</p> <p>Maybe <code>parseUri</code> should be in another class and maybe there is too much responsibility for this class.</p> <p>I know that it can be improved. The execute method could be better because there are some repeated code.</p> <pre><code>&lt;?php class Request { private static $_instance; private $_host; private $_request_uri; private $_script_name; private $_controller; private $_method; private $_parameters; private $_headers; private function __construct() { $this-&gt;_host = $_SERVER['HTTP_HOST']; $this-&gt;_request_uri = $_SERVER['REQUEST_URI']; $this-&gt;_script_name = $_SERVER['SCRIPT_NAME']; $this-&gt;_headers = array(); $this-&gt;_parseUri(); } private function _parseUri() { /* In 'http://www.example.com/foo/bar/' get the '/foo/bar/' part */ $part = str_replace( dirname($this-&gt;_script_name), '', $this-&gt;_request_uri ); /* break it into chunks and clean up empty positions */ $chunks = explode('/', $part); $chunks = array_filter($chunks); if (count($chunks)) { if ($this-&gt;_controller = array_shift($chunks)) { $this-&gt;_controller = ucfirst($this-&gt;_controller) . '_Controller'; } if ($this-&gt;_method = array_shift($chunks)) { $this-&gt;_method = ucfirst($this-&gt;_method) . 'Action'; } $this-&gt;_parameters = $chunks ? $chunks : null; } } private function _send_headers() { foreach($this-&gt;_headers as $header) { header($header); } } public static function instance() { if (!self::$_instance) { self::$_instance = new Request(); } return self::$_instance; } public function execute() { /* There is a controller ... */ if (!empty($this-&gt;_controller)) { if (!class_exists($this-&gt;_controller, true)) { array_push($this-&gt;_headers, 'HTTP/1.1 404 Not Found'); $this-&gt;_send_headers(); return; } $controller = new $this-&gt;_controller(); /* ... and a method */ if ($this-&gt;_method) { if (!method_exists($controller, $this-&gt;_method)) { array_push($this-&gt;_headers, 'HTTP/1.1 404 Not Found'); $this-&gt;_send_headers(); return; } $method = new ReflectionMethod( $controller, $this-&gt;_method ); /* Do we have parameters? Let's call the right method */ $this-&gt;_parameters ? $method-&gt;invokeArgs($controller, $this-&gt;_parameters) : $method-&gt;invoke($controller); array_push($this-&gt;_headers, 'HTTP/1.1 200 OK'); $this-&gt;_send_headers(); } /* we don't have a method here, let's call the 'index_action' method */ else { $method = new ReflectionMethod($controller, 'indexAction'); $method-&gt;invoke($controller); array_push($this-&gt;_headers, 'HTTP/1.1 200 OK'); $this-&gt;_send_headers(); } } /* We don't have a Controller, let's call the default one. */ else { if (!class_exists('Default_Controller', true)) { throw new RequestException("'Default_Controller' class not found."); } $controller = new Default_Controller(); if (!method_exists($controller, 'indexAction')) { throw new RequestException( "'indexAction' method not found in 'Default_Controller' class." ); } $method = new ReflectionMethod($controller, 'indexAction'); $method-&gt;invoke($controller); } } } ?&gt; </code></pre>
[]
[ { "body": "<p>Only something litle, don't write the closing <code>?&gt;</code> , because if there is a whitespace after and you try to modifiy the header anywhere else, it won't work and you will have very very long to find the whitespace.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T17:03:51.917", "Id": "1820", "Score": "2", "body": "I disagree. I would argue that closing PHP mode is good practice." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T23:35:02.633", "Id": "1844", "Score": "7", "body": "\"I disagree. I would argue that closing PHP mode is good practice\" - You won't say that when you've wasted a day or more of time trying to find some errant whitespace." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-04T02:49:41.987", "Id": "34128", "Score": "0", "body": "`throw new NotACodeReviewException()`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T14:09:13.640", "Id": "1012", "ParentId": "990", "Score": "3" } }, { "body": "<p>I think there is too much responsibility for this class. I also think that it's name is a misnomer. A more appropriate name would be a <code>FrontController</code> or <code>RequestHandler</code> rather than <code>Request</code>. When I see an object named <code>Request</code> I expect something that wraps around a HTTP request, providing easy access to the underlying request data and state. I.e. I expect something that <em>is</em> a request rather than something that <em>processes</em> requests.</p>\n\n<p>If you want to reduce/divide the responsibilities of this class, have a look at how other PHP frameworks have divided these, for example, Symfony2. Symfony2 has a <code>FrontController</code> object (they call it a <code>Kernel</code>) that has two parts: a <code>Router</code> and a <code>Resolver</code>. You put <code>Request</code> objects into the <code>Kernel</code> and you get <code>Response</code> objects back.</p>\n\n<p>Internally, the <code>Kernel</code> passes the <code>Request</code> to the <code>Router</code>. The <code>Router</code> figures out which <code>Controller</code> and <code>Action</code> are being requested. This information is then passed to the <code>Resolver</code> which tries to load the actual PHP class that holds the <code>Controller</code> and <code>Action</code>. The <code>Kernel</code> then executes the <code>Controller/Action</code> which returns a <code>Response</code> object, which is (usually) displayed by the <code>Kernel</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-26T06:26:09.637", "Id": "2099", "ParentId": "990", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-25T14:34:57.060", "Id": "990", "Score": "4", "Tags": [ "php", "http" ], "Title": "Handling HTTP requests" }
990
<p>I am currently learning myself a little F# and have written the following code to practice.</p> <p>The code uses the Mono.Cecil library to inject some IL at the start of every method in each .net assembly found in a given directory. The IL will call a LogMe method in a Loggit.dll assembly.</p> <p>I want to make this code as functional and idiomatically F# as possible.</p> <p>My main concern is that the method to inject code into an assembly has some definite side effects. This is unavoidable as thats what the whole point is. I do this in the function InjectMethods. This function is passed to the DoOnModule function. </p> <p>This DoOnModule function is used twice - </p> <ul> <li>once when injecting methods - a method with side effects and no real return value, </li> <li>and once when retreiving the LogMe method reference from the Loggit.dll assembly - a method with no side effects and a useful return value.</li> </ul> <p>I feel a little uneasy about this double use, which doesnt feel very functional - and yet I find it very useful save code repetition...</p> <p>How can I make this code more functional?</p> <pre><code>// open System.IO open Mono.Cecil open Mono.Cecil.Cil exception LogNotFoundError of string let IsClass(t:TypeDefinition) = t.IsAnsiClass &amp;&amp; not t.IsInterface let UsefulMethods(t:TypeDefinition) = t.Methods |&gt; Seq.filter ( fun m -&gt; m.HasBody ) // Perform the given funtion on the module found at the given filename. let DoOnModule fn (file:string) = try let _module = ModuleDefinition.ReadModule file Some ( fn ( _module ) ) with | :? System.BadImageFormatException as ex -&gt; printfn "%A" ex; None | :? System.Exception as ex -&gt; printfn "%A" ex; None // Do the given function on the dll filenames found in the given directory let MapAssemblies fn directory = System.IO.Directory.GetFiles(directory) |&gt; Seq.filter(fun file -&gt; file.EndsWith("dll") || file.EndsWith("exe") ) |&gt; Seq.map( fn ) // Return the methods found in the given module let GetMethods(_module:ModuleDefinition) = _module.Types |&gt; Seq.filter ( IsClass ) |&gt; Seq.collect ( UsefulMethods ) // Get the log method found in the Loggit.dll. // A call to this method will be injected into each method let LogMethod (_module:ModuleDefinition) = let GetLogMethod(_logmodule:ModuleDefinition) = let logClass = _logmodule.Types |&gt; Seq.filter ( fun t -&gt; t.Name.Contains ( "Log" ) ) |&gt; Seq.head let logMethod = logClass.Methods |&gt; Seq.filter ( fun m -&gt; m.Name.Contains ( "LogMe" ) ) |&gt; Seq.head _module.Import logMethod "Loggit.dll" |&gt; DoOnModule GetLogMethod // Injects IL into the second method to call the first method, // passing this and the method name as parameters let InjectCallToMethod(logMethod:MethodReference) (_method:MethodDefinition) = let processor = _method.Body.GetILProcessor() let firstInstruction = _method.Body.Instructions.Item(0) let parameter1 = processor.Create(OpCodes.Ldstr, _method.Name) let parameter2 = processor.Create(if _method.HasThis then OpCodes.Ldarg_0 else OpCodes.Ldnull) let call = processor.Create(OpCodes.Call, logMethod) processor.InsertBefore ( firstInstruction, parameter1 ); processor.InsertBefore ( firstInstruction, parameter2 ); processor.InsertBefore ( firstInstruction, call ) // Inject a call to the Log method at the start of every method found in the given module. let InjectMethods(_module:ModuleDefinition) = // Inject the call let logMethod = LogMethod _module match logMethod with | Some(log) -&gt; let methods = GetMethods _module for m in methods do m |&gt; InjectCallToMethod log | None -&gt; raise(LogNotFoundError("Cant find log method")) // Save the module Directory.CreateDirectory ( Path.GetDirectoryName ( _module.FullyQualifiedName ) + @"\jiggled\" ) |&gt; ignore _module.Write ( Path.Combine ( Path.GetDirectoryName ( _module.FullyQualifiedName ) + @"\jiggled\", Path.GetFileName ( _module.FullyQualifiedName ) ) ); let dir = "D:\\Random\\AssemblyJig\\spog\\bin\\Debug" // Now inject into the methods try dir |&gt; MapAssemblies ( DoOnModule InjectMethods ) |&gt; Seq.toList |&gt; ignore with | :? System.Exception as ex -&gt; printfn "%A" ex; System.Console.ReadLine |&gt; ignore </code></pre>
[]
[ { "body": "<p>I only have two minor nitpicks with this code:</p>\n\n<pre><code>Seq.filter(fun file -&gt; file.EndsWith(\"dll\") || file.EndsWith(\"exe\") ) |&gt;\n</code></pre>\n\n<p>Perhaps this should say <code>\".dll\"</code> and <code>\".exe\"</code>. Or you could use <code>Path.GetExtension</code>.</p>\n\n<pre><code>Seq.filter ( fun t -&gt; t.Name.Contains ( \"Log\" ) ) |&gt; Seq.head\n</code></pre>\n\n<p>This will take the first type whose name happens to contain <code>Log</code>; even if the name is <code>ILoggable</code> or <code>LogProcessor</code> or something. Are you sure you know that there will never be any other types with such names than the type you want? The same goes for the method <code>LogMe</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-02T10:36:04.250", "Id": "18282", "Score": "0", "body": "Also using Path.Combine is better than concatenating \"\\jiggled\\\" etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-23T21:44:35.740", "Id": "30228", "Score": "0", "body": "Wouldn't Seq.find(...) be a shorter and clearer version of Seq.filter(...) |> Seq.head?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T16:51:19.933", "Id": "992", "ParentId": "991", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T16:30:32.357", "Id": "991", "Score": "6", "Tags": [ "functional-programming", "f#" ], "Title": "How can I make this F# more functional?" }
991
<p>I have a function that returns a set of values from a <code>Dictionary</code>.<br> I don't currently want to allow it to throw <code>KeyNotFoundException</code>, so I'm filtering the keys out before I try to select the values.</p> <p>I have a feeling this can be done in a more straightforward fashion, but I'm not sure where to go with it.</p> <pre><code>// this.resources is a Dictionary&lt;string, Resource&gt; public IEnumerable&lt;Resource&gt; GetResources(IEnumerable&lt;string&gt; resourceNames) { HashSet&lt;string&gt; hs = new HashSet&lt;string&gt;(resourceNames); hs.IntersectWith(this.resources.Keys); List&lt;Resource&gt; resources = new List&lt;Resource&gt;(); foreach(string resourceName in hs) { resources.Add(this.resources[resourceName]); } return resources; } </code></pre>
[]
[ { "body": "<p>I would write it the obvious straight-forward LINQ way, which gives you good readability as well as lazy evaluation:</p>\n\n<pre><code>public IEnumerable&lt;Resource&gt; GetResources(IEnumerable&lt;string&gt; resourceNames)\n{\n return resourceNames\n .Where(name =&gt; resources.ContainsKey(name))\n .Select(name =&gt; resources[name]);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T17:10:27.517", "Id": "1798", "Score": "0", "body": "This is exactly what I was hoping for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T22:32:59.563", "Id": "413919", "Score": "0", "body": "you probably meant `yield return resourceNames..`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T17:07:27.933", "Id": "995", "ParentId": "993", "Score": "14" } } ]
{ "AcceptedAnswerId": "995", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-25T16:56:43.730", "Id": "993", "Score": "8", "Tags": [ "c#" ], "Title": "Pulling a subset of elements from a Dictionary" }
993
<p>Is it bad to do return render? I am doing this to NOT also allow a redirect. </p> <pre><code>def create @patient = Patient.new(params[:patient]) if [email protected] @patient.user.password = '' @patient.user.password_confirmation = '' return render is_admin? ? 'new_admin' : 'new' else #Fire off an e-mail PatientMailer.welcome_email(@patient).deliver end if current_user == @patient sign_in @patient else redirect_to patients_path end end </code></pre>
[]
[ { "body": "<p>Writing it like this makes it look the <code>render</code> returns a meaningful value that is then returned by create and used by the code that calls <code>create</code>, which is not the case. So instead I would write:</p>\n\n<pre><code>render is_admin? ? 'new_admin' : 'new'\nreturn\n</code></pre>\n\n<p>This makes it clear that <code>render</code> is solely used for its side effects and <code>create</code> does not return a value (other than <code>nil</code>).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-25T18:55:37.833", "Id": "997", "ParentId": "996", "Score": "8" } }, { "body": "<p>There are two sensible ways to write that function.</p>\n\n<p>The first way, with the early return, treats the special case more like an error condition:</p>\n\n<pre><code>def create\n @patient = Patient.new(params[:patient])\n if [email protected]\n @patient.user.password = ''\n @patient.user.password_confirmation = ''\n render is_admin? ? 'new_admin' : 'new'\n return\n end\n\n # Fire off an e-mail\n PatientMailer.welcome_email(@patient).deliver\n\n if current_user == @patient\n sign_in @patient\n else\n redirect_to patients_path\n end\nend\n</code></pre>\n\n<p>The other way outlines all the possible outcomes:</p>\n\n<pre><code>def create\n @patient = Patient.new(params[:patient])\n if [email protected]\n @patient.user.password = ''\n @patient.user.password_confirmation = ''\n render is_admin? ? 'new_admin' : 'new'\n else\n # Fire off an e-mail\n PatientMailer.welcome_email(@patient).deliver\n if current_user == @patient\n sign_in @patient\n else\n redirect_to patients_path\n end\n end\nend\n</code></pre>\n\n<p>I personally have a slight preference for the first way, since the failure to save is more like an error. Your original code, which is a hybrid of the two, feels awkward.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-25T19:29:06.830", "Id": "74883", "ParentId": "996", "Score": "1" } } ]
{ "AcceptedAnswerId": "997", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-25T18:39:09.897", "Id": "996", "Score": "10", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Return render in Ruby on Rails" }
996
<p>I am writing an application aimed at the desktop but using web technologies. It will have an HTML interface and a server written in Python using Flask will do all of the filesystem interaction. It will have the ability to edit user settings so I want to make it impossible for other users to interfere. This is a little tricky because the server and client communicate using HTTP over a localhost port.</p> <p>The program is split between 3 files:</p> <p><strong>run.py</strong> - controls the start up and shut down of the server and client.</p> <pre><code>import os import json import time import signal secret_file = os.path.join(os.environ['HOME'], '.myapp.secret') if os.path.exists(secret_file): os.remove(secret_file) os.system("python server.py &amp;") while not os.path.exists(secret_file): time.sleep(0.1) f = open(secret_file) secret = json.load(f) url = 'http://localhost:' + str(secret['port']) + '/' + secret['key'] os.system("python client.py " + url) os.kill(secret['pid'], signal.SIGINT) </code></pre> <p><strong>server.py</strong></p> <pre><code>from flask import Flask, request, Response import socket import random import json import sys import os app = Flask(__name__) key = ''.join(random.sample( "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM", random.randint(8, 24) )) port = 0 secret_file = os.path.join(os.environ['HOME'], '.myapp.secret') @app.route('/&lt;authkey&gt;') def hello(authkey): if authkey == key: return 'Hello, world!' else: return Response('Access Denied', 401) def broadcast(port): s = json.dumps({ 'key' : key, 'port' : port, 'pid' : os.getpid() }) f = open( secret_file, 'w' ) f.write(s) os.chmod(secret_file, 0400) f.close() if __name__ == '__main__': sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', 0)) port = sock.getsockname()[1] broadcast(port) sock.close() app.run(port=port) </code></pre> <p><strong>client.py</strong></p> <p>This is a simple GTK window with a webkit widget that renders the page. It renders the URL passed to it by the first argument.</p> <p>Is this sufficiently secure? Also, are there any other problems that I have not considered?</p>
[]
[ { "body": "<p>It's not secure because you delete the file with the port on. Finding open ports is easy. A better option is to bind only on localhost so that you can't connect from other computers at all. Figuring out the port is always going to be easy, so making that secret doesn't help. In fact it should be configurable so you can avoid port conflicts.</p>\n\n<p>Since you start the server from within the client, you can actually create the key in the client, and instead pass it in to the server at startup preferably via stdin. That way it doesn't have to exist on the file system at all. You probably want to use subprocess instead of os.system for that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-02T01:13:21.723", "Id": "30752", "Score": "0", "body": "Are you sure passing it via stdin is secure? I can see it in process list. `python server.py localhost 9999` for example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-02T09:02:45.927", "Id": "30757", "Score": "0", "body": "@JohnWong: It is neither more nor less secure. I repeat: Finding open ports is easy." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T11:03:24.077", "Id": "1009", "ParentId": "1000", "Score": "3" } }, { "body": "<p>The important thing you want to enforce is that only the same local user can see the hello world.</p>\n\n<p>You're relying at least on the inability of any random user to</p>\n\n<ol>\n<li>listen in on someone else's sockets.</li>\n<li>read another user's files</li>\n<li>otherwise learn the secret</li>\n<li>execute random python code in your server</li>\n<li>And the inability for a remote attacker to connect to your socket.</li>\n</ol>\n\n<p>1, 2 and 4 depend how well you've secured your system (no privilege elevation or random suid files lying around). 4 also depends on the security of flask and the rest of your python stack.</p>\n\n<p>Five can be broken, depending on how your firewall is configured (someone could use connection tracking to get your socket forwarded, even though it is bound to localhost). You'd be better off using unix domain sockets.</p>\n\n<p>The second is broken, because you chmod the file only after you've written to it. That gives a window for the attacker to open the file. In fact the attacker could even write to the file and execute arbitrary commands, which is why you should never use os.system, and you should use urlparse to build the url.</p>\n\n<p>The third is broken in two ways:</p>\n\n<ul>\n<li>the secret appears in the process list</li>\n<li>the server won't take the same time to compare strings that are mostly right and mostly wrong. The attacker can guess the length of the secret, and guess the secret letter by letter (timing attack).</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T11:04:13.403", "Id": "1010", "ParentId": "1000", "Score": "4" } } ]
{ "AcceptedAnswerId": "1010", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-25T20:44:42.203", "Id": "1000", "Score": "5", "Tags": [ "python", "security", "flask" ], "Title": "Security of simple client/server desktop app" }
1000
<p>I'm trying to port this little F# snippet while staying pythonic:</p> <pre><code>["something"; "something else"; "blah"; "a string"] |&gt; List.map (fun p -&gt; p, p.Length) |&gt; List.sortBy snd </code></pre> <p>In case you don't speak F#, it gets the length of each string, then sorts by length.</p> <p>Output:</p> <blockquote> <pre><code>[("blah", 4); ("a string", 8); ("something", 9); ("something else", 14)] </code></pre> </blockquote> <p>In Python, this is the best I could do so far:</p> <pre><code>sorted([(p, len(p)) for p in ["something", "something else", "blah", "a string"]], key=lambda a:a[1]) </code></pre> <p>While correct, this doesn't look very elegant to me, or maybe it's just my non-pythonic eye.</p> <p>Is this pythonic code? How would you write it? Maybe an imperative style is more appropriate?</p>
[]
[ { "body": "<pre><code>data = [\"something\", \"something else\", \"blah\", \"a string\"]\nresult = [(x, len(x)) for x in sorted(data, key = len)]\n</code></pre>\n\n<p>Basically, its more straightforward to sort first then decorate. Although, I'm not sure why you would need the length of the list in your tuple. If you don't really need it sorting by length can be much shorter.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>If all I wanted was to output the data, I'd do it like this:</p>\n\n<pre><code>for string in sorted(data, key = len):\n print string, len(string)\n</code></pre>\n\n<p>If you really wanted to eliminate the two references to len you could do:</p>\n\n<pre><code>mykey = len\nfor string in sorted(data, key = mykey):\n print string, mykey(string)\n</code></pre>\n\n<p>But unless you are reusing the code with different mykey's that doesn't seem worthwhile.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T16:24:15.013", "Id": "1816", "Score": "0", "body": "@Mauricio Scheffer, what are you doing with it afterwards?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T16:34:35.360", "Id": "1817", "Score": "0", "body": "@Winston Ewert: just printing it to screen." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T16:37:50.097", "Id": "1818", "Score": "0", "body": "@Mauricio Scheffer, so you are just printing this list out? Why do you need the string lengths in there?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T16:39:13.493", "Id": "1819", "Score": "0", "body": "@Winston Ewert: just need to display that information." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-24T21:17:13.283", "Id": "12906", "Score": "0", "body": "If you do not need to reuse `len` (eg. you need it only for sorting), you can use simply: `sorted(data, key=len)`. If you need it later, you can do it in two steps, to improve readability: 1) `data_sorted = sorted(data, key=len)`, 2) `result = zip(data_sorted, map(len, data_sorted))`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-29T19:36:36.287", "Id": "51091", "Score": "1", "body": "Nitpicking: the space between the `=` when using keyword arguments is not PEP8 compliant." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T00:48:39.577", "Id": "1004", "ParentId": "1001", "Score": "29" } }, { "body": "<p>I don't think that your solution looks bad. I would probably use a temporary variable to make the line length a bit more readable. You could consider <code>itemgetter</code> from the <code>operator</code> module.</p>\n\n<p>E.g.</p>\n\n<pre><code>from operator import itemgetter\n\norig_list = [\"something\", \"something else\", \"blah\", \"a string\"]\nmylist = [(p, len(p)) for p in orig_list]\nmylist.sort(itemgetter(1))\n</code></pre>\n\n<p>Personally I think that this is just as readable.</p>\n\n<pre><code>mylist = sorted([(p, len(p)) for p in orig_list], key=itemgetter(1))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T00:48:54.177", "Id": "1005", "ParentId": "1001", "Score": "6" } }, { "body": "<p>Here's another option. For the key function, it specifies a lambda that takes a two-item sequence, and unpacks the two items into \"s\" and \"l\", and returns \"l\". This avoids poking around each (string, length) pair by magic number, and also enforces a bit of a type constraint on the items to sort. Also, it breaks lines in convenient places, which is perfectly legal in Python:</p>\n\n<pre><code>sorted([(p, len(p)) for p \n in (\"something\", \n \"something else\", \n \"blah\", \n \"a string\")], \n key=lambda (s, l): l)\n</code></pre>\n\n<p>And here is a version that uses a generator comprehension instead of a list comprehension. Generator expressions are evaluated as items are pulled from them, rather than all at once. In this example there's no advantage, but when using expressions where items are expensive to create, or where iteration could terminate early (like database queries), generators are a big win:</p>\n\n<pre><code>sorted(((p, len(p)) for p \n in (\"something\", \n \"something else\", \n \"blah\", \n \"a string\")), \n key=lambda (s, l): l)\n</code></pre>\n\n<p>And this version deterministically handles cases where there is some ambiguity on sorting only by length:</p>\n\n<pre><code>sorted(((p, len(p)) for p \n in (\"something\", \n \"something else\", \n \"four things\", \n \"five things\", \n \"a string\")), \n key=lambda (s, l): (l, s))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T18:45:19.620", "Id": "1063", "ParentId": "1001", "Score": "1" } }, { "body": "<p>If you don't want to call <code>len</code> twice for each item (if, for example, you need to call some expensive function instead of <code>len</code>), you can sort by the second item without lambdas by using <code>itemgetter</code>.</p>\n\n<pre><code>from operator import itemgetter \n\ndata = [\"something\", \"something else\", \"blah\", \"a string\"]\nl = [(s, len(s)) for s in data]\nl.sort(key = itemgetter(1))\n</code></pre>\n\n<p>However, if the order of members is not important, it would be better to place the length first in the tuple, because the default behaviour for sorting tuples is to compare the elements in order.</p>\n\n<pre><code>data = [\"something\", \"something else\", \"blah\", \"a string\"]\nl = sorted((len(s), s) for s in data)\n</code></pre>\n\n<p>You can then switch them around during output if you want:</p>\n\n<pre><code>for length, item in l:\n print item, length\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T07:07:35.007", "Id": "1152", "ParentId": "1001", "Score": "5" } }, { "body": "<p>If the order of the items in the tuple isn't important (depends on what you're going to do with it), then it's easier to put the length first and the string second. The standard tuple sorting sorts on the first element, or if they're equal on the second, and so on.</p>\n\n<pre><code>sorted(\n (len(p), p) for p in\n (\"something\", \"something else\", \"four things\", \"five things\", \"a string\"))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-09T09:58:23.377", "Id": "36950", "ParentId": "1001", "Score": "1" } } ]
{ "AcceptedAnswerId": "1004", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-25T23:44:49.373", "Id": "1001", "Score": "37", "Tags": [ "python", "beginner", "strings", "sorting", "functional-programming" ], "Title": "Sorting strings by length - functional Python" }
1001
<p>I am working on a helper method that maps properties from an <code>ExpandoObject</code> to a user supplied object and was wondering if the code could be cleaned up or made any more efficient. It currently has the correct behaviour from a simple test.</p> <pre><code>public static class Mapper { public static void Map&lt;T&gt;(ExpandoObject source, T destination) { IDictionary&lt;string, object&gt; dict = source; var type = destination.GetType(); foreach (var prop in type.GetProperties()) { var lower = prop.Name.ToLower(); var key = dict.Keys.SingleOrDefault(k =&gt; k.ToLower() == lower); if (key != null) { prop.SetValue(destination, dict[key], null); } } } } </code></pre> <p>Full test can be seen <a href="https://gist.github.com/844736" rel="nofollow noreferrer">here</a>. There is currently no type checking. Would this be next to add?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-11T00:05:40.340", "Id": "507530", "Score": "0", "body": "If the ExpandoObject's are coming from JSON deserialization, might be simpler if you instead convert to `JObject`s. As seen [here](https://stackoverflow.com/q/30060974/199364)." } ]
[ { "body": "<p>I've come up with a few changes that should actually speed it up.</p>\n\n<pre><code>// By using a generic class we can take advantage\n// of the fact that .NET will create a new generic type\n// for each type T. This allows us to avoid creating\n// a dictionary of Dictionary&lt;string, PropertyInfo&gt;\n// for each type T. We also avoid the need for the \n// lock statement with every call to Map.\npublic static class Mapper&lt;T&gt;\n // We can only use reference types\n where T : class\n{\n private static readonly Dictionary&lt;string, PropertyInfo&gt; _propertyMap;\n\n static Mapper()\n {\n // At this point we can convert each\n // property name to lower case so we avoid \n // creating a new string more than once.\n _propertyMap = \n typeof(T)\n .GetProperties()\n .ToDictionary(\n p =&gt; p.Name.ToLower(), \n p =&gt; p\n );\n }\n\n public static void Map(ExpandoObject source, T destination)\n {\n // Might as well take care of null references early.\n if (source == null)\n throw new ArgumentNullException(\"source\");\n if (destination == null)\n throw new ArgumentNullException(\"destination\");\n\n // By iterating the KeyValuePair&lt;string, object&gt; of\n // source we can avoid manually searching the keys of\n // source as we see in your original code.\n foreach (var kv in source)\n {\n PropertyInfo p;\n if (_propertyMap.TryGetValue(kv.Key.ToLower(), out p))\n {\n var propType = p.PropertyType;\n if (kv.Value == null)\n {\n if (!propType.IsByRef &amp;&amp; propType.Name != \"Nullable`1\")\n {\n // Throw if type is a value type \n // but not Nullable&lt;&gt;\n throw new ArgumentException(\"not nullable\");\n }\n }\n else if (kv.Value.GetType() != propType)\n {\n // You could make this a bit less strict \n // but I don't recommend it.\n throw new ArgumentException(\"type mismatch\");\n }\n p.SetValue(destination, kv.Value, null);\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T14:28:07.220", "Id": "1920", "Score": "0", "body": "I'd advise you to check out Fasterflect (fasterflect.codeplex.com), which is a library to make reflection tasks easier (through an abstraction over the classic reflection API) and much faster (using dynamic code generation). Also worth mentioning is AutoMapper, which is a library dedicated just to the task of mapping between objects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-19T08:59:22.153", "Id": "102710", "Score": "0", "body": "May be ok *for now* but needs more work to handle nested types." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-27T19:50:52.380", "Id": "432163", "Score": "1", "body": "Be aware that this solution breaks on polymorphism. Suppose T is abstract and you provide an instance of V (V : T) to the mapper of type T, the properties declared at V are not mapped. Is this as designed?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-26T00:16:03.807", "Id": "1003", "ParentId": "1002", "Score": "8" } }, { "body": "<h3>Review</h3>\n\n<ul>\n<li>Generic type definition <code>T</code> is redundant.</li>\n<li>Looping the <code>ExpandoObject</code> is better optimized then looping the destination's properties, because you get the items as key-value pair in a single pass.</li>\n<li>Fetch only publicly accessible setter properties to avoid nasty exceptions on <code>property.SetValue</code>.</li>\n<li>Don't be too strict on matching the source and destination's types. Take advantage of the built-in type converter API <code>Convert.ChangeType</code>.</li>\n</ul>\n\n<h3>Proposed Alternative</h3>\n\n<p><code>TypeExtension</code> allows for a changing an instance's type.</p>\n\n<pre><code>public static class TypeExtension\n{\n public static bool IsNullable(this Type type)\n {\n type = type ?? throw new ArgumentNullException(nameof(type));\n return type.IsGenericType \n &amp;&amp; type.GetGenericTypeDefinition().Equals(typeof(Nullable&lt;&gt;));\n }\n\n public static bool IsNullAssignable(this Type type)\n {\n type = type ?? throw new ArgumentNullException(nameof(type));\n return type.IsNullable() || !type.IsValueType;\n }\n\n public static object ChangeType(this Type type, object instance)\n {\n type = type ?? throw new ArgumentNullException(nameof(type));\n if (instance == null)\n {\n if (!type.IsNullAssignable())\n {\n throw new InvalidCastException($\"{type.FullName} is not null-assignable\");\n }\n return null;\n }\n if (type.IsNullable())\n {\n type = Nullable.GetUnderlyingType(type);\n }\n return Convert.ChangeType(instance, type);\n }\n}\n</code></pre>\n\n<p><code>Mapper</code> could be optimized, made more robust and better suited to map between different types.</p>\n\n<pre><code>public static class Mapper\n{\n public static void Map(ExpandoObject source, object destination)\n {\n source = source ?? throw new ArgumentNullException(nameof(source));\n destination = destination ?? throw new ArgumentNullException(nameof(destination));\n\n string normalizeName(string name) =&gt; name.ToLowerInvariant();\n\n IDictionary&lt;string, object&gt; dict = source;\n var type = destination.GetType();\n\n var setters = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)\n .Where(p =&gt; p.CanWrite &amp;&amp; p.GetSetMethod() != null)\n .ToDictionary(p =&gt; normalizeName(p.Name));\n\n foreach (var item in dict)\n {\n if (setters.TryGetValue(normalizeName(item.Key), out var setter))\n {\n var value = setter.PropertyType.ChangeType(item.Value);\n setter.SetValue(destination, value);\n }\n }\n }\n}\n</code></pre>\n\n<p>Test Case:</p>\n\n<pre><code>public class Point\n{\n public int? X { get; set; }\n public double Y { get; set; }\n}\n\nstatic void Main(string[] args)\n{\n dynamic source = new ExpandoObject();\n source.X = 0;\n source.Y = 0m;\n\n var destination = new Point\n {\n X = 1,\n Y = 1d\n };\n\n Mapper.Map(source, destination);\n\n Console.WriteLine(destination.X);\n Console.WriteLine(destination.Y);\n Console.ReadKey();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-27T17:39:08.150", "Id": "432145", "Score": "0", "body": "My gut tells me that this is a xy-problem becuase I cannot think of any reasonable use-case where one would want to use such mapping. OP is probably parsing json into `dynamic` instead of `T` thus they need to _fix_ that with this mapper." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-27T17:41:45.380", "Id": "432146", "Score": "0", "body": "@t3chb0t I can see a use case in WPF when binding a view to an ExpandoObject and mapping further to some DTO. The ExpandoObject can be usefull for a table with a dynamic configurable set of columns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-27T17:42:07.760", "Id": "432147", "Score": "1", "body": "@TomBell do you remember what you needed this for?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-27T17:43:45.920", "Id": "432148", "Score": "0", "body": "I'm answering this question because I feel the accepted answer has a major flaw using the properties of `T`. The instance can be of a derived type, breaking the mapping." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-27T17:43:47.120", "Id": "432149", "Score": "0", "body": "maybe... but the question is where the `ExpandoObject` is comming from? This is not something you use on a daily basis and not at all for mapping. This is super suspicious." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-27T17:44:55.050", "Id": "432150", "Score": "1", "body": "sure, the review is fine, +1 as always ;-P but I'm curious about the real use case..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-11T00:02:13.087", "Id": "507528", "Score": "0", "body": "@t3chb0t - could be from `JsonConvert.DeserializeObject`, where destination is a list of different object types, to be determined by examining some property in each ExpandoObject. As seen [here](https://stackoverflow.com/q/30060974/199364). Note that a cleaner solution was obtained by converting to `JObject`s instead of `ExpandoObject`s." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-27T17:30:55.697", "Id": "223079", "ParentId": "1002", "Score": "4" } }, { "body": "<p>Popular NewtonSoft JSON library has built-in methods that could simplify this task.</p>\n<p>The [PopulateObject][1] method handles arrays, nested objects etc.</p>\n<pre><code>void Main()\n{\n var source= new ExpandoObject() as IDictionary&lt;string, Object&gt;;\n source.Add(&quot;Prop1&quot;, &quot;A&quot;);\n source.Add(&quot;Prop2&quot;, &quot;B&quot;);\n\n var target = new Test();\n JsonConvert.PopulateObject(JsonConvert.SerializeObject(source), target);\n target.Dump();\n}\n\npublic class Test{\n public string Prop1 {get;set;}\n public string Prop2 {get;set;}\n}\n\n\n [1]: https://www.newtonsoft.com/json/help/html/PopulateObject.htm\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T16:56:02.830", "Id": "528896", "Score": "2", "body": "Hi. Welcome to Code Review! While we appreciate code, please remember the review part. What was it about the question's code that prompted this? Why is this code better?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T16:26:26.180", "Id": "268230", "ParentId": "1002", "Score": "-1" } } ]
{ "AcceptedAnswerId": "1003", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-02-25T23:50:59.147", "Id": "1002", "Score": "12", "Tags": [ "c#", ".net", "reflection" ], "Title": "Mapping ExpandoObject to another object type" }
1002
<p>I am looking for some help with improving this bilinear scaling SSE2 code on Core 2 CPUs.</p> <p>On my Atom N270 and on an i7, this code is about 2x faster than the MMX code. But under Core 2 CPUs, it is only equal to the MMX code.</p> <pre class="lang-c prettyprint-override"><code>void ConversionProcess::convert_SSE2(BBitmap *from, BBitmap *to) { uint32 fromBPR, toBPR, fromBPRDIV4, x, y, yr, xr; ULLint start = rdtsc(); ULLint stop; if (from &amp;&amp; to) { uint32 width, height; width = from-&gt;Bounds().IntegerWidth() + 1; height = from-&gt;Bounds().IntegerHeight() + 1; uint32 toWidth, toHeight; toWidth = to-&gt;Bounds().IntegerWidth() + 1; toHeight = to-&gt;Bounds().IntegerHeight() + 1; fromBPR = from-&gt;BytesPerRow(); fromBPRDIV4 = fromBPR &gt;&gt; 2; toBPR = to-&gt;BytesPerRow(); uint32 x_ratio = ((width-1) &lt;&lt; 7) / toWidth ; uint32 y_ratio = ((height-1) &lt;&lt; 7) / toHeight ; uint8* toPtr = (uint8*)to-&gt;Bits(); uint8* fromPtr1 = (uint8*)from-&gt;Bits(); uint8* fromPtr2 = (uint8*)from-&gt;Bits() + fromBPR; struct FilterInfo { uint16 one_minus_diff; // one minus diff uint16 diff; // diff value used to calculate the weights used to average the pixels uint16 one_minus_diff_rep; // one minus diff repeated uint16 diff_rep; // diff value used to calculate the weights used to average the pixels repeated }; FilterInfo *xWeights = (FilterInfo *)memalign(16, toWidth * 8); FilterInfo *yWeights = (FilterInfo *)memalign(16, toHeight * 8); uint32 *xIndexes = (uint32 *)memalign(16, (toWidth+2) * 4); // will overread by 2 index uint32 *yIndexes = (uint32 *)memalign(16, toHeight * 4); x = 0; for (uint32 j=0;j &lt; toWidth;j++) { xr = x &gt;&gt; 7; xWeights[j].diff = x - (xr &lt;&lt; 7); xWeights[j].one_minus_diff = 127 - xWeights[j].diff; xWeights[j].one_minus_diff_rep = xWeights[j].one_minus_diff; xWeights[j].diff_rep = xWeights[j].diff; xIndexes[j] = xr &lt;&lt; 2; x += x_ratio; } y = 0; for (uint32 j=0;j &lt; toHeight; j++) { yr = y &gt;&gt; 7; yWeights[j].diff = y - (yr &lt;&lt; 7); yWeights[j].one_minus_diff = 127 - yWeights[j].diff; yIndexes[j] = (yr * fromBPR); y += y_ratio; } for (uint32 i=0;i &lt; toHeight; i++) { _ScaleSSE2X2(toPtr, fromPtr1 + yIndexes[i], fromPtr2 + yIndexes[i], xIndexes, xWeights, &amp;yWeights[i], toWidth); toPtr += toBPR; } free(xWeights); free(yWeights); free(xIndexes); free(yIndexes); stop = rdtsc() - start; if (stop &lt; timeTaken) { timeTaken = stop; } } } </code></pre> <pre class="lang-lisp prettyprint-override"><code>; ; Copyright (C) 2011 David McPaul ; ; All rights reserved. Distributed under the terms of the MIT License. ; ; A rather unoptimised bilinear scaler %macro cglobal 1 global _%1 %define %1 _%1 align 16 %1: %endmacro SECTION .data align=16 RGB_AND db 0xff db 0x00 db 0x00 db 0x00 db 0xff db 0x00 db 0x00 db 0x00 db 0xff db 0x00 db 0x00 db 0x00 db 0xff db 0x00 db 0x00 db 0x00 ; void _ScaleSSE2X2(void *toPtr, void *fromPtr1, void *fromPtr2, void* xIndexPtr, void *xWeightPtr, void *yWeightPtr, uint32 length); length equ ebp+32 yWeightPtr equ ebp+28 xWeightPtr equ ebp+24 xIndexPtr equ ebp+20 fromPtr2 equ ebp+16 fromPtr1 equ ebp+12 toPtr equ ebp+8 SECTION .text align=16 cglobal ScaleSSE2X2 ; reserve registers. eax, ecx, edx automatically available push ebp mov ebp, esp push ebx ; yWeights, xIndexPtr push edi ; scratch push esi ; fromPtr3 mov esi, [fromPtr1] mov edx, [fromPtr2] mov eax, [xWeightPtr] mov ebx, [yWeightPtr] mov ecx, [length] ; calculate y weights and cache movd xmm7, [ebx] ; get 1-yDiff and yDiff pshuflw xmm7, xmm7, 01010000b ; 1-yDiff, 1-yDiff, yDiff, yDiff pshufd xmm7, xmm7, 01000100b ; duplicate mov ebx, [xIndexPtr] push ebp ; reuse frame ptr for toPtr mov ebp, [toPtr] ; Cannot use parameter refs anymore shr ecx,1 ; calculate first index mov edi, [ebx] ; index align 16 REPEATLOOPX2: ; load first and second set of weights into xmm3 movdqa xmm3, [eax] ; get 1-xDiff, xDiff, 1-xDiff, xDiff pmullw xmm3, xmm7 ; calculate F1, F2, F3, F4 (2) add eax, 16 ; load first set of source pixels movq xmm0, [esi+edi] ; xmm0 = fromPtr1 + index | fromPtr1 + index + 4 movq xmm1, [edx+edi] ; xmm1 = fromPtr2 + index | fromPtr2 + index + 4 punpcklqdq xmm0, xmm1 ; combine all 4 pixels into xmm0 sub edi, [ebx+4] ; if the x index is the same then skip the second load jz SKIP ; calculate second index mov edi, [ebx+4] ; index ; load second set of source pixels movq xmm4, [esi+edi] ; xmm4 = fromPtr1 + index | fromPtr1 + index + 4 movq xmm5, [edx+edi] ; xmm5 = fromPtr2 + index | fromPtr2 + index + 4 punpcklqdq xmm4, xmm5 ; combine all 4 pixels into xmm4 movdqa xmm1, xmm0 ; copy to xmm1, xmm2 pshufd xmm2, xmm0, 0xE4 movdqa xmm5, xmm4 ; copy to xmm1, xmm2 pshufd xmm6, xmm4, 0xE4 jmp NEXT align 16 SKIP: movdqa xmm1, xmm0 ; copy to xmm1, xmm2 pshufd xmm2, xmm0, 0xE4 movdqa xmm4, xmm0 ; copy first pixel set xmm0 to second pixel set xmm4 pshufd xmm5, xmm4, 0xE4 ; copy to xmm4, xmm6 movdqa xmm6, xmm4 NEXT: ; prefetchnta [edx+edi+16] add ebx, 8 ; calculate dest rgb values using color = a * F1 + b * F2 + c * F3 + d * F4 ; extract b from both sets of pixels and combine into a single reg pand xmm0, [RGB_AND] ; clear all but r values leaving b000 pand xmm4, [RGB_AND] ; clear all but r values leaving b000 packssdw xmm0, xmm4 ; pack down to 16 bit values movdqa xmm4, [RGB_AND] ; xmm4 is now free pmaddwd xmm0, xmm3 ; multiply and add to get temp1 = a * F1 + b * F2, temp2 = c * F3 + d * F4 ; extract g psrld xmm1, 8 ; rotate g to low bytes pand xmm1, xmm4 ; extract g values g000 psrld xmm5, 8 ; rotate g to low bytes pand xmm5, xmm4 ; extract g values g000 packssdw xmm1, xmm5 ; pack down to 16 bit values pmaddwd xmm1, xmm3 ; multiply and add ; extract r psrld xmm2, 16 ; rotate b to low bytes pand xmm2, xmm4 ; extract b values b000 psrld xmm6, 16 ; rotate b to low bytes pand xmm6, xmm4 ; extract b values b000 packssdw xmm2, xmm6 ; pack down to 16 bit values pmaddwd xmm2, xmm3 ; multiply and add ; Add temp1 and temp2 leaving us with rrrr xxxx rrrr xxxx psrld xmm0, 14 ; scale back to range pshufd xmm3, xmm0, 00110001b ; extract temp2 paddd xmm0, xmm3 ; add back to temp1 psrld xmm1, 14 ; scale back to range pshufd xmm3, xmm1, 00110001b paddd xmm1, xmm3 ; add psrld xmm2, 14 ; scale back to range pshufd xmm3, xmm2, 00110001b paddd xmm2, xmm3 ; add ; recombine into 2 rgba values pslld xmm1, 8 por xmm0, xmm1 pslld xmm2, 16 por xmm0, xmm2 pshufd xmm0, xmm0, 00001000b ; shuffle down movq [ebp], xmm0 ; output 32bit * 2 add ebp, 8 mov edi, [ebx] ; index sub ecx, 1 jnz REPEATLOOPX2 ; Cleanup pop ebp pop esi pop edi pop ebx mov esp, ebp pop ebp ret </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T13:05:47.200", "Id": "2102", "Score": "2", "body": "Posts like these make me feel stupid :-) Kudos to you for writing this!" } ]
[ { "body": "<p>Probably not what you wished to hear, but honestly, my suggestion would be to rewrite the code using SSE2 intrinsics and see what GCC (or MSVC) is able to do here with scheduling and loop unrolling.</p>\n\n<p>That said, you do not appear to be doing any prefetching. Why is the <code>prefetchnta</code> line commented out? Did you try with different values?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-18T22:28:46.957", "Id": "2358", "Score": "0", "body": "No intrinsics available as I am using gcc 2.96 so it is all assembly for this." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-18T22:30:57.283", "Id": "2359", "Score": "0", "body": "I have been trying with prefetchnta with various values and getting no clear speed up. I think on the core2 the inbuilt fetch hardware is doing a pretty good job." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-10T18:04:09.200", "Id": "1241", "ParentId": "1006", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-26T07:06:59.440", "Id": "1006", "Score": "7", "Tags": [ "performance", "c", "assembly" ], "Title": "Bilinear scaling using SSE2 on Core 2 CPUs" }
1006
<p>I have used code which looks a little like this in an app I'm working on:</p> <pre><code>module App module Settings class &lt;&lt; self attr_accessor :console, :file end self.console ||= true self.file ||= [] end end </code></pre> <p>I decided to use this method because I like the interface, I had the idea after reading the Singleton examples from <em>Design Patterns in Ruby</em>.</p> <p>I can then <code>require 'app/settings'</code> from any file in my app and read/write the settings</p> <pre><code>p App::Settings.console App::Settings.file &lt;&lt; "afile.rb" p App::Settings.file </code></pre> <p>etc...</p> <p>Is this a reasonable way to keep my settings in a single file? I feel I am unnecessarily repeating myself. Any ideas for DRYing?</p>
[]
[ { "body": "<p>There is nothing really wrong with this but using a simple hash may be easier:</p>\n\n<pre><code>module App\n @@settings = {\n :console =&gt; true,\n :file =&gt; []\n }\n def self.settings\n @@settings\n end\nend\n</code></pre>\n\n<p>Your following code would then become:</p>\n\n<pre><code>p App.settings[:console]\nApp.settings[:file] &lt;&lt; \"afile.rb\"\np App.settings[:file]\n</code></pre>\n\n<p>There are several advantages to this approach:</p>\n\n<ul>\n<li><p>Hashes are easy to serialise and store in files using yaml/json/etc.</p>\n\n<pre><code>require 'yaml'\np App.settings.to_yaml\n</code></pre></li>\n<li><p>You can reference App.settings in a local variable to avoid writing it out:</p>\n\n<pre><code>s = App.settings\n#do stuff with s\n</code></pre></li>\n<li><p>Hash has many convenience methods for iterating over its values.</p>\n\n<pre><code>App.settings.each do |key, value|\n #do something\nend\n</code></pre></li>\n<li><p>You can add to/update it succinctly using the <code>merge!</code> method. </p>\n\n<pre><code>App.settings.merge! :console =&gt; false, :newsetting =&gt; 'value', :etc =&gt; '...'\n</code></pre></li>\n</ul>\n\n<p>To get functionality like this in your method would require you to write lots of methods yourself. It's better to just use the built in functionality that Ruby has instead of reinventing the wheel. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T14:37:22.617", "Id": "1832", "Score": "0", "body": "Why you use `@@settings` as a class variable instead of a instance variable?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T15:38:47.660", "Id": "1834", "Score": "2", "body": "Why would I use an instance variable?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T07:10:19.730", "Id": "1846", "Score": "0", "body": "Thanks, this looks good to me. Re:instance variables and @LBg too. My understanding is that modules are included once only in the ruby class hierarchy. Is there then a need for class variables if I can use instance variables? Is the effect the same, as modules can not be instantiated?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T10:32:40.323", "Id": "1019", "ParentId": "1015", "Score": "6" } }, { "body": "<p>Based on @david4dev solution, you can keep the old interface:</p>\n\n<pre><code>module App\n @settings = {\n :console =&gt; true,\n :file =&gt; []\n }\n def @settings.method_missing(name, *a)\n name.to_s =~ /(.*)=/ ? self[$1.to_sym] = a[0] : self[name]\n end\n def self.settings\n @settings\n end\nend\n\np App.settings.console\nApp.settings.file &lt;&lt; \"afile.rb\"\np App.settings.file\n</code></pre>\n\n<p>Additionally you can use Settings as a constant, as in your original code:</p>\n\n<pre><code>module App\n # ...\n def self.const_missing(name)\n name == :Settings ? @settings : super\n end\nend\n\np App::Settings.console\nApp::Settings.file &lt;&lt; \"afile.rb\"\np App::Settings.file\n\nrequire 'yaml'\np App::Settings.to_yaml\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T07:17:34.720", "Id": "1847", "Score": "0", "body": "please can you explain the purpose of App.settings.method_missing?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T17:42:33.293", "Id": "1863", "Score": "0", "body": "@dsjbirch, without this you can only access one of the settings with `App.settings[:console]`. Is just a wrapper to convert a undefined method (like `console`) to `[:console]`. I think it makes the interface better." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T18:59:24.407", "Id": "2944", "Score": "0", "body": "method_missing and const_missing here unnecessary and will only cause later debugging confusion. Use an OpenStruct instead. If you want a constant, make a constant. -1" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T14:35:34.850", "Id": "1020", "ParentId": "1015", "Score": "3" } }, { "body": "<p>So much gratuitous and unnecessary metaprogramming in the answers. <strong>Do the simplest thing that could possibly work</strong>.</p>\n\n<pre><code>require 'ostruct'\n\nmodule App\n Settings = OpenStruct.new({\n :console =&gt; true,\n :file =&gt; []\n })\nend\n\nApp::Settings.console # =&gt; true\n\nApp::Settings.widget = 'frobnosticated'\nApp::Settings.widget # =&gt; 'frobnosticated'\n</code></pre>\n\n<p>This will give you the behavior you're looking for with none of the metaprogramming cognitive overhead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T19:07:01.530", "Id": "1685", "ParentId": "1015", "Score": "6" } } ]
{ "AcceptedAnswerId": "1685", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-26T19:01:35.590", "Id": "1015", "Score": "9", "Tags": [ "ruby", "ruby-on-rails", "singleton", "configuration" ], "Title": "Storing a Ruby app's settings" }
1015
<p>I'm just wondering if the following is the best way to write a dao function. Should I get the entity manager before the transaction and close it after the transaction every time? Should I write transactions inside a dao?</p> <pre><code>public void sendBack(Long requestId,String comments){ EntityManager em = getEntityManager(); em.getTransaction().begin(); String update = "update CsRequestReceivers set activeInd = :activeInd,sendBackComments=:comments where requestId = :requestId and activeInd = :oldActiveInd"; em.createQuery(update).setParameter("activeInd", 0l) .setParameter("comments", comments) .setParameter("requestId", requestId) .setParameter("oldActiveInd", 1l) .executeUpdate(); em.getTransaction().commit(); em.close(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T08:10:28.343", "Id": "62836", "Score": "0", "body": "I think you refer to this thread of stackoverflow. [Link](http://stackoverflow.com/questions/4031433/dao-and-service-layer-with-hibernate)" } ]
[ { "body": "<p>It depends on your app context. If im writting a web app Id create a filter which would getEntityManager(), begin() the transaction, then add it to the request scope, .doFilter() and pass it to the dao in the constructor (at the controller, of course).</p>\n\n<p>When it returns to the filter id commit(), or even rollback() if any exception happens.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-25T12:50:19.483", "Id": "6288", "ParentId": "1021", "Score": "3" } } ]
{ "AcceptedAnswerId": "6288", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-27T15:15:30.223", "Id": "1021", "Score": "4", "Tags": [ "java", "hibernate" ], "Title": "Dao function using hibernate" }
1021
<p>Here is my problem abstracted to <code>Bird</code> classes. I know that number of <code>Bird</code>s will increase on the future and new behaviors might be needed. With 10 Birds first design might not look so simple and lead to lots of duplicated code. On the other hand, second design can be perceived as "class explosion". Which of these two designs would be considered best-practice?</p> <p><strong>Classic:</strong></p> <pre><code>#include &lt;iostream&gt; class Bird { public: virtual void Fly() const = 0; virtual void Speak() const = 0; }; class Eagle : public Bird { public: virtual void Fly() const { std::cout &lt;&lt; "Eagle shall fly now!" &lt;&lt; std::endl; } virtual void Speak() const { std::cout &lt;&lt; "Eagle speaking!" &lt;&lt; std::endl; } }; class Penguin : public Bird { public: virtual void Fly() const { std::cout &lt;&lt; "Penguin shall fly now!" &lt;&lt; std::endl; } virtual void Speak() const { std::cout &lt;&lt; "Penquin speaking!" &lt;&lt; std::endl; } }; int main() { std::cout &lt;&lt; "..." &lt;&lt; std::endl; Bird* bird = NULL; bird = new Eagle(); bird-&gt;Fly(); bird-&gt;Speak(); delete bird; bird = NULL; bird = new Penguin(); bird-&gt;Fly(); bird-&gt;Speak(); delete bird; bird = NULL; return 0; } </code></pre> <p><strong>"Better?</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;cassert&gt; class FlyStyle { public: virtual void Fly() const = 0; }; class FlyHigh : public FlyStyle { virtual void Fly() const { std::cout &lt;&lt; "Fly high!" &lt;&lt; std::endl; } }; class NoFly : public FlyStyle { virtual void Fly() const { std::cout &lt;&lt; "No fly!" &lt;&lt; std::endl; } }; class SpeakStyle { public: virtual void Speak() const = 0; }; class SpeakLoud : public SpeakStyle { virtual void Speak() const { std::cout &lt;&lt; "Speak LAUD!!!!" &lt;&lt; std::endl; } }; class NoSpeak : public SpeakStyle { virtual void Speak() const { std::cout &lt;&lt; "No speaking!" &lt;&lt; std::endl; } }; class SuperBird { public: SuperBird(FlyStyle* fly, SpeakStyle* speak) : flystyle(fly), speakstyle(speak) { assert(NULL != flystyle); assert(NULL != speakstyle); } ~SuperBird() { delete flystyle; delete speakstyle;} virtual void Fly() const { flystyle-&gt;Fly(); } virtual void Speak() const { speakstyle-&gt;Speak(); } protected: FlyStyle* flystyle; SpeakStyle* speakstyle; }; class SuperBirdFactory { public: static SuperBird* createEagle() { return new SuperBird(new FlyHigh(), new SpeakLoud()); } static SuperBird* createPenguin() { return new SuperBird(new NoFly(), new NoSpeak()); } }; int main() { SuperBird* bird = NULL; bird = SuperBirdFactory::createEagle(); bird-&gt;Fly(); bird-&gt;Speak(); delete bird; bird = NULL; bird = SuperBirdFactory::createPenguin(); bird-&gt;Fly(); bird-&gt;Speak(); delete bird; bird = NULL; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T16:35:56.397", "Id": "1835", "Score": "1", "body": "The second example looks like typical Java design cruft." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T17:18:21.607", "Id": "1837", "Score": "0", "body": "hmm? care to elaborate?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T10:18:43.677", "Id": "13331", "Score": "0", "body": "You're missing a lot of virtual destructors all over the place." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T18:13:54.360", "Id": "58714", "Score": "0", "body": "From a design patterns standpoint, this might be an appropriate place to look at the Prototype Pattern rather than Factory." } ]
[ { "body": "<p>The first one is definitely better. You should try to use as few classes as will get the job done and also favour lots of small methods over a few big methods. These will make your code easier to read, understand and maintain. I think you could improve on your first one a bit:</p>\n\n<pre><code>#include &lt;iostream&gt;\nusing namespace std;\n\nclass Bird {\n public:\n void print(const char* str) {\n cout &lt;&lt; str &lt;&lt; endl;\n }\n};\n\nclass Eagle : public Bird {\n public:\n void fly() {\n print(\"Eagle shall fly now!\");\n }\n void speak() {\n print(\"Eagle speaking!\");\n }\n}; \n\nint main() {\n Eagle* eagle = new Eagle();\n eagle-&gt;fly();\n eagle-&gt;speak();\n return 0;\n}\n</code></pre>\n\n<p>Basically, I'm saying 'An Eagle is a Bird' and would do the same with other birds. I'm keeping the specific parts (eg. what needs to be done for fly() and speak()) in the children classes (such as Eagle) and the general parts (eg. the ability to print to stdout) in the parent class (Bird).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T12:36:58.153", "Id": "1872", "Score": "0", "body": "eh? so I can't have a list of Birds and make them all speak?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T16:25:37.307", "Id": "1876", "Score": "0", "body": "I don't get what you mean." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T19:43:54.927", "Id": "1025", "ParentId": "1022", "Score": "3" } }, { "body": "<p>I really prefer the first as it's simpler. You can always mixin other interfaces later:</p>\n\n<pre><code>class Predator {\n public:\n virtual void attack();\n}\n\nclass Eagle: public Bird, public Predator {\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T20:17:02.740", "Id": "1838", "Score": "2", "body": "Remember that C++ has multiple inheritance. There is no need for a hierarchy of classes like that" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T02:18:21.500", "Id": "1845", "Score": "0", "body": "So, mix in the `BirdOfPrey`? `class Eagle: public Bird: public BirdOfPrey`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T16:09:01.700", "Id": "1861", "Score": "0", "body": "think more along the lines of `class Eagle: public Bird, public Predator` where Bird has fly() and speak() and Predator has attack(). Now you can also have Shark which isn't a bird but is a Predator (also not a BirdOfPrey)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T16:10:06.877", "Id": "1862", "Score": "0", "body": "There we go - will edit that in." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T19:46:35.323", "Id": "1026", "ParentId": "1022", "Score": "2" } }, { "body": "<p>The fact that you have two completely different outputs from these two examples should be a huge clue as to the answer.</p>\n\n<pre><code>Eagle shall fly now!\nEagle speaking!\nPenguin shall fly now!\nPenguin speaking!\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>Fly high!\nSpeak LAUD!!!!\nNo fly!\nNo speaking!\n</code></pre>\n\n<p>If you want your Penguin class to fly like a Penguin, whatever that means, then you're probably right to go with the first example. If you want all non-flying birds to act the same way as each other when calling <code>fly()</code>, the second is probably better.</p>\n\n<p>That said, I doubt I'd go as far as using a Factory class. I would rename <code>SuperBird</code> as <code>Bird</code> and continue to derive <code>Eagle</code> and <code>Penguin</code> from that, passing the relevant <code>FlyStyle</code> and <code>SpeakStyle</code> to the superclass's constructor, such as</p>\n\n<pre><code>class Penguin : public Bird\n{\n public:\n Penguin() : Bird(new NoFly(), new NoSpeak()) {}\n}\n</code></pre>\n\n<p>This is attempting to follow <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">Single Responsibility Principle</a>, by saying \"if I want to change the action of all birds which do not fly, I shall change the <code>NoFly</code> class accordingly, but if I want to make a <code>Penguin</code> fly, I will change the <code>Penguin</code> class.\"</p>\n\n<p>The Factory Pattern is more appropriate to the opposing use case, where your calling code doesn't know or care which type of bird you wish to instantiate but does know enough information for the Factory class to make that decision, such as</p>\n\n<pre><code>bird = BirdFactory::create(CAN_FLY, MAKES_NOISE);\nbird.Fly();\nbird.Speak();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-27T19:55:02.303", "Id": "1028", "ParentId": "1022", "Score": "8" } }, { "body": "<p>First option is best. It is readable and KISS-compliant. If you ever need to share a flight implementation, you can write a mixin. Also, unrelated, you should look into RAII and get rid of these assert/new/delete.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T21:47:28.253", "Id": "1839", "Score": "0", "body": "I know what mixin is in Ruby but what do you call a mixin in c++?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T21:53:45.627", "Id": "1840", "Score": "1", "body": "@naz The same thing: a class you inherit from to get a few methods implemented." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T21:56:06.233", "Id": "1841", "Score": "0", "body": "ok :) in Ruby, inheritance is inheritance and mixin is a mixin so I was confused a bit, +1 for clarification" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T22:24:23.790", "Id": "1843", "Score": "0", "body": "Ha, sorry. D adds that kind of mixin. But multiple inheritance can achieve the same results, wherever it is supported." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T10:16:44.210", "Id": "13330", "Score": "0", "body": "How are asserts and RAII not orthogonal?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-01T23:13:34.033", "Id": "13391", "Score": "0", "body": "@Anton these asserts check for null pointers. RAII gets rid of pointers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-02T00:23:25.983", "Id": "13393", "Score": "0", "body": "@Tobu: Seeing as these objects are polymorphic, I don't think RAII could get rid of the pointers -- only convert them to smart pointers, which may still be NULL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T08:06:16.803", "Id": "13512", "Score": "0", "body": "@Anton references can be polymorphic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-04T19:13:48.043", "Id": "13535", "Score": "0", "body": "True, possible in some cases." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-27T21:34:26.797", "Id": "1029", "ParentId": "1022", "Score": "3" } }, { "body": "<p>If there will be different kinds of birds that share a flying or speaking style (\"strategy\" is what the Gang of Four calls this), then the second design makes sense. If all birds will have unique flying and speaking styles, stick with the first.</p>\n\n<p>If you don't know the answer yet, stick with the first design. In the absence of information, always prefer the simplest solution. It's easier to extend a simple design later than it is to simplify a needlessly extensible one.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T05:52:32.747", "Id": "1032", "ParentId": "1022", "Score": "5" } }, { "body": "<p>This first one is simpler and you might want to use it if you do not need a lot of flexibility. If you ask yourself this question, I think it means you might need flexibility.</p>\n\n<p>In this little example, the first method indeed have fewer classes but in general, if you need a lot of different combinations it might no be the case anymore. Take the second example, if your \"SuperBird\" is extended be compound of 5 different objects and for each one you have defined 5 abstract types: doing the same thing for the first example would need 3000 classes with a lot of boilerplate repeated in many classes.</p>\n\n<p>See the Gang of Four principle: favor object composition over class inheritance/</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T09:39:58.657", "Id": "1034", "ParentId": "1022", "Score": "0" } }, { "body": "<p>In my opinion, a better approach (along similar lines) is to avoid abstract base classes and instead use generic \"policy\" classes. You informally define an interface for each behaviour, and mix them into the class as template parameters. This avoids the need for dynamic memory allocation, and removes the overhead of virtual function calls; everything is resolved at compile time. Your example could be something like this:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\n// Flying styles must have interfaces compatible with this\n// struct FlyStyle\n// {\n// void Fly() const;\n// };\n\nstruct FlyHigh\n{\n void Fly() const\n {\n std::cout &lt;&lt; \"Fly high!\" &lt;&lt; std::endl;\n }\n};\n\nstruct NoFly\n{\n void Fly() const\n {\n std::cout &lt;&lt; \"No fly!\" &lt;&lt; std::endl;\n }\n};\n\n// Speaking styles must have interfaces compatible with this\n// struct SpeakStyle\n// {\n// void Speak() const;\n// };\n\nstruct SpeakLoud\n{\n void Speak() const\n {\n std::cout &lt;&lt; \"Speak LAUD!!!!\" &lt;&lt; std::endl;\n }\n};\n\nstruct NoSpeak\n{\n void Speak() const\n {\n std::cout &lt;&lt; \"No speaking!\" &lt;&lt; std::endl;\n }\n};\n\ntemplate &lt;class FlyStyle, class SpeakStyle&gt;\nclass SuperBird\n{\n public:\n void Fly() const\n {\n flystyle.Fly();\n }\n void Speak() const\n {\n speakstyle.Speak();\n }\n private:\n FlyStyle flystyle;\n SpeakStyle speakstyle;\n};\n\ntypedef SuperBird&lt;FlyHigh, SpeakLoud&gt; Eagle;\ntypedef SuperBird&lt;NoFly, NoSpeak&gt; Penguin;\n\nint main()\n{\n Eagle eagle;\n eagle.Fly();\n eagle.Speak();\n\n Penguin penguin;\n penguin.Fly();\n penguin.Speak();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-05T19:37:19.897", "Id": "2058", "Score": "0", "body": "Great Scott! That's cool!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-16T22:37:34.447", "Id": "2301", "Score": "0", "body": "Agreed, this will be very useful for cuda projects where I don't have the ability to use virtual methods of dynamic memory allocation!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-01T21:44:06.510", "Id": "8690", "Score": "0", "body": "Let's take the case of Eagle's case where the wings are cut. Now how could we change the current ability to Fly ? I mean, this solution is good but the point I am trying to make is we can't change the behaviour in between." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-02T12:07:28.083", "Id": "8706", "Score": "0", "body": "@Jagannath: Indeed, static polymorphism is no good for changing behaviour dynamically. On the other hand, neither is dynamic polymorphism, at least in C++ - you can't change the dynamic type of an object, only instantiate other objects with different types. In either case, you'd need to add some runtime state to `Eagle` if you want to remove the wings from any particular instantiation." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T13:10:20.720", "Id": "1038", "ParentId": "1022", "Score": "17" } }, { "body": "<p>Start with the first, refactor to the second.</p>\n\n<p>The interface is the same in both situations. All of the code which is using these classes should not care which method you choose to implement. </p>\n\n<p>You should implement the first, simpler method. When it becomes useful, you should apply other techniques. For example, if you find yourself having a lot of flightless birds you might implement a FlightlessBird class which has the common logic. When speaking becomes too complicated, you might want to break it out into its own object. In other words, implement parts of the second version as they become neccessary.</p>\n\n<p>Your second version is attempting to have maximum flexibility. Attempting to do that has a strange tendency to result in lots of obtuse code and still lack the flexibility that you need. Therefore, in most situations its better to wait until you have a better idea of what you actually need rather then guessing ahead of time.</p>\n\n<p>There is no significant benefit to implementing the flexible version now. There are definite benefits to implementing the simple version now. You only a basic idea of what the code will be required to do later. Attempting to implement that now will only produce a mess.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T16:53:24.690", "Id": "1046", "ParentId": "1022", "Score": "4" } }, { "body": "<p>Let's see: you've gotten votes for the first and for the second. Hmm...how can I argue with both. Oh, I've got it: both designs must be wrong!</p>\n\n<p>From an abstract viewpoint, you have nothing to justify the Bird/Eagle/Penguin classes as <em>classes</em> at all. In particular, even though you've defined a couple of virtual functions, the functions aren't really doing anything different at all. In all cases, they do exactly the same thing -- print out a string.</p>\n\n<p>As such, you should probably just create birds, and when you create a bird you should specify the \"flyingstyle\" and \"speakingstyle\" as arguments to the constructor:</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\n\nclass bird { \n std::string movingstyle;\n std::string speakingstyle;\npublic:\n bird(std::string const &amp;ms, std::string const &amp;ss) \n : movingstyle(ms), speakingstyle(ss)\n {}\n\n void speak() { std::cout &lt;&lt; speakingstyle &lt;&lt; \"\\n\"; }\n void move() { std::cout &lt;&lt; movingstyle &lt;&lt; \"\\n\"; }\n};\n\nint main() {\n bird birds[2] = {\n bird(\"Eagle Flying\", \"Eagle speaking\"), \n bird(\"Penguin swimming\", \"Penguin speaking\")\n };\n\n for (int i=0; i&lt;2; i++) {\n birds[i].speak();\n birds[i].move();\n }\n return 0;\n}\n</code></pre>\n\n<p>Reserve separate classes for objects that truly have different behavior, not the same behavior with different values.</p>\n\n<p>I'd also note that I've halfway-repaired a basic flaw in your original hierarchy. By including \"fly\" in your base class, you've asserted that all birds can fly -- an outright falsehood. Here I've changed that the more abstract concept \"move\" instead. With this, you can have Penguins that swim, Ostriches that run, and Eagles that fly.</p>\n\n<p>Something similar should probably be done with the \"speak\". Some birds don't make sounds, so you should consider whether you want something like:</p>\n\n<pre><code>class bird {};\n\nclass speaking_bird : public bird {\npublic: \n virtual void speak() = 0; \n};\n\nclass silent_bird : public bird {};\n</code></pre>\n\n<p>This correctly models the fact that some birds \"speak\" and others don't. It also has a fundamental difference in behavior between \"speaking bird\" and \"silent bird\" that justifies using inheritance.</p>\n\n<p>Alternatively, you could assert in the design that all birds can speak, but in the implementation say that some birds (that you can I know can't speak) should just never be asked to speak:</p>\n\n<pre><code>class bird {\n bool silent;\npublic:\n void speak() { if (silent) throw runtime_error(\"Cannot speak\"); }\n};\n</code></pre>\n\n<p>There's a fair basis for saying this is a kludge, but in some cases, it's worth avoiding creating extra levels of inheritance (and such) just to cover obscure corner cases that you'll probably never care about in real use anyway. At the same time, this can lead to littering other code with checks for those corner cases to avoid invoking functions that won't work, and you'd generally rather avoid that as well. As such, you need to look at the specific situation to decide which is the least of the available evils.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T04:09:13.033", "Id": "1048", "ParentId": "1022", "Score": "5" } }, { "body": "<p>It's much more important to be able to change design in future that to select \"the correct design\" from the start.</p>\n\n<p>The simple way to have this ability is to hide as much as possible.</p>\n\n<p>Are users happy with one class with virtual function? Hide the knowledge that different birds have or have not separate classes.</p>\n\n<p>Are users OK with delegating creation of bird to your module? Hide all constructors of Bird (or make it abstract).</p>\n\n<p>Internally - use whatever is good for current purposes, and change the internal design once it will become inconvenient.</p>\n\n<p>Thus interface may be the following:</p>\n\n<pre><code>class Bird\n{\npublic:\n virtual void Fly()=0;\n virtual void Speak()=0;\n};\nclass BirdFactory\n{\npublic:\n static Bird *CreateEagle();\n ...\n};\n</code></pre>\n\n<p>Everything other should be hidden either as a private stuff of some class or surrounded with other hints about being internal (namespace \"detail\", directory \"internal\", etc).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T20:44:59.503", "Id": "1108", "ParentId": "1022", "Score": "0" } }, { "body": "<p>The first example is fine to start with, but you should have in mind where you want it to go where more birds are added, so you don't make changes incompatible with that inevitable change.</p>\n\n<p>First, what are your requirements? I assume from your examples:</p>\n\n<ol>\n<li>There will be a common interface for bird types (called \"Bird\" in the first example)</li>\n<li>You initially expect all functions to deal with either a bird type, or an eagle type, but you don't know if you will ever need to pass a pointer to a nofly type.</li>\n<li>You would prefer that if you declare an eagle type at compile time, all the code can be instantiated then, as efficiently as in the first example?</li>\n</ol>\n\n<p>If so, how about:</p>\n\n<pre><code>class Bird\n{\n public:\n virtual void Fly() const = 0;\n virtual void Speak() const = 0;\n protected:\n void FlyYes() const {\n std::cout &lt;&lt; \"No fly!\" &lt;&lt; std::endl;\n }\n /*\n ...\n */\n\n};\n\n/* final */ class Eagle : public Bird\n{\n public:\n void Fly() const\n {\n FlyYes();\n }\n /*\n ...\n */\n};\n\n\n/*\n ...\n*/\n</code></pre>\n\n<p>That's a compromise, but:</p>\n\n<ul>\n<li>it should all happen at compile time</li>\n<li>it should prevent subtle differences in supposedly equivalent \"fly\" types</li>\n<li>you can always implement custom functions for birds that fly in a specific way, without needing to create lots more classes for each</li>\n<li>and you can easily move those into the base class if you later want to share them</li>\n<li>if you later realise that all of your birds do fall into some categories, you can create some intermediate partially abstract classes which fall between bird and most leaf classes, eg. a BirdFly class that implements the fly function as I did in Eagle, which Eagle can then inherit from.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-16T21:38:09.193", "Id": "1315", "ParentId": "1022", "Score": "2" } } ]
{ "AcceptedAnswerId": "1038", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-27T15:48:21.707", "Id": "1022", "Score": "14", "Tags": [ "c++", "inheritance", "polymorphism" ], "Title": "Design dilemma: extensibility vs simplicity" }
1022
<p>Here's what I've right now:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import functools import math import time class Timer(object): def __init__(self): self.__values = [] def start(self): self.__start = time.time() return self def stop(self): self.__values.append(int(round((time.time() - self.__start) * 1000))) self.__start = None return self @property def average(self): return sum(self.__values) / len(self.__values) @property def deviation(self): if self.average: return math.sqrt(sum((v - self.average) ** 2 for v in self.__values) / self.runs) return 0 @property def elapsed(self): return sum(self.__values) @property def runs(self): return len(self.__values) class Profiler(object): __timers = {} @staticmethod def info(timer_id): if not Profiler.__timers.has_key(timer_id): raise Exception('Timer not started') return Profiler.__timers[timer_id] @staticmethod def profile(f): @functools.wraps(f) def wrap(self=None, *args, **kwargs): method = self.__class__.__name__ + '.' + f.func_name if self \ else f.func_name Profiler.start(method) r = f(self, *args, **kwargs) if self else f(*args, **kwargs) Profiler.stop(method) return r return wrap @staticmethod def reset(timer_id): Profiler.__timers[timer_id] = Timer() @staticmethod def start(timer_id): if not Profiler.__timers.has_key(timer_id): Profiler.reset(timer_id) Profiler.__timers[timer_id].start() @staticmethod def stop(timer_id): if not Profiler.__timers.has_key(timer_id): raise Exception('Timer not started') Profiler.__timers[timer_id].stop() if __name__ == '__main__': class Test(object): def isPrime(self, n): if n &lt; 2 or (n % 2) == 0: return n == 2 f = 3 while (f * f) &lt;= n: if (n % f) == 0: return False f += 2 return True @Profiler.profile def run(self): return filter(self.isPrime, range(1, 1000001)) test = Test() for x in range(5): test.run() p = Profiler.info('Test.run') print 'runs = %d' % p.runs print 'elapsed = %d ms' % p.elapsed print 'average = %d ms' % p.average print 'deviation = %d ms' % p.deviation </code></pre> <p>I'm looking for suggestions to improve it and you're welcome to suggest. :)</p> <p>The Profiler.profile decorator supports both functions and class methods. I've written a small test to demonstrate my profiler.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T08:37:25.880", "Id": "1849", "Score": "0", "body": "As written it doesn't seem to handle recursion. If you move the start/stop time tracking into `profile()` it would." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T19:00:39.077", "Id": "62806", "Score": "0", "body": "Why not start from [cProfile](http://docs.python.org/library/profile.html), and then operate on the [Stats](http://docs.python.org/library/profile.html#the-stats-class) object generated by that?" } ]
[ { "body": "<pre><code>#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport functools\nimport math\nimport time\n\nclass Timer(object):\n def __init__(self):\n self.__values = []\n</code></pre>\n\n<p>You are using prefix __ to denote private attributess. This is perfectly valid and has special support within python. Having said that, I'm not a fan of it. Its designed for use when you are subclassing objects to prevent accidents. I think that if you are not designing your object to be subclassed, you should stick with single underscores.</p>\n\n<pre><code> def start(self):\n self.__start = time.time()\n\n return self\n</code></pre>\n\n<p>Some frameworks do make use of this return self paradigm. However, its kinda unusual and will lead to code being confusing if you are not used to it. As it is you don't seem to be making use of this. I'd just get rid of return self. This doesn't seem to be the type of object which works well with the pattern anyways.</p>\n\n<pre><code> def stop(self):\n self.__values.append(int(round((time.time() - self.__start) * 1000)))\n</code></pre>\n\n<p>The operations being performed here are just long enough to come across as awkward, I'd write it as</p>\n\n<pre><code>seconds_elapsed = time.time() - self.__start\nmilliseconds_elapsed = int(round(seconds_elapsed*1000))\nself.__values.append(milliseconds_elapsed)\n</code></pre>\n\n<p>As another note, don't be afraid of floats. You'd probably be better off storing a list of floating point seconds rather then integer milliseconds. The code would be clearer and there is probably no noticeable difference in efficiency. </p>\n\n<pre><code> self.__start = None\n\n return self\n\n @property\n def average(self):\n return sum(self.__values) / len(self.__values) \n\n @property\n def deviation(self):\n if self.average:\n return math.sqrt(sum((v - self.average) ** 2 for v in self.__values) / self.runs)\n\n return 0\n</code></pre>\n\n<p>I recommend using the numpy library which has functions to calculate average/stdev/pretty much everything. The math done in numpy will be much more efficient then your python versions. </p>\n\n<pre><code> @property\n def elapsed(self):\n return sum(self.__values)\n\n @property\n def runs(self):\n return len(self.__values)\n</code></pre>\n\n<p>I don't like the name Timer for the class because it spends most of its effort keeping track of values not measuring time.</p>\n\n<pre><code>class Profiler(object):\n __timers = {}\n\n @staticmethod\n def info(timer_id):\n if not Profiler.__timers.has_key(timer_id):\n raise Exception('Timer not started')\n\n return Profiler.__timers[timer_id]\n</code></pre>\n\n<p>If you are going to store state on your class object, use classmethod like so:</p>\n\n<pre><code> @classmethod\n def info(cls, timer_id):\n if not cls.__timers.has_key(timer_id):\n raise Exception('Timer not started')\n\n return cls.__timers[timer_id]\n</code></pre>\n\n<p>There also does not appear to be a good reason to be storing this state statically. I suggest that you really should implement this as a normal object. There are few cases where storing state on a static object is justified.</p>\n\n<pre><code> def info(self, timer_id):\n if not self.__timers.has_key(timer_id):\n raise Exception('Timer not started')\n\n return self.__timers[timer_id]\n</code></pre>\n\n<p>Additionally, don't be afraid of exceptions. In python you shouldn't (in general) try to detect whether an exception will be thrown before attempting an operation. Just perform the operation and catch the exception. The above version ends up locating an element in a dictionary twice, which is just a waste. The above function should be implemented as: </p>\n\n<pre><code> def info(self, timer_id):\n try:\n return self.__timers[timer_id] \n except KeyError:\n raise Exception('Timer not started')\n</code></pre>\n\n<p>Similar comments apply to your other functions.</p>\n\n<pre><code> @staticmethod\n def profile(f):\n @functools.wraps(f)\n def wrap(self=None, *args, **kwargs):\n</code></pre>\n\n<p>You assume that your first parameter will be self (if it exists). Depending on how this is called, self may actually already be bundled into f as a method object. Also, if you are calling a function which is not a method something else will come in there. You shouldn't capture self this way, just let all parameters go into *args</p>\n\n<pre><code> method = self.__class__.__name__ + '.' + f.func_name if self \\\n else f.func_name\n</code></pre>\n\n<p>As mentioned, you shouldn't capture self the way you do. The correct place to find the class is f.im_class. Be careful! That attribute won't be there on non-methods.</p>\n\n<pre><code> Profiler.start(method)\n r = f(self, *args, **kwargs) if self else f(*args, **kwargs)\n</code></pre>\n\n<p>I recomment calling r, return_value for better clarity. Also by eliminating self, you'll make this bit of code cleaner\n Profiler.stop(method)</p>\n\n<p>This is actually wrong in the case of recursion as another commenter has pointed out. Also, since Timer is really concerned with keeping track of times, perhaps calculating time spent would be better here. </p>\n\n<pre><code> return r\n\n return wrap\n</code></pre>\n\n<p>Your API is counterintuitive on this point. I'd except a function called profile to profile a function, not return a new function which I then have to call in order to profile it. For what the function does it should be called profiled. </p>\n\n<pre><code> @staticmethod\n def reset(timer_id):\n Profiler.__timers[timer_id] = Timer()\n\n @staticmethod\n def start(timer_id):\n if not Profiler.__timers.has_key(timer_id):\n Profiler.reset(timer_id)\n\n Profiler.__timers[timer_id].start()\n\n @staticmethod\n def stop(timer_id):\n if not Profiler.__timers.has_key(timer_id):\n raise Exception('Timer not started')\n\n Profiler.__timers[timer_id].stop()\n\nif __name__ == '__main__':\n class Test(object):\n def isPrime(self, n):\n if n &lt; 2 or (n % 2) == 0:\n return n == 2\n\n f = 3\n\n while (f * f) &lt;= n:\n if (n % f) == 0:\n return False\n\n f += 2\n\n return True\n\n @Profiler.profile\n def run(self):\n return filter(self.isPrime, range(1, 1000001))\n\n test = Test()\n\n for x in range(5):\n test.run()\n\n p = Profiler.info('Test.run')\n print 'runs = %d' % p.runs\n print 'elapsed = %d ms' % p.elapsed\n print 'average = %d ms' % p.average\n print 'deviation = %d ms' % p.deviation\n</code></pre>\n\n<p>I think a better API to implement would be one that works like this:</p>\n\n<pre><code> class Test(object):\n def isPrime(self, n):\n if n &lt; 2 or (n % 2) == 0:\n return n == 2\n\n f = 3\n\n while (f * f) &lt;= n:\n if (n % f) == 0:\n return False\n\n f += 2\n\n return True\n\n @profiled\n def run(self):\n return filter(self.isPrime, range(1, 1000001))\n\n test = Test()\n\n for x in range(5):\n test.run()\n\n stats = Test.run.stats\n print 'runs = %d' % stats.runs\n print 'elapsed = %d ms' % stats.elapsed\n print 'average = %d ms' % stats.average\n print 'deviation = %d ms' % stats.deviation\n</code></pre>\n\n<p>Essentially, store your Timer object on the function object itself. That will simplify your code considerably because you are using python's name resolution rather then your own.</p>\n\n<p>As a final note, there are plenty of good profiling tools out there for python. You are probably best off using one one of those.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T22:38:40.460", "Id": "1109", "ParentId": "1030", "Score": "6" } } ]
{ "AcceptedAnswerId": "1109", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-28T03:43:07.433", "Id": "1030", "Score": "5", "Tags": [ "python", "python-2.x" ], "Title": "Suggestions for a Profiler class in Python" }
1030
<p>Originally, I had everything in the base method #read_wall(). I'm not sure what happened with the array, but when I tried:</p> <p><code>array = result + second + third + fourth</code>. I was left with data from only the original result. So I created this working disaster. <strong>Can you please help me refactor this?</strong></p> <pre><code> # Gets the user's Wall def read_wall(fbuserid) result ||= graph.get_connections(fbuserid, 'feed') end def second_wall(fbuserid) result ||= graph.get_connections(fbuserid, 'feed') second ||= result.next_page end def third_wall(fbuserid) result ||= graph.get_connections(fbuserid, 'feed') second ||= result.next_page third ||= second.next_page end def fourth_wall(fbuserid) result ||= graph.get_connections(fbuserid, 'feed') second ||= result.next_page third ||= second.next_page fourth ||= third.next_page end # Collects your friends' wall Posts and puts the IDs into an array def get_post_ids(fbuserid) x ||= read_wall(fbuserid) var = [] for i in 0..25 if find_nil(x, [i,'id']).nil? == false var &lt;&lt; x[i]['id'] end end second_wall ||= second_wall(fbuserid) for i in 0..25 if find_nil(second_wall, [i,'id']).nil? == false var &lt;&lt; second_wall[i]['id'] end end third_wall ||= third_wall(fbuserid) for i in 0..25 if find_nil(third_wall, [i,'id']).nil? == false var &lt;&lt; third_wall[i]['id'] end end fourth_wall ||= fourth_wall(fbuserid) for i in 0..25 if find_nil(fourth_wall, [i,'id']).nil? == false var &lt;&lt; fourth_wall[i]['id'] end end @get_post_ids = var end </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T08:29:07.057", "Id": "1848", "Score": "1", "body": "Is it meaningful in Ruby to declare a local variable with the same name as a function and still expect to reference both in the same context? `second_wall ||= second_wall(fbuserid) ... find_nil(second_wall, ...)`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T10:37:46.040", "Id": "1852", "Score": "1", "body": "@David: Yes, `x = x()` works in ruby and sets the local variable `x` to the result of calling the method `x`. However it's not necessarily good style." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-06T18:57:46.747", "Id": "2943", "Score": "0", "body": "It should be obvious, but shadowing a method with a local variable is a terrible code smell, almost certain to cause confusion and trivial to avoid. So **don't do it**. There's no excuse." } ]
[ { "body": "<pre><code>def fourth_wall(fbuserid)\n result ||= graph.get_connections(fbuserid, 'feed')\n second ||= result.next_page\n third ||= second.next_page\n fourth ||= third.next_page\nend\n</code></pre>\n\n<p>A couple of problems here: <code>result</code>, <code>second</code>, <code>third</code> and <code>fourth</code> are all local variables. This means they won't persist after the method call is finished and they will never persist after the method call is finished. So:</p>\n\n<ol>\n<li>You don't need to set the <code>fourth</code> variable as you never use it in the method and it won't be available after</li>\n<li>You don't need <code>||=</code> as the variables will never be set anyway.</li>\n</ol>\n\n<p>I.e. your code is equivalent to this:</p>\n\n<pre><code>def fourth_wall(fbuserid)\n result = graph.get_connections(fbuserid, 'feed')\n second = result.next_page\n third = second.next_page\n third.next_page\nend\n</code></pre>\n\n<p>Or just:</p>\n\n<pre><code>def fourth_wall(fbuserid)\n graph.get_connections(fbuserid, 'feed').next_page.next_page.next_page\nend\n</code></pre>\n\n<p>The same goes for the other <code>wall</code> methods.</p>\n\n<hr>\n\n<p>Further your <code>fourth_wall</code> method contains the entire code of the <code>third_wall</code> method (which contains the entire <code>second_wall</code> method and so on). This is bad style. Just let the methods call each other:</p>\n\n<pre><code>def fourth_wall(fbuserid)\n third_wall(fbuserid).next_page\nend\n</code></pre>\n\n<p>(And again the same for the other <code>wall</code> methods of course)</p>\n\n<hr>\n\n<p>However since you seem to only call those functions together (i.e. you never use <code>fourth_wall</code> without having used <code>third_wall</code> before) it seems much more sensible to have one method which returns all for walls:</p>\n\n<pre><code>def four_walls(fbuserid)\n first = graph.get_connections(fbuserid, 'feed')\n # For more than 4 pages the following should be replaced by a loop\n second = first.next_page\n third = second.next_page\n fourth = third.next_page\n [first, second, third, fourth]\nend\n</code></pre>\n\n<hr>\n\n<p>In your <code>get_post_ids</code> method you're repeating the same code four times. This is again bad style. You're also creating an empty array and then appending to it from a loop. This is often (but not always) a sign of bad code in ruby as well. Also using <code>x</code> and <code>var</code> as variable names is not a good idea and having a variable name that starts with <code>@get_</code> just seems weird and confusing.</p>\n\n<p>I'm also assuming that your <code>find_nil</code> method is supposed to check whether either <code>wall[i]</code> or <code>wall[i]['id']</code> are nil. There are better ways to do this.</p>\n\n<p>In this case you can use map on the walls and then the numbers from 0 to 25 to create an array of user ids for each wall, then use <code>compact</code> to remove <code>nil</code>s and <code>flatten</code> to turn the array into one single array rather than an array of four subarray. Thus your whole <code>get_post_ids</code> method can be replaced with this:</p>\n\n<pre><code>def retrieve_post_ids(fbuserid)\n walls = four_walls(fbuserid)\n @post_ids = walls.map do |wall|\n # Iterate over the first 26 entries in wall\n (0..25).map do |i|\n wall[i] &amp;&amp; wall[i]['id']\n end.compact\n end.flatten\nend\n</code></pre>\n\n<hr>\n\n<p>Though if the <code>wall</code>s allow slicing similar to arrays, this would be better:</p>\n\n<pre><code>def retrieve_post_ids(fbuserid)\n walls = four_walls(fbuserid)\n @post_ids = walls.map do |wall|\n # Iterate over the first 26 entries in wall\n wall[0..25].map do |entry|\n entry &amp;&amp; entry['id']\n end.compact\n end.flatten\nend\n</code></pre>\n\n<p>If the wall never contains more than 26 elements, you don't even need the <code>[0..25]</code> and you can just use <code>well.map</code>.</p>\n\n<hr>\n\n<p>However it occurs to me that the reason you needed the nil check at all was that each wall contains 25 elements and you got <code>nil</code> for index <code>25</code> because you did not realize that ranges using <code>..</code> are inclusive. In that case you can just use:</p>\n\n<pre><code>def retrieve_post_ids(fbuserid)\n walls = four_walls(fbuserid)\n @post_ids = walls.map do |wall|\n # Iterate over the entries in wall\n wall.map do |entry|\n entry['id']\n end\n end.flatten\nend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-05T11:46:00.670", "Id": "2051", "Score": "0", "body": "Everything I thought of with more besides!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T02:29:05.600", "Id": "2999", "Score": "1", "body": "Maybe use `flat_map` instead of 1st `map`, so we'll not need `flatten`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T10:25:22.723", "Id": "1036", "ParentId": "1031", "Score": "13" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-28T05:25:48.470", "Id": "1031", "Score": "7", "Tags": [ "ruby", "pagination" ], "Title": "Collecting friends' wall posts" }
1031
<p><strong>Option 1 - nice and simple</strong></p> <pre><code>private void GetFileReady() { private StringBuilder fileContents = new StringBuilder(); using (var sr = new StreamReader("C:\A big file.txt")) { fileContents.Append(sr.ReadToEnd()); } } </code></pre> <p><strong>Option 2 - less simple</strong></p> <pre><code>private void GetFileReady2() { private StringBuilder fileContents = new StringBuilder(); const int bufferSize = 1024; var buffer = new Char[bufferSize]; var count = bufferSize; using (var sr = new StreamReader("C:\A big file.txt")) { while (count &gt; 0) { count = sr.Read(buffer, 0, bufferSize); fileContents.Append(buffer, 0, count); } } } </code></pre> <p>Would option 2 be better for something esoteric like memory allocation?</p>
[]
[ { "body": "<p>I don't think there's a significant difference between your two options when it comes to memory allocations. In both cases, you're reading the entire file into memory, which trumps any minor differences that might exist in the number of objects allocated by the two options. (Though both options are also immediately discarding those contents since they are only stored in local variables, but I'm assuming that this is just a highly simplified example.)</p>\n\n<p>If you're concerned about memory consumption when using a big file, you need to not read in the entire file all at once. Instead, you should load chunks out of the file as needed by your application, and discard them when no longer needed so the memory can be reclaimed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-12T00:22:32.860", "Id": "400447", "Score": "0", "body": "This answer is incorrect: the first implementation requires double the file size temporarily during `fileContents.Append()` before the result of `sr.ReadToEnd()` can be discarded, while the second only requires 2kB overhead for the read buffer. Apologies for the comment on a seven-year old answer, but this does still come up on google!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T13:20:45.400", "Id": "1039", "ParentId": "1037", "Score": "2" } }, { "body": "<p>Is the goal to get a string containing the content of the file? or to add the content of a file to an existing StringBuilder?</p>\n\n<p>if it's the former then Option 1 can drop the string builder altogether ... or better yet.</p>\n\n<pre><code>string value = File.ReadAllText(\"C:\\A big file.txt\");\n</code></pre>\n\n<p>if it's the latter then you might want to think about using <code>StringBuilder.EnsureCapacity()</code> to avoid the overhead of resizing the buffer more then it needs to. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T15:08:16.597", "Id": "1859", "Score": "0", "body": "cool, I wasn't aware of EnsureCapacity. I'll use that to size the stringbuilder from FileInfo" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T13:23:25.220", "Id": "1040", "ParentId": "1037", "Score": "11" } } ]
{ "AcceptedAnswerId": "1040", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-28T13:00:06.627", "Id": "1037", "Score": "2", "Tags": [ "c#", "comparative-review", "io" ], "Title": "Reading file contents into a string" }
1037
<p>It is an online learning application with different types of learnable items, that different users learn.</p> <p>The users learn by spaced repetition (once right, wait a couple days, ask again), success is mirrored in stages and mistakes made.</p> <p>I intend to use this for scientific data collection in the near future, so there is one table especially, user_terms_answers where data amasses at a granularity not currently used by the application.</p> <p>I especially had trouble with figuring out how to arrange my learnable types, and I'm not sure if I chose the optimal solution.</p> <p>Since this is potentially not understood just from looking at the chart, the two basic types are:</p> <ul> <li><strong>known – unknown</strong>: What year did Thomas Edison die? – [1931] - <em>one question &amp; one answer</em></li> <li><strong>cloze tests</strong> or <strong>gap texts</strong>: Slow loris are of the genus [Nycticebus] and of the subfamily [Lorinae] - <em>one question &amp; many answers</em>!</li> </ul> <h3>My schema</h3> <p>The part in gray ships with the TankAuth component of CodeIgniter and I'm hoping that this is properly done already. </p> <p><a href="https://i.stack.imgur.com/5kpjI.png" rel="nofollow noreferrer">Database schema</a></p> <p>In response to a now-gone comment by l0bo, I <a href="http://ul.dyden.de/schemaspy/d00fab60/index.html" rel="nofollow noreferrer">visualized this in SchemaSpy</a> as well.</p> <h3>Common queries</h3> <p>These the views that I have so far, they reflect quite well what the application will usually want.<br> They also reflect how I run into trouble with the way I chose to implement "languages".</p> <pre><code>CREATE VIEW `retrieve_user_term_or_gap` AS SELECT u.id, u.learnable_id, u.user_id, u.stage, u.mistakes, u.time_due, u.added, terms.language, terms.field, terms.known, terms.unknown, terms.hint, gaps.cloze_id, gaps.gap, c.language AS cloze_language, c.field AS cloze_field, c.cloze, c.hint AS cloze_hint -- this is bad, not 3NF FROM user_terms AS u LEFT JOIN learnables AS l ON u.learnable_id = l.id LEFT JOIN terms ON l.id = terms.learnable_id LEFT JOIN gaps ON l.id = gaps.learnable_id LEFT JOIN clozetests AS c ON c.id = gaps.cloze_id CREATE VIEW `how_many_due` AS SELECT COUNT(id) FROM user_terms WHERE stage &lt; 5 AND DATE(time_due) &lt;= CURDATE() CREATE VIEW `due_terms` AS SELECT u.id, u.learnable_id, u.user_id, u.stage, u.mistakes, u.time_due, u.added, terms.language, terms.field, terms.known, terms.unknown, terms.hint, gaps.cloze_id, gaps.gap, c.language AS cloze_language, c.field AS cloze_field, c.cloze, c.hint AS cloze_hint -- this is bad, not 3NF FROM user_terms AS u LEFT JOIN learnables AS l ON u.learnable_id = l.id LEFT JOIN terms ON l.id = terms.learnable_id LEFT JOIN gaps ON l.id = gaps.learnable_id LEFT JOIN clozetests AS c ON c.id = gaps.cloze_id WHERE DATE(u.time_due) &lt;= CURDATE() AND u.stage &lt; 5 ORDER BY terms.language, terms.field, u.id </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T14:41:44.083", "Id": "62283", "Score": "0", "body": "could you add the Schema picture to the question rather than a link? or along with a link?" } ]
[ { "body": "<p>You do have the field <code>languages</code> several times as a string. I'd create a general table <code>languages</code> with all language-related informations and have 1:m or n:m relations to other tables. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T16:56:59.930", "Id": "1877", "Score": "0", "body": "I thought about this, but said general table would contain *only* the language and possibly a surrogate key. The user-language table would still be necessary. But I'm also having a hard time to name the pros and cons. Is this not normalized as it is?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T17:29:22.630", "Id": "1881", "Score": "0", "body": "As long as you do use the language-string as an atomic type it's ok. But you can't add additional propertys to a language then (as i assume `special_chars` is) you add redundancy." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T17:50:33.050", "Id": "1884", "Score": "0", "body": "Well, special_chars is a property of the user-language combination, so that table would still be there, if a general language table existed. A *user-independent* table like `terms ` and `clozetests` would only contain the language. One pro would be, though, that if I ever add user-independent properties to languages, I'd have something to build on. However, the only thing I can think of now, is tags, and these would again require a different table. Is this a textbook example for using a natural key?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T19:34:14.597", "Id": "1891", "Score": "0", "body": "As said, it's absolutley ok if you are fine with languages being an atomic and unique." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T14:40:02.420", "Id": "62282", "Score": "0", "body": "why would you do this? Explaining it (even a little bit) makes for a better review" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T16:17:16.343", "Id": "1058", "ParentId": "1041", "Score": "2" } }, { "body": "<p>You have really obscure table aliases, why? </p>\n\n<p>Don't alias your table names just to alias your table names, that isn't the purpose of aliases. </p>\n\n<p>If you have a lengthy table name or you are calling tables from several databases where you need to call the table like <code>database1name.dbo.tablename1</code> then that is when you should use a table alias, so that you don't have to type the whole table location in the query. </p>\n\n<p>Do not use just one character for the alias, that doesn't tell you what information the table holds, make the alias meaningful.</p>\n\n<p>All of the Left Joins look a little weird to me, but I am sure it is necessary.</p>\n\n<p>Personally I wouldn't use Views, I would probably use Functions or Stored Procedures. but then again I don't normally code in MySQL so I really don't know if that would be best for that Engine. </p>\n\n<p>Still, I would see if I could use functions or stored procedures. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-25T02:35:52.560", "Id": "36029", "ParentId": "1041", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-28T13:58:30.093", "Id": "1041", "Score": "3", "Tags": [ "mysql", "sql", "codeigniter" ], "Title": "Database design for an online learning application" }
1041
<p>This a very simple function to expand the sizes between the given values.</p> <p>For instance, if the input variable is "S-XL" then the function returns "S, M, L, XL".</p> <p>Basically I'm not happy with this function. I think it's too complex for its purpose. </p> <pre><code>function sizexpander($sizes) { $sizearray=Array("XS", "S", "M", "L", "XL", "XXL", "XXXL"); $size1=array_search(strstrb($sizes, "-"), $sizearray); $size2=array_search(substr(strstr($sizes, "-"),1), $sizearray); while ($size1 &lt;= $size2) { $prodsizes.= $sizearray[$size1].", "; $size1++; } return substr($prodsizes, 0, -2); } function strstrb($h,$n){ return array_shift(explode($n,$h,2)); } </code></pre>
[]
[ { "body": "<p>You can use the function <code>array_slice</code> to take the subarray which contains the sizes from <code>$size1</code> to <code>size2</code>. And then use <code>implode</code> to turn this subarray into a comma-separated string. This will simplify your algorithm.</p>\n\n<p>You can also just use <code>explode</code> instead of <code>substr</code> and <code>strstr</code> to split the range string into its parts.</p>\n\n<p>In addition I would recommend changing the variable names of <code>$size1</code> and <code>$size2</code>. To me the name <code>$size1</code> suggests that the variable contains the actual size while in fact it contains its index. Something like <code>index_of_size1</code> or <code>index_from</code> might be more appropriate.</p>\n\n<p>If I were to write this function, it'd look something like this:</p>\n\n<pre><code>function sizexpander($size_range) {\n $sizearray=Array(\"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\", \"XXXL\");\n list($size_from, $size_to) = explode(\"-\", $size_range);\n $index_from = array_search($size_from, $sizearray);\n $index_to = array_search($size_to, $sizearray);\n $subsizes = array_slice($sizearray, $index_from, $index_to-$index_from+1);\n return implode(\", \", $subsizes);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T14:16:31.653", "Id": "1044", "ParentId": "1043", "Score": "6" } }, { "body": "<p>My implementation would be pretty much the same as yours, but removing the <code>foreach</code> loop. It's not required as <code>array_slice</code> can do the job with less code.</p>\n\n<pre><code>function sizexpander($sizes)\n{\n //These should be in order!\n $range = array(\"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\", \"XXXL\");\n\n //Split them into 2 segments, min / max + convert to upper\n $keys = explode(\"-\",strtoupper($sizes));\n\n //Get the initial index of min\n $min = array_search($keys[0],$range);\n $max = array_search($keys[1],$range);\n\n //Slice the array and implode.\n return implode(\",\",array_slice($range,$min,($max - $min) + 1));\n}\n</code></pre>\n\n<p>The main problem you had was that you had created a second function using string searching to find your segments. This has been replaced by <code>explode</code> which, as long as there is only ever 1 delimiter, then this would suffice.</p>\n\n<p>Also, the <code>while</code> statement has been revoked, along with the string concatenation and been replaced with implode, which takes the found segments of the <code>sizearray</code> and implode them by a delimiter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T11:12:22.733", "Id": "1869", "Score": "0", "body": "`array_slice` takes a starting index and a length, not a starting index and an end index." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T11:30:06.030", "Id": "1871", "Score": "0", "body": "Yea my bad, sorry about the confusion in your question aswell." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-01T09:51:15.303", "Id": "1049", "ParentId": "1043", "Score": "2" } }, { "body": "<p>Option A:</p>\n\n<pre><code>function sizexpander($sizes) {\n $sizeArray = array(\"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\", \"XXXL\");\n list($minSize, $maxSize) = split('-', $sizes);\n\n $minIndex = array_search($minSize, $sizeArray);\n $maxIndex = array_search($maxSize, $sizeArray);\n return join(', ', array_slice($sizeArray, $minIndex, ++$maxIndex - $minIndex));\n}\n</code></pre>\n\n<p>You can do this with array_filter but it's not as efficient.</p>\n\n<p>If you're uncomfortable with array operations or find the code unclear (i.e. not self documenting) you can do this with a simple enough loop.</p>\n\n<pre><code>function sizexpander2($sizes) {\n $sizeArray = array(\"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\", \"XXXL\");\n list($minSize, $maxSize) = split('-', $sizes);\n $tmp = array();\n\n foreach($sizeArray as $size) {\n if($size == $minSize) {\n $tmp[] = $size;\n } else if(count($tmp)) {\n $tmp[] = $size;\n if($size == $maxSize) break;\n }\n }\n\n return join(', ', $tmp);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T10:35:28.370", "Id": "1050", "ParentId": "1043", "Score": "2" } } ]
{ "AcceptedAnswerId": "1044", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-02-28T14:05:07.063", "Id": "1043", "Score": "5", "Tags": [ "php", "array" ], "Title": "Expanding sizes between given values" }
1043
<p>Here's a class that converts Hibernate proxies to normal classes. This is useful with GWT for example, when sending objects loaded from database to the GWT client. Please review it.</p> <pre><code>package ru.minogin.core.server.hibernate; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.log4j.Logger; import org.hibernate.collection.PersistentBag; import org.hibernate.collection.PersistentList; import org.hibernate.collection.PersistentMap; import org.hibernate.collection.PersistentSet; import org.hibernate.collection.PersistentSortedSet; import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.LazyInitializer; import ru.minogin.core.client.bean.Bean; import ru.minogin.core.server.reflection.ReflectionUtils; /** * Thread-safety: this class in not thread-safe. * * @author Andrey Minogin * @version 1.0, 02/28/11 * */ public class Dehibernator { private static final Logger logger = Logger.getLogger(Dehibernator.class); private IdentityHashMap&lt;Object, Object&gt; processed; @SuppressWarnings("unchecked") public &lt;T&gt; T clean(T object) { processed = new IdentityHashMap&lt;Object, Object&gt;(); logger.debug("Cleaning: " + (object != null ? object.getClass() : null)); return (T) doClean(object); } @SuppressWarnings("unchecked") private Object doClean(Object dirty) { logger.debug("Do clean: " + (dirty != null ? dirty.getClass() : null)); if (dirty == null) return null; if (processed.containsKey(dirty)) { logger.debug("Object already cleaned, skipping."); return processed.get(dirty); } if (isPrimitive(dirty)) { logger.debug("Object is primitive, skipping."); return dirty; } if (dirty instanceof PersistentList) { logger.debug("Object is a PersistentList"); PersistentList dirtyList = (PersistentList) dirty; List&lt;Object&gt; cleanList = new ArrayList&lt;Object&gt;(); processed.put(dirtyList, cleanList); if (dirtyList.wasInitialized()) { for (Object value : dirtyList) { cleanList.add(doClean(value)); } } return cleanList; } if (dirty instanceof PersistentBag) { logger.debug("Object is a PersistentBag"); PersistentBag dirtyList = (PersistentBag) dirty; List&lt;Object&gt; cleanList = new ArrayList&lt;Object&gt;(); processed.put(dirtyList, cleanList); if (dirtyList.wasInitialized()) { for (Object value : dirtyList) { cleanList.add(doClean(value)); } } return cleanList; } if (dirty instanceof PersistentSortedSet) { logger.debug("Object is a PersistentSortedSet"); PersistentSortedSet dirtySet = (PersistentSortedSet) dirty; Set&lt;Object&gt; cleanSet = new TreeSet&lt;Object&gt;(); processed.put(dirtySet, cleanSet); if (dirtySet.wasInitialized()) { for (Object value : dirtySet) { cleanSet.add(doClean(value)); } } return cleanSet; } if (dirty instanceof PersistentSet) { logger.debug("Object is a PersistentSet"); PersistentSet dirtySet = (PersistentSet) dirty; Set&lt;Object&gt; cleanSet = new HashSet&lt;Object&gt;(); processed.put(dirtySet, cleanSet); if (dirtySet.wasInitialized()) { for (Object value : dirtySet) { cleanSet.add(doClean(value)); } } return cleanSet; } if (dirty instanceof PersistentMap) { logger.debug("Object is a PersistentMap"); PersistentMap dirtyMap = (PersistentMap) dirty; Map&lt;Object, Object&gt; cleanMap = new LinkedHashMap&lt;Object, Object&gt;(); processed.put(dirtyMap, cleanMap); if (dirtyMap.wasInitialized()) { for (Object key : dirtyMap.keySet()) { Object value = dirtyMap.get(key); cleanMap.put(doClean(key), doClean(value)); } } return cleanMap; } if (dirty instanceof List) { logger.debug("Object is a List"); List&lt;Object&gt; dirtyList = (List&lt;Object&gt;) dirty; List&lt;Object&gt; cleanList = new ArrayList&lt;Object&gt;(); processed.put(dirtyList, cleanList); for (Object value : dirtyList) { cleanList.add(doClean(value)); } return cleanList; } if (dirty instanceof LinkedHashMap) { logger.debug("Object is a LinkedHashMap"); Map&lt;Object, Object&gt; dirtyMap = (Map&lt;Object, Object&gt;) dirty; Map&lt;Object, Object&gt; cleanMap = new LinkedHashMap&lt;Object, Object&gt;(); processed.put(dirtyMap, cleanMap); for (Object key : dirtyMap.keySet()) { Object value = dirtyMap.get(key); cleanMap.put(doClean(key), doClean(value)); } return cleanMap; } if (dirty instanceof HashMap) { logger.debug("Object is a HashMap"); Map&lt;Object, Object&gt; dirtyMap = (Map&lt;Object, Object&gt;) dirty; Map&lt;Object, Object&gt; cleanMap = new HashMap&lt;Object, Object&gt;(); processed.put(dirtyMap, cleanMap); for (Object key : dirtyMap.keySet()) { Object value = dirtyMap.get(key); cleanMap.put(doClean(key), doClean(value)); } return cleanMap; } if (dirty instanceof LinkedHashSet&lt;?&gt;) { logger.debug("Object is a LinkedHashSet"); Set&lt;Object&gt; dirtySet = (LinkedHashSet&lt;Object&gt;) dirty; Set&lt;Object&gt; cleanSet = new LinkedHashSet&lt;Object&gt;(); processed.put(dirtySet, cleanSet); for (Object value : dirtySet) { cleanSet.add(doClean(value)); } return cleanSet; } if (dirty instanceof HashSet&lt;?&gt;) { logger.debug("Object is a HashSet"); Set&lt;Object&gt; dirtySet = (HashSet&lt;Object&gt;) dirty; Set&lt;Object&gt; cleanSet = new HashSet&lt;Object&gt;(); processed.put(dirtySet, cleanSet); for (Object value : dirtySet) { cleanSet.add(doClean(value)); } return cleanSet; } if (dirty instanceof TreeSet&lt;?&gt;) { logger.debug("Object is a TreeSet"); Set&lt;Object&gt; dirtySet = (TreeSet&lt;Object&gt;) dirty; Set&lt;Object&gt; cleanSet = new TreeSet&lt;Object&gt;(); processed.put(dirtySet, cleanSet); for (Object value : dirtySet) { cleanSet.add(doClean(value)); } return cleanSet; } if (dirty instanceof HibernateProxy) { logger.debug("Object is a HibernateProxy"); HibernateProxy proxy = (HibernateProxy) dirty; LazyInitializer lazyInitializer = proxy.getHibernateLazyInitializer(); if (lazyInitializer.isUninitialized()) { logger.debug("It is uninitialized, skipping"); processed.put(dirty, null); return null; } else { logger.debug("It is initialized, getting implementati"); dirty = lazyInitializer.getImplementation(); } } if (dirty instanceof Bean) { logger.debug("Object is a Bean"); Bean bean = (Bean) dirty; processed.put(bean, bean); for (String property : bean.getPropertyNames()) { bean.set(property, doClean(bean.get(property))); } return bean; } processed.put(dirty, dirty); for (String property : ReflectionUtils.getProperties(dirty)) { logger.debug("Processing property " + property); Object value = ReflectionUtils.get(dirty, property); ReflectionUtils.setIfPossible(dirty, property, doClean(value)); } return dirty; } private boolean isPrimitive(Object object) { if (object instanceof String) return true; if (object instanceof Date) return true; if (object instanceof Enum) return true; Class&lt;? extends Object&gt; xClass = object.getClass(); if (xClass.isPrimitive()) return true; return false; } } </code></pre>
[]
[ { "body": "<p><code>doClean()</code> is crying out for decomposition. Compare</p>\n\n<pre><code>if (dirty instanceof PersistentList) {\n logger.debug(\"Object is a PersistentList\");\n\n PersistentList dirtyList = (PersistentList) dirty;\n List&lt;Object&gt; cleanList = new ArrayList&lt;Object&gt;();\n processed.put(dirtyList, cleanList);\n if (dirtyList.wasInitialized()) {\n for (Object value : dirtyList) {\n cleanList.add(doClean(value));\n }\n }\n return cleanList;\n}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if (dirty instanceof List) {\n logger.debug(\"Object is a List\");\n\n List&lt;Object&gt; dirtyList = (List&lt;Object&gt;) dirty;\n List&lt;Object&gt; cleanList = new ArrayList&lt;Object&gt;();\n processed.put(dirtyList, cleanList);\n for (Object value : dirtyList) {\n cleanList.add(doClean(value));\n }\n return cleanList;\n}\n</code></pre>\n\n<p>The differences are</p>\n\n<ol>\n<li>The types in the debug messages.</li>\n<li>The types in the casts.</li>\n<li>The types of the clean replacements.</li>\n<li>The check for <code>PersistentList.wasInitialized()</code>.</li>\n</ol>\n\n<p>Similar patterns exist for maps, sets, sorted sets, etc. and can all be refactored into new methods, each handling a different collection interface.</p>\n\n<pre><code>if (dirty instanceof List) {\n return cleanList((List)dirty);\n}\n\n...\n\nprivate cleanList(List dirty) {\n logger.debug(\"Object is a List\");\n List clean = new ArrayList();\n processed.put(dirty, clean);\n if (shouldCopyValues(dirty)) {\n for (Object value : dirty) {\n clean.add(doClean(value));\n }\n }\n return clean;\n}\n\nprivate shouldCopyValues(Collection dirty) {\n return (!(dirty instanceof Persistent) || ((Persistent)dirty).wasInitialized());\n}\n</code></pre>\n\n<p>Note that there's no longer a need for a separate check in <code>doClean()</code> for <code>PersistentList</code>. One minor optimization here would be to calculate the size of the needed list ahead of time, setting it to zero if it's an uninitialized <code>PersistentList</code>.</p>\n\n<p>For the more complicated <code>Map</code> and <code>Set</code> types, you'll need a way to map from the dirty class to the appropriate clean class. I recommend putting this logic into <code>cleanSet()</code> and <code>cleanMap()</code> instead of <code>doClean()</code>. You could take the same approach as you did above, using a series of <code>instanceof</code> tests, or you could use a map.</p>\n\n<p>Actually, only the persistent varieties need to use a different class type, so you may as well just check for those three specifically and otherwise create a new instance of the dirty collection.</p>\n\n<p>Note: when copying values for <code>Map</code>s you can use <code>Map.entrySet()</code> to get the key/value pairs as <code>Map.Entry</code> objects instead of calling <code>Map.get()</code> on each key. It's a minor speed improvement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T22:02:50.903", "Id": "1047", "ParentId": "1045", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-02-28T16:33:15.073", "Id": "1045", "Score": "2", "Tags": [ "java", "converting", "hibernate", "proxy", "gwt" ], "Title": "Hibernate proxy converter for GWT" }
1045
<pre><code>namespace SharpDream.Api { public enum SourceType { Test, Xml } public class UserFinder { private IUserInformationSource _sourceType; private IParser _parserType; private string _source; public UserFinder(SourceType sourceType) { switch (sourceType) { case SourceType.Test: var testSource = new TestSource(); _sourceType = testSource; break; case SourceType.Xml: var xmlSource = new XmlSource(); var xmlParser = new XmlParser(); _sourceType = xmlSource; _parserType = xmlParser; break; default: break; } } /// &lt;summary&gt; /// Returns a User object loaded with information. /// &lt;/summary&gt; /// &lt;param name="forumUserId"&gt;The DIC forum users ID number.&lt;/param&gt; /// &lt;returns&gt;A User object.&lt;/returns&gt; public User GetUserById(int forumUserId) { _source = _sourceType.GetResponseSource(forumUserId); return _parserType.ParseUserFromSource(_source); } } } </code></pre> <p>What I'm aiming for:</p> <ul> <li><p>Separation of concerns. Which is working believe it or not! It's so refreshing to feel confident that your code won't break if you change something somewhere else. I finished this bit, and now I can work on the parsing area without having to put anything else in the mental buffer.</p></li> <li><p>Flexibility during usage. </p></li> </ul> <p>Here is an example of how my library will be used:</p> <pre><code>UserFinder userFinder = new UserFinder(SourceType.Xml); var foundUser = userFinder.GetUserById(1); </code></pre> <p>Compare this to the old version of the library:</p> <pre><code>//Let's create an XmlMemberFinder, since we'll use the XML api as our data source. XmlMemberFinder xmlMemberFinder = new XmlMemberFinder(); //MemberList is the class you'll use in your application to get anything you need //relating to members. MemberLister memberList = new MemberLister(xmlMemberFinder); //This is an example of fetching and listing a user. var member = memberList.FindMember(1); </code></pre> <p>I think I have made improvements, but there is always someone smarter out there. :) </p> <p>Thanks for your time!</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T21:55:04.473", "Id": "1997", "Score": "0", "body": "Read up a bit on the Open-Closed Principle and how it applies to enums/switches: http://numainnovations.com/mentis-vulgaris/jason/software-development/is-your-code-solid-ocp-and-fighting-the-cost-of-change/" } ]
[ { "body": "<p>This is looking pretty good to me. The main thing that stands out that I woudl change is that the UserFinder() method is somewhat large, and it isn't immediately understandable to me what each piece does. </p>\n\n<p>I would try to break that up into several smaller, descriptively named methods:</p>\n\n<pre>public UserFinder(SourceType sourceType) \n{ \n if (requestIsTest()) \n { \n createTestSource();\n }\n else\n {\n createXmlSource();\n }\n}</pre>\n\n<p>Your original is more compact but less readable in my book. In six months when you come back to it, will you be able to remember what it does, or will you have to spend 10 minutes parsing it out and figuring out what it does?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T15:52:33.280", "Id": "1873", "Score": "0", "body": "UserFinder() is the constructor for the UserFinder.cs class. It's purpose it to set the source type the end developer is using." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T15:42:37.800", "Id": "1054", "ParentId": "1053", "Score": "0" } }, { "body": "<p>Personally I'd make the <code>UserFinder</code> class source-independent.<br>\nThis could be either by seeing the Xml and Test sources as a mapper and the <code>UserFinder</code> as a model (some kind of <a href=\"http://martinfowler.com/eaaCatalog/dataMapper.html\" rel=\"nofollow\">DataMapper</a>):</p>\n\n<pre><code>public interface UserMapperInterface {}\npublic class XmlSource : UserMapperInterface { // ... }\npublic class TestSource : UserMapperInterface { // ... }\n\npublic class UserFinder {\n public UserFinder(UserMapperInterface $source) { // ... }\n public UserFinder() { // use default source }\n}\n</code></pre>\n\n<p>This way you make the <code>GetUserById</code> method source-independent. Basic usage would be:</p>\n\n<pre><code>UserFinder t = new UserFinder(new TestSource());\n// UserFinder t = new UserFinder(); // using the default source\nt.GetUserById(43);\n</code></pre>\n\n<p>This way you seperate the source logic from the operations and you can easily add new sources without touching the <code>UserFinder</code> class. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T16:13:30.267", "Id": "1874", "Score": "0", "body": "Can you explain a bit why this is different to what I'm doing? In my code I also set the type of course to be used in the constructor. The UserFinder class acts on an interface, not a concrete implementation. Thanks! :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T16:19:40.540", "Id": "1875", "Score": "2", "body": "@sergio : you don't have to change the `UserFinder` class when you add new sources. The class doesn't (need to) know which source it does use thus you programm to an interface, not to an implementation." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T17:23:53.133", "Id": "1879", "Score": "1", "body": "The brother is taking you down a whole new path here! Look up Inversion of Control. (Come back in about 6 months and let us know if you are ok..) :-)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T16:00:39.290", "Id": "1055", "ParentId": "1053", "Score": "8" } }, { "body": "<p>Fge's answer (along with Mongus Pong's comment) really notes the major issue with your design. In general, you will want to avoid:</p>\n\n<ol>\n<li>Using enumerations in the place of polymorphism.</li>\n<li>Leaking the details of how you test a type into the type itself. You are doing this by explicitly referencing <code>TestSource</code> in <code>UserFinder</code>. Doing this complicates the core type with test code and/or test types that don't belong in it. Note that there are times when you'll have to break this \"rule\"; for example, when there is no other way to test the object in question, but generally you can avoid it. </li>\n</ol>\n\n<p>Fge's answer provides a great fix for both of these issues (though the <code>UserMapperInterface</code> interface should really be named <code>IUserMapper</code>, but that's just nitpicking).</p>\n\n<p>Once you get this pattern of IoC and Dependency Injection down you're on the cusp of something that can really transform how you write and test code: Mocking. A great introduction on the how and why of mocking can be found <a href=\"http://stephenwalther.com/blog/archive/2008/03/23/tdd-introduction-to-rhino-mocks.aspx\" rel=\"nofollow\">here</a>.</p>\n\n<p>Hope this helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T05:04:19.850", "Id": "1073", "ParentId": "1053", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T14:44:24.667", "Id": "1053", "Score": "2", "Tags": [ "c#", "api" ], "Title": "Majorly refactored my code, is this good enough?" }
1053
<p>How can I improve on this rather ugly method that builds an HTML unordered list from an XML file?</p> <p>I maintain a collection of ASP.NET webforms that all need to pull in the same site navigation as our main website. The forms have a master page that mimics the main site template, and we want any changes to the main navigation to flow through to the forms automatically. </p> <p>The main site uses an XML document to generate the navigation, and the document uses inconsistent formatting for the links (some have "http://mysite.com" hardcoded, and some are relative to the main site "/subsite"). </p> <p>Here's what I have right now: </p> <pre><code>private void LoadNavigation() { string urlPrefix = "http://mysite.com"; string xmlFilePath = ConfigurationManager.AppSettings["NavigationUrl"].ToString(); XmlDocument doc = new XmlDocument(); doc.Load(xmlFilePath); XmlNodeList navigationItems = doc.DocumentElement.FirstChild.ChildNodes; foreach (XmlNode item in navigationItems) { if (item.Attributes.GetNamedItem("url").Value.Contains("http://")) // link is hard coded { navList.InnerHtml += "&lt;li&gt; &lt;a href=" + '"' + item.Attributes.GetNamedItem("url").Value + '"' + "&gt;" + item.Attributes.GetNamedItem("title").Value + "&lt;/a&gt;|&lt;/li&gt;"; } else { navList.InnerHtml += "&lt;li&gt; &lt;a href=" + '"' + urlPrefix + item.Attributes.GetNamedItem("url").Value + '"' + "&gt;" + item.Attributes.GetNamedItem("title").Value; //relative link if (item.NextSibling == null) { navList.InnerHtml += "&lt;/a&gt;&lt;/li&gt;"; //last item in list } else { navList.InnerHtml += "&lt;/a&gt;|&lt;/li&gt;"; //not the last item in list } } } } </code></pre> <p>Believe it or not, this is an improvement over the original, which included a hardcoded URL for the XML file and got the values out of the XML document like this:</p> <pre><code>XmlNodeList nodeList = doc.ChildNodes[1].ChildNodes[0].ChildNodes; </code></pre> <p>But it still needs a lot of work. Please have at it.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T17:11:10.673", "Id": "1878", "Score": "0", "body": "Welcome to codereview. In the future please use the code button (the one with the 1s and 0s) to format your code or indent it by four spaces. The `<pre>` tag does not enable syntax highlighting (though `<code>` does, but don't use that either) and more importantly: It does not escape HTML special characters. So your code did not display correctly using `<pre>` tags. Thanks." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T17:26:46.207", "Id": "1880", "Score": "0", "body": "Thanks for fixing it! The code button doesn't work very well for me. When I click the code button and then paste in my code, it only picks up the first line, then makes a mess of the rest of it. What am I missing?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T17:40:09.723", "Id": "1882", "Score": "0", "body": "@Josh: First paste your code, then select it, then hit the code button." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T18:12:38.540", "Id": "1885", "Score": "0", "body": "Great. I'll try that next time." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T18:44:20.527", "Id": "1886", "Score": "0", "body": "What is `navList`? A class variable?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T19:15:14.920", "Id": "1890", "Score": "0", "body": "navList is a placeholder server control of some kind. Its sole function is to have this list attached to it." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T10:23:11.933", "Id": "1908", "Score": "0", "body": "Can you add an example that is being processed? xml input and expected output" } ]
[ { "body": "<p>The part that looks most problematic in your code is the <code>if</code> statement: the code in the <code>if</code> part and the <code>else</code> part is almost the same except that you prepend <code>urlPrefix</code> to the URL if it is relative. (Also you're only checking whether the node is the last if the URL is relative, which does not seem right). At the very least I'd factor this out into a helper method, which takes the absolute URL as a parameter to remove the code duplication.</p>\n\n<p>However there's an even better way: .net already comes with the <code>System.Uri</code> class, which can take care of making the URL absolute for you.</p>\n\n<pre><code>private void LoadNavigation()\n{\n Uri urlPrefix = new Uri(\"http://mysite.com\");\n string xmlFilePath = ConfigurationManager.AppSettings[\"NavigationUrl\"].ToString();\n XmlDocument doc = new XmlDocument();\n doc.Load(xmlFilePath);\n XmlNodeList navigationItems = doc.DocumentElement.FirstChild.ChildNodes;\n\n foreach (XmlNode item in navigationItems) \n {\n Url fullUrl = new Uri(urlPrefix, item.Attributes.GetNamedItem(\"url\").Value);\n String title = item.Attributes.GetNamedItem(\"title\").Value;\n navList.InnerHtml += \"&lt;li&gt; &lt;a href=\\\"\" + fullUrl + \"\\\"&gt;\" + title + \"&lt;/a&gt;\";\n\n if (item.NextSibling == null)\n {\n navList.InnerHtml += \"&lt;/a&gt;&lt;/li&gt;\"; //last item in list\n }\n else\n {\n navList.InnerHtml += \"&lt;/a&gt;|&lt;/li&gt;\"; //not the last item in list\n }\n } \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T20:55:32.800", "Id": "1899", "Score": "0", "body": "Good catch on the issue about only checking if the node is the last if the URL is relative. This code was originally written by looking at the existing XML file. Currently, the last node is relative, so why would we need to check the absolute nodes? :) That's why I'm reworking this..." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T21:00:15.090", "Id": "1900", "Score": "0", "body": "I like the suggestion to use the Uri class here, but wouldn't it lead to the hardcoded absolute URLs getting the protocol and domain appended to them twice: http://mysite.comhttp://mysite.com/restofurl" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T21:02:52.250", "Id": "1901", "Score": "0", "body": "@Josh: No, `new Uri(baseUri, uri)` only prepends `baseUri` to `uri` if `uri` is relative. If it is absolute, `baseUri` is ignored. So it's perfect if you have an URL which might be relative or absolute and you want to turn it into an absolute one." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T21:23:48.387", "Id": "1902", "Score": "0", "body": "That is pretty sweet. Definitely implementing this piece of your suggestion at least." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T17:38:42.253", "Id": "1061", "ParentId": "1056", "Score": "3" } }, { "body": "<p>I would look into using XSLT to transform the XML into the required HTML.</p>\n\n<p>So the code above becomes much simpler and would just have to load the XML file, load the XSL file, apply the transform and the result would be the HTML you require.<br/>\nAnother advantage is that if one day you decide to change the resulting HTML, this code will not need to change, only the XSL file will change.</p>\n\n<p>A quick search yields a lot of useful resources including an article that seems to explain what I was suggesting: <a href=\"http://www.xmlfiles.com/articles/sample_chapters/sams_xmlforaspnet/default.asp\" rel=\"nofollow\">Transforming XML with XSLT and ASP</a></p>\n\n<p>Another useful resource I'd recommend in case you are not familiar with XSLT is the <a href=\"http://www.w3schools.com/xsl/default.asp\" rel=\"nofollow\">XSLT Tutorial</a> at W3Schools.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T19:13:51.490", "Id": "1889", "Score": "0", "body": "This is an interesting suggestion. I've been wanting to dig into XSLT a bit anyway, so I might give it a shot. Would I be able to handle the absolute/relative URL issue in the XSL file?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T18:44:16.657", "Id": "1062", "ParentId": "1056", "Score": "3" } }, { "body": "<p>I'd build upon @sepp2k's modification by separating the concerns of 1) getting the link data, 2) building the links, 3) combining links into a bulleted list, and 4) adding the bullets to navList as follows:</p>\n\n<pre><code>private void LoadNavigation()\n{\n Uri urlPrefix = new Uri(\"http://mysite.com\");\n string xmlFilePath = ConfigurationManager.AppSettings[\"NavigationUrl\"].ToString();\n XmlDocument doc = new XmlDocument();\n doc.Load(xmlFilePath);\n XmlNodeList navigationItems = doc.DocumentElement.FirstChild.ChildNodes;\n\n var links = navigationItems\n .Cast&lt;XmlNode&gt;()\n .Select(x =&gt; new\n {\n FullUrl = new Uri(urlPrefix, x.Attributes.GetNamedItem(\"url\").Value) , \n Title = x.Attributes.GetNamedItem(\"title\").Value\n })\n .Select(x =&gt; String.Format(\"&lt;a href=\\\"{0}\\\"&gt;{1}&lt;/a&gt;\", x.FullUrl, x.Title))\n .ToArray();\n\n var bulletedLinks = \"&lt;li&gt;\" + String.Join(\"|&lt;/li&gt;&lt;li&gt;\", links) + \"&lt;/li&gt;\";\n navList.InnerHtml += bulletedLinks;\n}\n</code></pre>\n\n<p>Next I'd separate the concerns of 1) getting the xmlFilePath from the ConfigurationManager, and 2) loading the navigations items, from the process of updating navList. I'd also pass in the urlPrefix string or fetch it from an application configuration setting instead of hard coding it.</p>\n\n<pre><code>private string GetNavigationUrlXmlFilePath()\n{\n string xmlFilePath = ConfigurationManager.AppSettings[\"NavigationUrl\"].ToString();\n return xmlFilePath;\n}\n\nprivate IEnumerable&lt;XmlNode&gt; LoadNavigationItems()\n{\n var xmlFilePath = GetNavigationUrlXmlFilePath();\n XmlDocument doc = new XmlDocument();\n doc.Load(xmlFilePath);\n XmlNodeList navigationItems = doc.DocumentElement.FirstChild.ChildNodes;\n return navigationItems.Cast&lt;XmlNode&gt;();\n}\n\nprivate void LoadNavigation(Uri urlPrefix)\n{\n var links = LoadNavigationItems()\n .Select(x =&gt; new\n {\n FullUrl = new Uri(urlPrefix, x.Attributes.GetNamedItem(\"url\").Value) , \n Title = x.Attributes.GetNamedItem(\"title\").Value\n })\n .Select(x =&gt; String.Format(\"&lt;a href=\\\"{0}\\\"&gt;{1}&lt;/a&gt;\", x.FullUrl, x.Title))\n .ToArray();\n\n var bulletedLinks = \"&lt;li&gt;\" + String.Join(\"|&lt;/li&gt;&lt;li&gt;\", links) + \"&lt;/li&gt;\";\n navList.InnerHtml += bulletedLinks;\n}\n</code></pre>\n\n<p>I'd also pull \"NavigationUrl\" out to a single location so I wouldn't have to change a bunch of code when I want to change the key name.</p>\n\n<pre><code>public static class ApplicationConfigurationSettingsKeys\n{\n public static class MySite\n {\n public static readonly string NavigationUrl = \"NavigationUrl\";\n }\n}\n</code></pre>\n\n<p>Then I'd put GetNavigationUrlXmlFilePath and LoadNavigationItems behind interfaces so that they can be tested independently and LoadNavigation can be tested without having to go to the disk. </p>\n\n<pre><code>public interface IApplicationConfigurationSettingsProvider\n{\n string GetSetting(string key);\n}\n\npublic class ApplicationConfigurationSettingsProvider : IApplicationConfigurationSettingsProvider\n{\n public string GetSetting(string key)\n {\n return ConfigurationManager.AppSettings[key].ToString();\n }\n}\n\npublic interface INavigationLoader\n{\n IEnumerable&lt;XmlNode&gt; LoadNavigationItems();\n}\n\npublic class NavigationLoader : INavigationLoader\n{\n private readonly IApplicationConfigurationSettingsProvider _applicationConfigurationSettingsProvider;\n\n public NavigationLoader(IApplicationConfigurationSettingsProvider applicationConfigurationSettingsProvider)\n {\n _applicationConfigurationSettingsProvider = applicationConfigurationSettingsProvider;\n }\n\n public IEnumerable&lt;XmlNode&gt; LoadNavigationItems()\n {\n var xmlFilePath = _applicationConfigurationSettingsProvider\n .GetSetting(ApplicationConfigurationSettingsKeys.MySite.NavigationUrl);\n var doc = new XmlDocument();\n doc.Load(xmlFilePath);\n var navigationItems = doc.DocumentElement.FirstChild.ChildNodes;\n return navigationItems.Cast&lt;XmlNode&gt;();\n }\n}\n</code></pre>\n\n<p>leaving:</p>\n\n<pre><code>private readonly INavigationLoader _navigationLoader;\nprivate void LoadNavigation(Uri urlPrefix)\n{\n var links = _navigationLoader.LoadNavigationItems()\n .Select(x =&gt; new\n {\n FullUrl = new Uri(urlPrefix, x.Attributes.GetNamedItem(\"url\").Value) , \n Title = x.Attributes.GetNamedItem(\"title\").Value\n })\n .Select(x =&gt; String.Format(\"&lt;a href=\\\"{0}\\\"&gt;{1}&lt;/a&gt;\", x.FullUrl, x.Title))\n .ToArray();\n\n var bulletedLinks = \"&lt;li&gt;\" + String.Join(\"|&lt;/li&gt;&lt;li&gt;\", links) + \"&lt;/li&gt;\";\n navList.InnerHtml += bulletedLinks;\n}\n</code></pre>\n\n<p>Next I'd pull the conversion of XmlNode data to an HTML link out where it can be tested independently, possibly to an extension method:</p>\n\n<pre><code>public static class XmlNodeExtensions\n{\n public static string ToHtmlLink(this XmlNode node, Uri urlPrefix)\n {\n var fullUrl = new Uri(urlPrefix, node.Attributes.GetNamedItem(\"url\").Value);\n var title = node.Attributes.GetNamedItem(\"title\").Value;\n return String.Format(\"&lt;a href=\\\"{0}\\\"&gt;{1}&lt;/a&gt;\", fullUrl, title);\n }\n}\n</code></pre>\n\n<p>leaving:</p>\n\n<pre><code>private void LoadNavigation(Uri urlPrefix)\n{\n var links = _navigationLoader.LoadNavigationItems()\n .Select(x =&gt; x.ToHtmlLink(urlPrefix))\n .ToArray();\n\n var bulletedLinks = \"&lt;li&gt;\" + String.Join(\"|&lt;/li&gt;&lt;li&gt;\", links) + \"&lt;/li&gt;\";\n navList.InnerHtml += bulletedLinks;\n}\n</code></pre>\n\n<p>Finally, I'd pull out another method, possibly an extension, for building the bulleted list</p>\n\n<pre><code>public static class StringExtensions\n{\n public static string ToHtmlBullets(this IEnumerable&lt;string&gt; items, string suffix)\n {\n var bulleted = \"&lt;li&gt;\"+String.Join((suffix??\"\")+\"&lt;/li&gt;&lt;li&gt;\",items.ToArray())+\"&lt;/li&gt;\";\n return bulleted;\n }\n}\n</code></pre>\n\n<p>leaving only:</p>\n\n<pre><code>private void LoadNavigation(Uri urlPrefix)\n{\n var links = _navigationLoader.LoadNavigationItems()\n .Select(x =&gt; x.ToHtmlLink(urlPrefix))\n .ToHtmlBullets(\"|\");\n\n navList.InnerHtml += links;\n}\n</code></pre>\n\n<p>This method might now be more accurately named something like AddNavigationLinks. I'm also inclined to make this method side-effect free by passing navList into the method, I just don't happen to know what its type is.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T23:39:21.880", "Id": "1145", "ParentId": "1056", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T16:03:01.533", "Id": "1056", "Score": "5", "Tags": [ "c#", "asp.net" ], "Title": "Elegant approach to building unordered list from XML" }
1056
<p>Here's the code which I use for my Android custom cursor adapter which I use to bind data to my list view.</p> <pre><code>public class MessageAdapter extends CursorAdapter { private Cursor mCursor; private Context mContext; private final LayoutInflater mInflater; public MessageAdapter(Context context, Cursor c) { super(context, c); mInflater=LayoutInflater.from(context); mContext=context; } @Override public void bindView(View view, Context context, Cursor cursor) { TextView mobileNo=(TextView)view.findViewById(R.id.mobileNolistitem); mobileNo.setText(cursor.getString(cursor.getColumnIndex(TextMeDBAdapter.KEY_MOBILENO))); TextView frequency=(TextView)view.findViewById(R.id.frequencylistitem); frequency.setText(cursor.getString(cursor.getColumnIndex(TextMeDBAdapter.KEY_FREQUENCY))); TextView rowid=(TextView)view.findViewById(R.id.rowidlistitem); rowid.setText(cursor.getString(cursor.getColumnIndex(TextMeDBAdapter.KEY_ID))); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { final View view=mInflater.inflate(R.layout.message_list_item,parent,false); return view; } } </code></pre> <p>I know that there's another efficient way to do this which reuses the list item instantiated. Can someone tell me how?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T18:51:40.863", "Id": "1887", "Score": "0", "body": "I'm still getting started on Android apps. What list item are you refering to?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T19:50:45.120", "Id": "1892", "Score": "0", "body": "I'm referring to the list items in the list.See this video by Romain guy on making a good and efficient list view http://www.youtube.com/watch?v=N6YdwzAvwOA , although it's pretty long." } ]
[ { "body": "<p>This is exactly* the way you should be using your <code>CursorAdapter</code>. I'm sure you're referring to \"recycling\" the Views as talked about when overriding the <code>getView()</code> method of a <code>BaseAdapter</code>.</p>\n\n<p>In the case of the <code>CursorAdapter</code>, all of that is taken care of for you so that just implementing <code>newView()</code> and <code>bindView()</code> fully takes advantage of the View recycling you're asking about.</p>\n\n<p>Here is the code for <code>CursorAdapter.getView()</code>:</p>\n\n<pre><code>public View getView(int position, View convertView, ViewGroup parent) {\n if (!mDataValid) {\n throw new IllegalStateException(\"this should only be called when the cursor is valid\");\n }\n if (!mCursor.moveToPosition(position)) {\n throw new IllegalStateException(\"couldn't move cursor to position \" + position);\n }\n View v;\n if (convertView == null) {\n v = newView(mContext, mCursor, parent);\n } else {\n v = convertView;\n }\n bindView(v, mContext, mCursor);\n return v;\n}\n</code></pre>\n\n<p>So you see, the method attempts to recycle the View that was passed in by checking <code>convertView == null</code>. If successful, it uses that View and simply calls <code>bindView()</code> to set it up appropriately. If <code>convertView</code> is null, it calls <code>newView()</code> to create the View, followed by <code>bindView()</code> to set it up. This is one of the rare instances on SE that I can say \"You're doing it right!\"</p>\n\n<ul>\n<li>But to nitpick, there's really no reason to maintain a reference to your Context in <code>mContext</code> - You're not using it anywhere and maintaining references to Contexts can lead to memory leaks, and ultimately the end of the world.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-06T20:44:04.277", "Id": "11831", "Score": "1", "body": "One more thing You should definitely use - save pointers to all views with a ViewHolder, in order not to findViewById every time." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-02T21:45:16.770", "Id": "2201", "ParentId": "1057", "Score": "24" } }, { "body": "<p>It would be even easier to use a <code>SimpleCursorAdapter</code>, but the exact same principal applies for <code>CursorAdapter</code>. You can cache the calls to <code>findViewById()</code> on the view and even <code>getColumnIndex</code> on the cursor by storing the data in the views tag. Using this stopped by <code>ListView</code> rendering slowly.</p>\n\n<p>The <code>ViewHolder</code> pattern is borrowed from Efficient Adapter API demo <a href=\"http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html\" rel=\"nofollow\">here</a>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static class CustomSimpleCursorAdapter extends SimpleCursorAdapter {\n\n /* constructor(); */\n\n @Override\n public void bindView(View view, Context context, Cursor cursor) {\n super.bindView(view, context, cursor);\n\n ViewHolder holder = (ViewHolder) view.getTag();\n if (holder == null) {\n holder = new ViewHolder();\n holder.textView1 = (TextView) view.findViewById(R.id.text1);\n holder.textView2 = (TextView) view.findViewById(R.id.text2);\n holder.column1 = cursor.getColumnIndexOrThrow(\"column1\");\n holder.column2 = cursor.getColumnIndexOrThrow(\"column2\");\n view.setTag(holder);\n }\n\n holder.textView1.setText(cursor.getString(holder.column1));\n holder.textView2.setText(cursor.getString(holder.column2));\n }\n\n static class ViewHolder {\n TextView textView1;\n TextView textView2;\n int column1; \n int column2;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-31T12:31:28.073", "Id": "19525", "Score": "1", "body": "THe ViewHolder is the concept to go with, it costs a little bit of ram, but speeds up the binding of the view. @Tom Curran: Though I don't understand why you would get and keep the column index for every view, you should get it in the constructor and put in in two final fields!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-17T23:00:36.963", "Id": "4185", "ParentId": "1057", "Score": "8" } } ]
{ "AcceptedAnswerId": "2201", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-01T16:10:38.723", "Id": "1057", "Score": "34", "Tags": [ "java", "android" ], "Title": "Custom CursorAdapter Design" }
1057
<p>I'm working on a managed OpenGL game engine for C#, and here's how I'm managing shader parameters (uniforms). Is it "alright"? Could it be better? I'm a bit unsure about using generics in this case.</p> <pre><code>public abstract class ShaderParameter { public readonly string Name; internal readonly int Location; internal readonly Shader Parent; internal ShaderParameter(string name, int location, Shader parent) { Name = name; Location = location; Parent = parent; } //Ensures that the value is set on the shader, //this should be called before using the parent shader internal abstract void EnsureSet(); //Gives a value to this shader paramerter public abstract void SetValue&lt;T&gt;(T value); } //A shader paramater of type float public sealed class ShaderParamFloat : ShaderParameter { float value = 0; bool valueChanged = false; //If the value has changed since the last time it was set on the shader internal ShaderParamFloat(string name, int location, Shader parent) : base(name, location, parent) { } internal override void EnsureSet() { if (valueChanged) { //Hands over a single value to OpenGL. GL.Uniform1(Location, value); valueChanged = false; } } //Gives a value to this shader parameter public override void SetValue&lt;T&gt;(T value) { if (typeof(T) != typeof(float)) throw new ArgumentException("Value is of type: " + typeof(T).ToString() + ", expected: float", "value"); this.value = (float)(object)value; valueChanged = true; } } </code></pre> <p>The reason for using inheritance is because other <code>ShaderParameter</code> classes behave differently in <code>EnsureSet()</code>. For example, <code>ShaderParamVector3</code> uses <code>GL.Uniform3(...)</code>, and <code>ShaderParamTexture</code> needs to ensure that the texture is valid and set on the graphics card.</p>
[]
[ { "body": "<p>The biggest thing here is that you should make the ShaderParam class itself generic, not just its SetValue method. This will get rid of your type check and double cast (any time you have a type check or a double cast, chances are you're using the type system incorrectly). It will also get rid of the ShaderParamFloat class completely.</p>\n\n<p>For example:</p>\n\n<pre><code>public class ShaderParam&lt;T&gt;\n{\n private T value;\n\n ... (other code here)\n\n public void SetValue(T value)\n {\n this.value = value;\n ...\n }\n}\n</code></pre>\n\n<p>You can now use this for floats by instantiating a <code>ShaderParam&lt;float&gt;</code>, plus it works just as well for other types.</p>\n\n<p>Some other comments:</p>\n\n<ul>\n<li>Don't write comments that just duplicate the code. A variable named <code>valueChanged</code> doesn't need a comment saying \"If the value has changed\" - that much is obvious from the name. More importantly in this code, the method named <code>EnsureSet()</code> should have a comment explaining its purpose and why it should be called, not just a comment that expands the name into a longer sentence. I'm not an OpenGL user so I don't know what <code>GL.Uniform1()</code> does, but that code is surprising to me and a comment to explain why it's written that way would be useful.</li>\n<li>I take it you have good reasons for making some things public and others internal. To me, those choices seem pretty arbitrary. If it works in your situation, consider making the class itself internal and all members public.</li>\n<li>I don't personally like making fields public/internal, though given that they are readonly, I could live with it. I might personally still change this to use properties and a readonly backing field. That gives you the added benefit of being able to set breakpoints later if you ever need to debug.</li>\n<li>Not relevant if you make the first change above, but why is <code>ShaderParamFloat</code> still abstract?</li>\n<li>The private fields in <code>ShaderParamFloat</code> should be explicitly marked private.</li>\n<li>There is no need to initialize <code>value</code> to 0 or <code>valueChanged</code> to false. Those are their default values.</li>\n<li>I would personally call the class <code>ShaderParameter</code> instead of <code>ShaderParam</code>. Your abbreviation is pretty obvious in this case, but I tend to stay away from all but the most commonly used abbreviations. In particular, if using the abbreviation improves the readability of the code, then it makes sense. I don't think that applies here.</li>\n</ul>\n\n<p>EDIT:</p>\n\n<p>Based on your updated question, I would still recommend a solution like I mentioned above, where the base <code>ShaderParameter</code> is a generic class. However, it does make sense for you to derive classes from that with different implementations of <code>EnsureSet</code>. For example:</p>\n\n<pre><code>public abstract class ShaderParameter&lt;T&gt;\n{\n private T value;\n\n public abstract void EnsureSet();\n\n public void SetValue(T value)\n {\n this.value = value;\n }\n}\n\npublic class FloatShaderParameter : ShaderParameter&lt;float&gt;\n{\n public override void EnsureSet()\n {\n ...\n }\n}\n</code></pre>\n\n<p>And you can then derive similar classes for the other types of parameters. Note that you only need a single implementation of <code>SetValue</code> in the base, and it works for all derived classes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T07:36:12.310", "Id": "1905", "Score": "0", "body": "Thanks for such a thorough answer! :D I've taken most of these points into consideration. I should've mentioned that other classes who inherit ShaderParameter do completely different things inside EnsureSet, I've updated the question tp include this. Your answer made me realize that I might be able to do this in one class, using only function overloading." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T11:19:27.057", "Id": "1911", "Score": "0", "body": "@Hannesh, updated my answer based on your update. You'll still want to make the base class generic to avoid your type checks and casts." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T22:32:32.777", "Id": "1069", "ParentId": "1059", "Score": "5" } } ]
{ "AcceptedAnswerId": "1069", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-01T17:23:45.270", "Id": "1059", "Score": "3", "Tags": [ "c#", "opengl" ], "Title": "Shader parameters in managed OpenGL" }
1059
<p>I'm creating a game in C#, and I've created a <code>ScreenManager</code> so I can call</p> <pre><code>ScreenManager.MoveToScreen(typeof(ScreenClassHere)) </code></pre> <p>to move to other game states. However, I feel that my method of creating an instance of the class is... not very optimal. See for yourself.</p> <pre><code> public static void MoveToScreen(Type s) { if (currentscreen != null) currentscreen.Remove(); currentscreen = (Screen)s.GetConstructor(System.Type.EmptyTypes).Invoke(null); currentscreen.Init(); } </code></pre> <p>Does anyone know if there's a better way to create an instance of a certain class from a <code>Type</code>?</p>
[]
[ { "body": "<p>You could use generics</p>\n\n<pre><code>public static void MoveToScreen&lt;T&gt;() where T : Screen, new()\n{\n if (currentscreen != null) currentscreen.Remove();\n\n currentscreen = new T();\n currentscreen.Init();\n}\n</code></pre>\n\n<p>In this case, you'd have to call the method as</p>\n\n<pre><code>ScreenManager.MoveToScreen&lt;ScreenClassHere&gt;();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T20:05:07.283", "Id": "1893", "Score": "0", "body": "Let's get those proper casts in there. :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T20:06:52.517", "Id": "1894", "Score": "0", "body": "Although this seems like the better way to do it, I'm getting errors about the compiler not being able to convert T to Screen... `Error 1 Cannot convert type 'T' to 'SFMLGame.Screens.Screen'`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T20:07:55.430", "Id": "1895", "Score": "1", "body": "Since `currentscreen` seems to have the type `Screen` this should be `where T : Screen, new()`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T20:09:56.467", "Id": "1897", "Score": "0", "body": "@sepp2k - Exactly I was gonna suggest that over an awkward cast `currentscreen = (Screen)(object)new T();`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T19:58:47.140", "Id": "1067", "ParentId": "1066", "Score": "19" } }, { "body": "<p>Nitpicky, but I would change <code>if (currentscreen != null) currentscreen.Remove();</code> to</p>\n\n<pre><code>if (currentscreen != null) {\n currentscreen.Remove();\n}\n</code></pre>\n\n<p>I second pdr on using generics.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T05:02:44.000", "Id": "1904", "Score": "0", "body": "I don't like the unnecessary braces but I don't like it as a one-liner either, I would make it a two-liner with proper indentation. Just an opinion" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T14:20:53.140", "Id": "1919", "Score": "0", "body": "Nothing wrong with doing that either. I started always using braces because it's clearer to modify. Personal preference :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-01T20:04:23.033", "Id": "1068", "ParentId": "1066", "Score": "4" } }, { "body": "<p>I don't like the naming of a <code>Remove</code> method, it suggests that you remove something from the <code>currentScreen</code> but really it's the method that is called when the <code>currentScreen</code> itself is being removed, if I got it right.</p>\n\n<p>Also, other people suggesting generics are correct, you should use it. But if you once again find yourself in need of creating an instance knowing its type, don't go <code>GetConstructors</code> way. Use <code>Activator.CreateInstance</code> for that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T05:00:45.017", "Id": "1072", "ParentId": "1066", "Score": "5" } } ]
{ "AcceptedAnswerId": "1067", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-01T19:54:35.770", "Id": "1066", "Score": "7", "Tags": [ "c#" ], "Title": "Moving to other game states with ScreenManager" }
1066
<p>As far as I know the standard <a href="http://msdn.microsoft.com/en-us/library/system.delegate.createdelegate.aspx" rel="nofollow"><code>Delegate.CreateDelegate()</code></a> which allows to create a delegate by using reflection, doesn't allow doing something as follows when the first parameter of <code>method</code> isn't <strong>exactly</strong> of type <code>object</code>.</p> <pre><code>public class Bleh { public void SomeMethod( string s ) { } } ... object bleh = new Bleh(); MethodInfo method = bleh.GetType().GetMethod("SomeMethod"); // Starting from here, all knowledge about Bleh is unknown. // Only bleh and method are available. Action&lt;object&gt; a = (Action&lt;object&gt;)Delegate.CreateDelegate( typeof( Action&lt;object&gt; ), bleh, method ); </code></pre> <p>Which is why I now have an implementation which allows the following:</p> <pre><code>Action&lt;object&gt; compatibleExecute = DelegateHelper.CreateCompatibleDelegate&lt;Action&lt;object&gt;&gt;( bleh, method ); </code></pre> <p><code>method</code> can be any method, with or without return type, and with as many parameters as desired. I need to create an <code>Action&lt;T&gt;</code>, since other code is dependant on this strong typed delegate.</p> <p>In this example, I <strong>know</strong> the method is at least an <code>Action&lt;object&gt;</code>.</p> <p>The following code improves on the original <code>CreateDelegate</code> in two ways:</p> <ul> <li>It is generic now, instead of passing type as a first parameter.</li> <li>It does conversion to suitable lower types when possible.</li> </ul> <p>This is the first time for me working with expression trees, so I don't know whether what I'm doing is correct or the best approach. I based this implementation on <a href="http://msmvps.com/blogs/jon_skeet/archive/2008/08/09/making-reflection-fly-and-exploring-delegates.aspx" rel="nofollow">an article by Jon Skeet</a> (without fully understanding it :)), but the code seems to be working!</p> <pre><code>/// &lt;summary&gt; /// A generic helper class to do common /// &lt;see cref = "System.Delegate"&gt;Delegate&lt;/see&gt; operations. /// &lt;/summary&gt; /// &lt;author&gt;Steven Jeuris&lt;/author&gt; public static class DelegateHelper { /// &lt;summary&gt; /// The name of the Invoke method of a Delegate. /// &lt;/summary&gt; const string InvokeMethod = "Invoke"; /// &lt;summary&gt; /// Get method info for a specified delegate type. /// &lt;/summary&gt; /// &lt;param name = "delegateType"&gt;The delegate type to get info for.&lt;/param&gt; /// &lt;returns&gt;The method info for the given delegate type.&lt;/returns&gt; public static MethodInfo MethodInfoFromDelegateType( Type delegateType ) { Contract.Requires&lt;ArgumentException&gt;( delegateType.IsSubclassOf( typeof( MulticastDelegate ) ), "Given type should be a delegate." ); return delegateType.GetMethod( InvokeMethod ); } /// &lt;summary&gt; /// Creates a delegate of a specified type that represents the specified /// static or instance method, with the specified first argument. /// Conversions are done when possible. /// &lt;/summary&gt; /// &lt;typeparam name = "T"&gt;The type for the delegate.&lt;/typeparam&gt; /// &lt;param name = "firstArgument"&gt; /// The object to which the delegate is bound, /// or null to treat method as static /// &lt;/param&gt; /// &lt;param name = "method"&gt; /// The MethodInfo describing the static or /// instance method the delegate is to represent. /// &lt;/param&gt; public static T CreateCompatibleDelegate&lt;T&gt;( object firstArgument, MethodInfo method ) { MethodInfo delegateInfo = MethodInfoFromDelegateType( typeof( T ) ); ParameterInfo[] methodParameters = method.GetParameters(); ParameterInfo[] delegateParameters = delegateInfo.GetParameters(); // Convert the arguments from the delegate argument type // to the method argument type when necessary. ParameterExpression[] arguments = (from delegateParameter in delegateParameters select Expression.Parameter( delegateParameter.ParameterType )) .ToArray(); Expression[] convertedArguments = new Expression[methodParameters.Length]; for ( int i = 0; i &lt; methodParameters.Length; ++i ) { Type methodType = methodParameters[ i ].ParameterType; Type delegateType = delegateParameters[ i ].ParameterType; if ( methodType != delegateType ) { convertedArguments[ i ] = Expression.Convert( arguments[ i ], methodType ); } else { convertedArguments[ i ] = arguments[ i ]; } } // Create method call. ConstantExpression instance = firstArgument == null ? null : Expression.Constant( firstArgument ); MethodCallExpression methodCall = Expression.Call( instance, method, convertedArguments ); // Convert return type when necessary. Expression convertedMethodCall = delegateInfo.ReturnType == method.ReturnType ? (Expression)methodCall : Expression.Convert( methodCall, delegateInfo.ReturnType ); return Expression.Lambda&lt;T&gt;( convertedMethodCall, arguments ).Compile(); } } </code></pre> <p>So, did I do this the easiest/best way? Am I doing something completely unnecessary? Thanks!</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T09:00:26.190", "Id": "1963", "Score": "0", "body": "Why would you use such delegates? You're mentioning that it is generic but couldn't you simply use delegates constructor like so: `Action<object> execute = new Action(_owner.SomeMethod)`?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T14:48:26.550", "Id": "1971", "Score": "0", "body": "@Snowbear: This is reflection, `method` is a `MethodInfo`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T14:53:17.650", "Id": "1972", "Score": "0", "body": "Do you mean that entrance point to your code will be a reflection? So you won't know method you need at compile-time?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T15:01:59.413", "Id": "1973", "Score": "0", "body": "The `MethodInfo` is known, the instance (in this scenario) is known but the type of it unkown. By using applied attributes to a class I known which method is desired, and can retrieve the `MethodInfo`. That's the specific scenario, but in the general case, I **convert a MethodInfo into a delegate**. Read the intro of [Jon Skeet's article](http://msmvps.com/blogs/jon_skeet/archive/2008/08/09/making-reflection-fly-and-exploring-delegates.aspx) for more information. Thanks for the interest!" } ]
[ { "body": "<p>I feel like naming your first argument <code>firstArgument</code> will cause more confusion than it's worth. I would offer 2 overloads for this method.</p>\n\n<pre><code>// This overload will simply pass null to the main overload \n// for the sake of convenience.\npublic static T CreateCompatibleDelegate&lt;T&gt;(MethodInfo method)\n\n// I feel like the name 'instance' really makes it clear\n// what the parameter means.\npublic static T CreateCompatibleDelegate&lt;T&gt;(object instance, MethodInfo method)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T11:41:26.280", "Id": "2005", "Score": "0", "body": "You are actually really right about that. :O I just copy pasted it [from the info on CreateDelegate from msdn](http://msdn.microsoft.com/en-us/library/74x8f551.aspx) for consistency. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T22:12:40.773", "Id": "1141", "ParentId": "1070", "Score": "4" } }, { "body": "<p>I don't know if I'm missing something, but this doesn't look like it adds anything to doing </p>\n\n<pre><code> Expression&lt;Action&lt;T,TArg1,TArg2&gt;&gt; lambda = \n (instance,arg1,arg2) =&gt; instance.CallSomeMethod(arg1,arg2);\n var delegate = lambda.Compile();\n</code></pre>\n\n<p>If the only problem is getting the delegate to accept something without knowing the type then all you have to do is</p>\n\n<pre><code> Action&lt;object&gt; ConvertToUntyped&lt;T&gt;(Action&lt;T&gt; action){\n return o =&gt; action((T)o);\n }\n</code></pre>\n\n<p>If you need to get the <code>MethodInfo</code> for some other reason you can always get the <code>(MethodCallExpression)Expression&lt;TDelegate&gt;.Expression</code>. I don't know your use case, but from my similar experience it looks like you are trying to rebuild some functionality that is already there for you.</p>\n\n<p>I'd also like to add that, <em>as a general rule</em>, <strong>if you are setting out to optimize Jon Skeet's C# code, you are probably wasting your time</strong>. </p>\n\n<p><strong>EDIT</strong>\nUsing the non-generic lambda expression you have to write less code, and you could probably event cut this down. I wrote an example for you below. However, I'm still not sure I understand why you are trying to do this.</p>\n\n<pre><code> var instanceParameterExpression = Expression.Parameter(method.DeclaringType, \"Instance\");\n var argumentParameterExpressions = method.GetParameters().Select(x =&gt; Expression.Parameter(x.ParameterType, x.Name));\n var delegateParameters = new List&lt;ParameterExpression&gt;();\n delegateParameters.Add(instanceParameterExpression);\n delegateParameters.AddRange(argumentParameterExpressions);\n var lambda = Expression.Lambda(\n Expression.Call(instanceParameterExpression, method, argumentParameterExpressions.Cast&lt;Expression&gt;()),\n delegateParameters.ToArray()); \n</code></pre>\n\n<h2>UPDATE</h2>\n\n<p>the method below will make a delegate with all object parameters. I do see what you are getting at now, but I don't think it is a good idea at all. You have a minimal performance benefit over just using <code>Action&lt;object&gt; action = arg =&gt; bleh.GetType().GetMethod(\"SomeMethod\").Invoke(new[]{arg});</code>, and a huge amount of excess complexity. Furthermore, you are not even using the benefit of strong typing, and you will lose some of the performance benefit whenever you use this on methods with ValueType parameters, (boxing/unboxing). In theory, this could make something faster, but I think the real world scenarios you will find to apply it this way will be very rare, and won't be worth it. </p>\n\n<pre><code> public Delegate CreateDelegateWithObjectParameters(object instance, MethodInfo methodInfo)\n {\n var parameters = methodInfo.GetParameters()\n .Select(parameterInfo =&gt; new\n {\n MethodParameterType = parameterInfo.ParameterType,\n DelegateParameter = Expression.Parameter(typeof(object), parameterInfo.Name)\n })\n .Select(x =&gt; new\n {\n x.DelegateParameter,\n MethodParameter = Expression.Convert(x.DelegateParameter, x.MethodParameterType)\n });\n MethodCallExpression methodCallExpression = instance == null\n ? Expression.Call(methodInfo, parameters.Select(x =&gt; x.MethodParameter).ToArray())\n : Expression.Call(Expression.Constant(instance), methodInfo, parameters.Select(x =&gt; x.MethodParameter).ToArray());\n return Expression.Lambda(methodCallExpression, parameters.Select(x =&gt; x.DelegateParameter).ToArray()).Compile();\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T03:09:36.083", "Id": "2812", "Score": "0", "body": "_\"which allows to create a delegate by using reflection\"_ ... I only have `MethodInfo`. Thanks for the input though. ;p" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T03:12:35.337", "Id": "2814", "Score": "0", "body": "@Steven, do you have an instance of the object or just the `MethodInfo`? How did you get the `MethodInfo`? From where/why are you making this call?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T03:57:41.333", "Id": "2815", "Score": "0", "body": "The MethodInfo is known, the instance (in this scenario) is known but the type of it unkown. By using applied attributes to a class I known which method is desired, and can retrieve the MethodInfo. That's the specific scenario, but in the general case, I convert a MethodInfo into a delegate. Read the intro of Jon Skeet's article for more information. Thanks for the interest!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T04:01:22.033", "Id": "2816", "Score": "0", "body": "@Steven, (1) You can get the type from `MethodInfo.DeclaringType`, (2) Is the method a static method or an instance method? Because, if you want to get a delegate to a method on an instance, then you also need to construct the instance, (3) I've read the article several times and I just reviewed the intro - I'm still not clear on what you are trying to accomplish" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T04:11:29.643", "Id": "2818", "Score": "0", "body": "@smartcaveman: (1) K, I know the `Type` as in, I have the Type object, which is where I get the `MethodInfo` from in the first place. But I don't have the type at compile time so I can do `instance.CallSomeMethod(arg1,arg2);`. (2) It can be both, check the documentation on firstArgument. (3) Take a look at where the original [CreateDelegate](http://msdn.microsoft.com/en-us/library/74x8f551.aspx) is used. It does the exact same thing, but allows non-specific types. This code is somehow different than the article since I don't allow to pass an instance at runtime." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T04:18:51.947", "Id": "2819", "Score": "0", "body": "@Steven, Are you familiar with non-generic `Expression.Lambda()` factory method? I think that using that with a call to `Compile()` does what you are looking for. http://msdn.microsoft.com/en-us/library/dd268052.aspx" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T04:23:05.033", "Id": "2821", "Score": "0", "body": "In what way does that improve on my last line (the return statement of the function) which uses the generic Lambda() call?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T04:33:34.080", "Id": "2822", "Score": "0", "body": "It seems like it would save you a lot of unnecessary code, since you aren't able to take advantage of having/don't need a strongly typed delegate" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T04:58:26.133", "Id": "2824", "Score": "0", "body": "I need a strongly typed delegate. (`Action<object>` in this case) Furthermore, I don't see how constructing the body and parameters would be any different. The conversions are necessary because Expression.Call() would throw an `ArgumentException` otherwise." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T05:08:00.247", "Id": "2825", "Score": "0", "body": "As for the `.Cast<Expression>`, I'm not just converting the types to `Expression`, I construct expressions which convert the arguments from the delegate type to the method type (both not known at compile time)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T05:12:02.227", "Id": "2826", "Score": "0", "body": "If the method's parameter type is assignable from the type of the argument that you are passing it, but the type is not exactly the same, then there will be no exception. Look at the sample code I posted in the edit. It returns a type of `Delegate`, but you can cast it to the type of delegate that you would get from the method signature and it will compile. So if you used the `MethodInfo` from `Something.VoidMethod()` you would get `Delegate`, that you could make strongly typed by calling `(Action<Something>)yourDelegate)`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T05:13:41.180", "Id": "2827", "Score": "0", "body": "@Steven, I used `Cast<Expression>` because that is what the `Call` method requires. `ParameterExpression` is derived from `Expression`, so there really isn't much going on there. By method type, do you mean the object with the method or the return value?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T05:15:19.570", "Id": "2828", "Score": "0", "body": "@Steven, one of us is clearly misunderstanding something. Maybe when you've worked out a more concrete use case, then the advantage of what you are doing will be more obvious. I hope I've at least helped you to think about it in a different way - good luck" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T05:23:06.840", "Id": "2829", "Score": "0", "body": "@smartcaveman: I need `Action<object>`. Perhaps you understand the code better if you try to get the sample provided to work. `DelegateCommand<T>()` takes `Action<T>` as a first parameter. `_owner` is an `object` and `method` is `MethodInfo`. The type of the argument of the method isn't just `object`, but more specific." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T05:25:33.007", "Id": "2830", "Score": "0", "body": "@Steven, `Action<object> GetActionOfObject<T>(Action<T> actionOfT){ return x => actionOfT((T)x); }`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T05:30:05.247", "Id": "2831", "Score": "0", "body": "@smartcaveman: _\"By method type, do you mean the object with the method or the return value?\"_ I mean the type of the argument of the method. By delegate type I mean the type of the argument of the delegate." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T05:31:48.287", "Id": "2832", "Score": "0", "body": "@Steven, methods and delegates can both take multiple arguments with different types." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T05:34:10.860", "Id": "2833", "Score": "0", "body": "@smartcaveman: and where does `actionOfT` come from? That's the exact thing which is being constructed! I mean, try to get this code to work: `Action<object> compatibleExecute =\n DelegateHelper.CreateCompatibleDelegate<Action<object>>( _owner, method );\nDelegateCommand<object> command =\n new DelegateCommand<object>( compatibleExecute, canExecute );\n`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T05:37:36.483", "Id": "2834", "Score": "0", "body": "@Steven, It seems like I would need (1) the class definition for `DelegateCommand`, (2) the class definition for `_owner` with the (3) method signature for `method`, (4) a criteria for what it means for your code to \"work\"" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T05:51:34.657", "Id": "2835", "Score": "0", "body": "@smartcaveman: I gave those before. (1) `DelegateCommand<T>( Action<T> param )` (2, 3) _owner can be any object, let's say an instance from `class Bleh { public void SomeMethod(string s) { } }`, but do remember, you don't know this at compile time. (4) For it to work, making it compile is just fine, what it does is irrelevant." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T05:53:23.050", "Id": "2836", "Score": "0", "body": "@Steven, Where does the value for `s` in `SomeMethod` come from?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T05:57:25.403", "Id": "2837", "Score": "0", "body": "@smartcaveman: That's totally irrelevant, and unknown, it's a public method, it can come from anywhere. I believe I don't understand the question." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T06:02:29.573", "Id": "2838", "Score": "0", "body": "@Steven, How do you expect to get an `Action<object>`, when the object parameter has to be an instance of `Bleh`, and `SomeMethod` requires a string? You are trying to get a delegate which requires a single parameter for an action that has two parameters (the `Bleh` instance and the string `s`)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T06:03:13.217", "Id": "2839", "Score": "0", "body": "Oops, ofcourse it needs to be able to run as well, I mean, if it doesn't throw an exception at runtime, it's ok. ;p" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T06:06:08.957", "Id": "2840", "Score": "0", "body": "Who said the object parameter is an instance of `Bleh`, or two parameters? The returned delegate should execute the given method on the given instance." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T06:11:15.803", "Id": "2841", "Score": "0", "body": "@Steven, dude you did. \"_owner can be any object, let's say an instance from class Bleh\"" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T06:14:06.613", "Id": "2842", "Score": "0", "body": "@smartcaveman: I thought you were referring to the template parameter (`Action<object>`), which ofcourse didn't make any sense. `_owner` is an instance of `Bleh` yes. I'll update the question with a compileable example as an attempt to clarify things. ;p" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T06:24:16.297", "Id": "2843", "Score": "0", "body": "@smartcaveman: Give the updated example another look, I hope the intent is clear now. I'm hoping you'll have an 'aha-erlebnis' ;p" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T06:28:54.143", "Id": "2844", "Score": "1", "body": "@Steven, I don't have edit permissions on this site, but you clearly meant `bleh.GetType().GetMethod()`" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T06:49:56.427", "Id": "2845", "Score": "0", "body": "@Steven, now I get what you're trying to do - give me a couple min." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T13:24:24.807", "Id": "2866", "Score": "0", "body": "@smartcaveman: Regarding to your update, I actually never benchmarked this, but you are the one which said to not question Jon Skeet. ;p _\"using reflection takes over 600 times as long\"_, _\"the whole point of the exercise was to avoid invoking methods by reflection\"_. He talks of a considerable speed gain over `Invoke()`. I'll benchmark it at some point, and write a blog post about it if the results are worthwile, I'll include the edge cases you mentioned, thanks for pointing them out." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T13:49:23.523", "Id": "2867", "Score": "0", "body": "P.s.: And I just ran your code, it gives an exception on the `Compile()` line: \"variable .. of type ... referenced from scope '' but it is not defined. Furthermore your code allows less strong typing than mine. I still allow to use e.g. `Action<string>` in the given sample if I know it is at least that." } ], "meta_data": { "CommentCount": "32", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-03T02:17:28.497", "Id": "1629", "ParentId": "1070", "Score": "3" } }, { "body": "<p>By applying some extra <a href=\"http://msdn.microsoft.com/en-us/library/dd267698.aspx\" rel=\"nofollow\">LINQ 4.0 Zip</a> magic, I was able to reduce the code to the following. Anyone sees any more improvements? IMHO this is already a bit clearer.</p>\n\n<pre><code>public static T CreateCompatibleDelegate&lt;T&gt;( object instance, MethodInfo method )\n{\n MethodInfo delegateInfo = MethodInfoFromDelegateType( typeof( T ) );\n\n var methodTypes = method.GetParameters().Select( m =&gt; m.ParameterType );\n var delegateTypes = delegateInfo.GetParameters().Select( d =&gt; d.ParameterType );\n\n // Convert the arguments from the delegate argument type\n // to the method argument type when necessary.\n var arguments = methodTypes.Zip( delegateTypes, ( methodType, delegateType ) =&gt;\n {\n ParameterExpression delegateArgument = Expression.Parameter( delegateType );\n return new\n {\n DelegateArgument = delegateArgument,\n ConvertedArgument = methodType != delegateType\n ? (Expression)Expression.Convert( delegateArgument, methodType )\n : delegateArgument\n };\n } ).ToArray();\n\n // Create method call.;\n MethodCallExpression methodCall = Expression.Call(\n instance == null ? null : Expression.Constant( instance ),\n method,\n arguments.Select( a =&gt; a.ConvertedArgument )\n );\n\n // Convert return type when necessary.\n Expression convertedMethodCall = delegateInfo.ReturnType == method.ReturnType\n ? (Expression)methodCall\n : Expression.Convert( methodCall, delegateInfo.ReturnType );\n\n return Expression.Lambda&lt;T&gt;(\n convertedMethodCall,\n arguments.Select( a =&gt; a.DelegateArgument )\n ).Compile();\n}\n</code></pre>\n\n<p>At first I got the dreaded <em>\"variable .. of type ... referenced from scope '' but it is not defined.\"</em> exception, but after some pondering I realized I had to add <code>ToArray()</code> after the <code>Zip()</code> statement to make sure the delegate arguments would already be defined. Powerful stuff this <a href=\"http://marlongrech.wordpress.com/2007/12/22/linq-and-deferred-execution-of-queries/\" rel=\"nofollow\">deferred execution</a>, but apparently also a source for errors. I got the same exception when running smartcaveman's latest update, which is perhaps due to a similar mistake.</p>\n\n<hr>\n\n<p>Writing a custom Zip which takes three arguments removes the need of the anonymous type. Writing the Zip is really easy, <a href=\"http://msmvps.com/blogs/jon_skeet/archive/2011/01/14/reimplementing-linq-to-objects-part-35-zip.aspx\" rel=\"nofollow\">as documented by Jon Skeet</a>.</p>\n\n<pre><code>public static T CreateCompatibleDelegate&lt;T&gt;( object instance, MethodInfo method )\n{\n MethodInfo delegateInfo = MethodInfoFromDelegateType( typeof( T ) );\n\n var methodTypes = method.GetParameters().Select( m =&gt; m.ParameterType );\n var delegateTypes = delegateInfo.GetParameters().Select( d =&gt; d.ParameterType );\n var delegateArguments = delegateTypes.Select( Expression.Parameter ).ToArray();\n\n // Convert the arguments from the delegate argument type\n // to the method argument type when necessary.\n var convertedArguments = methodTypes.Zip(\n delegateTypes, delegateArguments,\n ( methodType, delegateType, delegateArgument ) =&gt;\n methodType != delegateType\n ? (Expression)Expression.Convert( delegateArgument, methodType )\n : delegateArgument );\n\n // Create method call.\n MethodCallExpression methodCall = Expression.Call(\n instance == null ? null : Expression.Constant( instance ),\n method,\n convertedArguments\n );\n\n // Convert return type when necessary.\n Expression convertedMethodCall = delegateInfo.ReturnType == method.ReturnType\n ? (Expression)methodCall\n : Expression.Convert( methodCall, delegateInfo.ReturnType );\n\n return Expression.Lambda&lt;T&gt;(\n convertedMethodCall,\n delegateArguments\n ).Compile();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T14:40:51.117", "Id": "416850", "Score": "0", "body": "If I understood this correctly, I would need to know in advance, the signature of the delegate (that matches the target method(s) signature). What if I don't know it before hand? In my use case, I am reading a file with \"method calls\" in each line. For example, DoThis(1,2); DoThat(3,4,\"test\"). I am able to execute them now using Method.Invoke, in fact caching then into a dictionary <String,Action> where the method invoke call, is wrapped further by an Action (e.g. Action act = ()=> methodInfo.Invoke({1,2}). I'm wondering if I could expand this delegate idea further for my use-case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T15:27:59.587", "Id": "416862", "Score": "0", "body": "I wrote more info on this use case here: [\"Creating delegates during reflection for unknown types\"](https://whatheco.de/2011/05/25/creating-delegates-during-reflection-for-unknown-types/), [\"Creating delegates during reflection with unbound instances\"](https://whatheco.de/2011/05/30/creating-delegates-during-reflection-with-unbound-instances/), and [\"Casting to less generic types\"](https://whatheco.de/2011/07/02/casting-to-less-generic-types/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T15:36:18.887", "Id": "416866", "Score": "0", "body": "However, I doubt what I describe here (and in the blog posts) is relevant to you. If all you are interested in is calling the methods and their full type definition is known (no casting is needed), then you can just use `Delegate.CreateDelegate` I start the post with. The result of that function would be the `Delegate` you store in your dictionary. The example you state does not make clear why the method signature would be unknown; you have the `MethodInfo`, no?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T18:25:20.143", "Id": "416903", "Score": "0", "body": "Yes, after reflection, the method signature is known, and in fact, I am able to generate a delegate of Action<T1,T2,...Tn> type matching the method signature, by calling Expression.GetActionType(types.ToArray()), where types is from methodInfo.GetParameters() . In theory, this would be the type I would use in your method above (CreateCompatibleDelegate). Where I'm lost next, is that how I then \"feed\" my string method call into this delegate, so I can cache that specific method call (cache this: Action act = () => newlycreatedDelegate(\"DoThis(1,2)\"))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T18:47:48.420", "Id": "416912", "Score": "0", "body": "Another way (or my other problem), is that when I make the call to the generic method CreateCompatibleDelegate<T>( object instance, MethodInfo method ), when I don't know T until runtime. I am able to programmatically obtain it, but I can't dynamically supply it to this method. T must be known at compile time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T21:31:42.463", "Id": "416954", "Score": "0", "body": "Why are you trying to cache the method including specific values for the parameters? I thought you were trying to cache the method (by name, for now presuming you do not support method overloading). As far as I understand what you are trying to do you do not need what I did in this post here. You should parse the parameters according to what is expected for the method name, and pass that to your cached delegate; the one you are already able to generate. You do not need method above, which I created for when \"other code is dependant on this strong typed delegate\" but exact type is not known." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-15T21:38:52.163", "Id": "416957", "Score": "0", "body": "Put differently: all this code does is generate a method which does the appropriate type conversions, assuming these are possible, thereby resulting in a delegate with different type signatures." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-04T20:50:26.967", "Id": "1646", "ParentId": "1070", "Score": "1" } } ]
{ "AcceptedAnswerId": "1646", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-02T02:55:01.627", "Id": "1070", "Score": "9", "Tags": [ "c#", "expression-trees" ], "Title": "Generic advanced Delegate.CreateDelegate using expression trees" }
1070
<p>I've just given this as a response to an absolute beginner on SO, and I'm wondering how terrible it is.</p> <p>Output for an odd number of lines:</p> <pre><code>&gt; &gt;&gt;&gt; &gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt; &gt; </code></pre> <p>Output for an even number of lines:</p> <pre><code>&gt; &gt;&gt;&gt; &gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt;&gt;&gt; &gt;&gt;&gt; &gt; </code></pre> <p>The code:</p> <pre><code>int lines = 7; int half = lines/2; String carat = "&gt;"; int i; //better to declare first or does it not matter? if(lines%2==0){boolean even = true;} else{boolean even = false;} for(i=1;i&lt;=lines;i++){ System.out.println(carat + "\n"); if(i==half &amp;&amp; even){System.out.println(carat+"\n");} if(((i&gt;=half &amp;&amp; even) || (i&gt;=half+1)) &amp;&amp; i!=lines){ carat = carat.substring(0,carat.length()-2); }else{ carat = carat + "&gt;&gt;"; } } </code></pre> <p>This code just seems so ugly, not considering the fact that there is no method that takes number of lines and that it is abusing integer rounding. </p>
[]
[ { "body": "<blockquote>\n <p>better to declare first or does it not matter?</p>\n</blockquote>\n\n<p>No. These days most people believe variables should be declared as late as possible, right by where they are used.</p>\n\n<blockquote>\n <p>This code just seems so ugly.</p>\n</blockquote>\n\n<p>It is. A little whitespace in there would help a lot. Which is easier to read:</p>\n\n<pre><code>// This:\nif(i==half &amp;&amp; even){System.out.println(carat+\"\\n\");}\n\n// Or this:\nif (i == half &amp;&amp; even) {\n System.out.println(carat+\"\\n\");\n}\n</code></pre>\n\n<blockquote>\n <p>that it is abusing integer rounding. </p>\n</blockquote>\n\n<p>There's no abuse, and it's not rounding. Truncation on integer arithmetic is a specified part of the language. Feel free to use it. In this case, it does exactly what you want.</p>\n\n<p>If I were writing this, I'd do:</p>\n\n<pre><code>printCarats(int numLines) { \n for (int line = 0; line &lt; numLines; line++) {\n // Mirror vertically across center line.\n int halfLine = line;\n if (line &gt; numLines / 2) halfLine = numLines - line - 1;\n\n int numCarats = 1 + halfLine * 2;\n for (int i = 0; i &lt; numCarats; i++) {\n System.out.print(\"&gt;\");\n }\n System.out.println();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T02:48:12.053", "Id": "1956", "Score": "9", "body": "I would rephrase \"should be declared as late as possible\" rather as \"should be declared in as narrow a scope as possible\". Perhaps the meaning is the same to most people, but to me, the talking about scope is clearer. For example, the benefit of declaring `int i` in the `for` loop statement is that its scope is limited to the loop statement and block." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T07:03:15.253", "Id": "1075", "ParentId": "1071", "Score": "16" } }, { "body": "<pre><code> if(lines%2==0){boolean even = true;} \n else{boolean even = false;} \n</code></pre>\n\n<p>Does this work for you? First, it looks like this makes the <em>even</em> variable only have scope in the decision block. You shouldn't be able to reference this further down in the code if you are declaring it in the braces.</p>\n\n<p>Also, you can probably get rid of the if/else by just using the logic test to define the <em>even</em> variable:</p>\n\n<pre><code>boolean even = (lines%2 == 0); //parens for clarity\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T12:56:34.607", "Id": "1085", "ParentId": "1071", "Score": "10" } }, { "body": "<p>Since there are not any requirements listed for this simple program, except some output that is lacking detail and since this was given to a beginner, I would start with a template like the one included and start the new programmer off with good practices like, code indentation, comments use of CONSTANTS etc.</p>\n\n<pre><code> /*\n * this program will print the &gt; greater than sign when the loop index is even\n * and the &lt; less than sign when the loop index is odd\n * the program will test up to the integer value 7\n * \n * programmer name\n * date\n */\n\n//begin class definition\npublic final class PrintStrings {\n\n //required main method\n public static void main(String[] args){\n String ODDCARAT = \"&lt;\"; // ODDCARAT constant\n String EVENCARAT = \"&gt;\";// EVENCARAT constant\n int i;\n //loop through 7\n for(i=1;i&lt;=7;i++){\n //test if integer is odd or even by % by 2 and checking for remainder\n if(i %2 == 0){\n System.out.println(EVENCARAT);\n }else{\n System.out.println(ODDCARAT);\n }//end if\n }//end for\n }//end main\n\n}//end class\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T18:00:26.460", "Id": "5362", "ParentId": "1071", "Score": "1" } }, { "body": "<p>Know your libraries, use your libraries...</p>\n\n<pre><code>int lines = 7;\n\nfor (int i = 0; i &lt; lines; i++) {\n int k = Math.min(i, lines-i-1);\n char[] line = new char[2*k+1];\n java.util.Arrays.fill(line, '&gt;');\n System.out.println(new String(line));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T21:41:21.747", "Id": "8105", "Score": "0", "body": "nice, except it's `java.util.Arrays`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-07T15:56:01.230", "Id": "23330", "Score": "0", "body": "I really like this. But it could be even better - you should initialize a String of length `(lines + 1) / 2` before the `for` loop and print it with `substring(...)` inside." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T19:03:32.363", "Id": "5369", "ParentId": "1071", "Score": "5" } } ]
{ "AcceptedAnswerId": "1075", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-02T04:43:32.600", "Id": "1071", "Score": "11", "Tags": [ "java", "strings" ], "Title": "Different character outputs using loops and strings" }
1071
<p>I have 3 simple similar event handler functions that I would like to refactor. Any suggestions?</p> <pre><code>private void btnBuildingList_Click(object sender, EventArgs e) { selectedExportType = (int)ExportType.Building; path = csvFilePath + String.Format("{0:yyyy-MM-dd}", datDate.DateTime) + "-BuildingList.csv"; Export(); } private void btnOwnerList_Click(object sender, EventArgs e) { selectedExportType = (int)ExportType.Persons; path = csvFilePath + String.Format("{0:yyyy-MM-dd}", datDate.DateTime) + "-OwnerList.csv"; Export(); } private void btnFacts_Click(object sender, EventArgs e) { selectedExportType = (int)ExportType.Facts; path = csvFilePath + String.Format("{0:yyyy-MM-dd}", datDate.DateTime) + "-FactsData.csv"; Export(); } </code></pre>
[]
[ { "body": "<ol>\n<li><p>You can use an <em>Extract Method</em> refactoring to get rid of the duplicate code:</p>\n\n<pre><code>private static string GetExportFilePath(string csvFilePath, DateTime date, string fileSuffix)\n{\n return string.Format(\"{0}{1:yyyy-MM-dd}-{2}.csv\", csvFilePath, date, fileSuffix);\n}\n</code></pre></li>\n<li><p>I would add those <code>selectedExportType</code> and <code>path</code> variables as parameters to the <code>Export()</code> method. I hope they are not used anywhere. It is usually pretty subjective whether to add something as method parameters or leave it as class member, but here I would definitely pass them as parameters. I assume this class is a “View” since you have button click event handlers, and I also tend to move such methods out from the views.</p></li>\n</ol>\n\n<p>If we use these two ideas, your event handlers would be simplified to:</p>\n\n<pre><code>private void btnBuildingList_Click(object sender, EventArgs e)\n{\n var path = GetExportFilePath(csvFilePath, datDate.DateTime, \"BuildingList.csv\");\n Export((int)ExportType.Building, path);\n}\n\nprivate void btnOwnerList_Click(object sender, EventArgs e)\n{\n var path = GetExportFilePath(csvFilePath, datDate.DateTime, \"OwnerList.csv\");\n Export((int)ExportType.Persons, path);\n}\n\nprivate void btnFacts_Click(object sender, EventArgs e)\n{\n var path = GetExportFilePath(csvFilePath, datDate.DateTime, \"FactsData.csv\");\n Export((int)ExportType.Facts, path);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-02T09:44:47.063", "Id": "1078", "ParentId": "1076", "Score": "15" } }, { "body": "<p>In addition to what @Snowbear suggests. I thought you should know that all button's click event can be pointed to the same event handler. You can then distinguish each one using the sender parameter.</p>\n\n<p>I prefer @Snowbear's recommendation but I mention this because many people don't seem to know this can be done.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T10:06:12.983", "Id": "1079", "ParentId": "1076", "Score": "8" } }, { "body": "<p>I would push the path formatting code down into the \"Export\" function. Creating a path formatting function merely adds noise to the program. I would modify the \"Export\" function to take one parameter of type ExportType. This parameter can be used to determine the type of export as well as the file prefix string by putting the file prefixes in a string array in which the strings are ordered the same as the class constants or enumeration.</p>\n\n<p>Note: this example assumes that BuildingList resolves to 0, OwnerList resolves to 1, and FactsData resolves to 2.</p>\n\n<pre><code>private void Export( ExportType typeOfExport )\n{\n\n string[] exportPrefixes = { \"BuildingList\", \"OwnerList\", \"FactsData\" };\n\n string path = csvFilePath + String.Format(\"{0:yyyy-MM-dd}\", datDate.DateTime) + \"-\" + exportPrefixes[(int)typeOfExport] + \".csv\";\n\n ...\n\n}\n</code></pre>\n\n<p>As Shiv Kumar mentioned, one can create a single event and use the parameter \"sender\" to determine the caller. In this case, we would have something like:</p>\n\n<pre><code> private void unified_Click(object sender, EventArgs e)\n {\n if (sender is btnBuildingList)\n Export(ExportType.Building);\n else if (sender is btnOwnderList)\n Export(ExportType.Owner);\n else if (sender is btnFacts)\n Export(ExportType.Facts);\n }\n</code></pre>\n\n<p>Whether or not, you feel that a unified approach is cleaner is up to you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T15:17:33.177", "Id": "1094", "ParentId": "1076", "Score": "3" } } ]
{ "AcceptedAnswerId": "1078", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-02T09:03:55.197", "Id": "1076", "Score": "5", "Tags": [ "c#", "event-handling" ], "Title": "Similar event handlers for buttons" }
1076
<p>A fully functional demo URL: <code>http://69.24.73.172/demos/index.html</code></p> <p>Note that in FireFox there is a small horizontal scrollbar bug which I have fixed at home.</p> <p><strong>HTML:</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8" /&gt; &lt;title&gt;Welcome to Scirra.com&lt;/title&gt; &lt;meta name="description" content="Construct 2, the HTML5 games creator." /&gt; &lt;link rel="stylesheet" href="css/default.css" type="text/css" /&gt; &lt;link rel="stylesheet" href="plugins/coin-slider/coin-slider-styles.css" type="text/css" /&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/common.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="plugins/coin-slider/coin-slider.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/homepage.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="topBar"&gt;&lt;/div&gt; &lt;div class="mainBox"&gt; &lt;div class="headWrapper"&gt; &lt;div class="searchWrapper"&gt; &lt;div class="searchBox"&gt; &lt;input type="text" id="SearchBox" /&gt; &lt;div class="s searchIco"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="topMenu"&gt; &lt;a href="#" class="topSelWrapper"&gt;Home&lt;/a&gt; &lt;a href="#" class="topNormal"&gt;Forum&lt;/a&gt; &lt;a href="#" class="topNormal"&gt;Contruct&lt;/a&gt; &lt;a href="#" class="topNormal"&gt;Arcade&lt;/a&gt; &lt;a href="#" class="topNormal"&gt;Manual&lt;/a&gt; &lt;a href="#" class="topNormal"&gt;Support&lt;/a&gt; &lt;a href="#" class="topNormal"&gt;Contact&lt;/a&gt; &lt;/div&gt; &lt;div class="subMenu"&gt; &lt;a href="#" class="subSelWrapper"&gt;Homepage&lt;/a&gt; &lt;a href="#" class="subNormal"&gt;Construct&lt;/a&gt; &lt;a href="#" class="subNormal"&gt;Products&lt;/a&gt; &lt;a href="#" class="subNormal"&gt;Community Forum&lt;/a&gt; &lt;a href="#" class="subNormal"&gt;Contact Us&lt;/a&gt; &lt;/div&gt; &lt;div class="contentWrapper"&gt; &lt;div class="wideCol"&gt; &lt;div id='coin-slider' class="slideShowWrapper"&gt; &lt;a href="#" target="_blank"&gt; &lt;img src='images/screenshot1.jpg' &gt; &lt;span&gt; Scirra software allows you to bring your imagination to life &lt;/span&gt; &lt;/a&gt; &lt;a href="#"&gt; &lt;img src='images/screenshot2.jpg' &gt; &lt;span&gt; Export your creations to HTML5 pages &lt;/span&gt; &lt;/a&gt; &lt;a href="#"&gt; &lt;img src='images/screenshot3.jpg' &gt; &lt;span&gt; Another description of some image &lt;/span&gt; &lt;/a&gt; &lt;a href="#"&gt; &lt;img src='images/screenshot4.jpg' &gt; &lt;span&gt; Something motivational to tell people &lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="newsWrapper"&gt; &lt;h1&gt;Latest from Twitter&lt;/h1&gt; &lt;div id="twitterFeed"&gt; &lt;p&gt;The news on the block is this. Something has happened some news or something. &lt;span class="smallDate"&gt;About 6 hours ago&lt;/span&gt;&lt;/p&gt; &lt;p&gt;Another thing has happened lets tell the world some news or something. Lots to think about. Lots to do.&lt;span class="smallDate"&gt;About 6 hours ago&lt;/span&gt;&lt;/p&gt; &lt;p&gt;Shocker! Santa Claus is not real. This is breaking news, we must spread it. &lt;span class="smallDate"&gt;About 6 hours ago&lt;/span&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="thinCol"&gt; &lt;h1&gt;Main Heading&lt;/h1&gt; &lt;p&gt;Some paragraph goes here. It tells you about the picture. Cool! Have you thought about downloading Construct 2? Well you can download it with the link below. This column will expand vertically.&lt;/p&gt; &lt;h2&gt;Help Me!&lt;/h2&gt; &lt;p&gt;This column will keep expanging and expanging. It pads stuff out to make other things look good imo.&lt;/p&gt; &lt;h2&gt;Why Download?&lt;/h2&gt; &lt;p&gt;As well as other features, we also have some other features. Check out our &lt;a href="#"&gt;other features&lt;/a&gt;. Each of our other features is really cool and there to help everyone suceed.&lt;/p&gt; &lt;a href="#" class="s downloadBox"&gt; &lt;div class="downloadHead"&gt;Download&lt;/div&gt; &lt;div class="downloadSize"&gt;24.5 MB&lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;h1&gt;This Weeks Spotlight&lt;/h1&gt; &lt;div class="halfColWrapper"&gt; &lt;img src="images/spotlight1.png" class="spotLightImg" /&gt; &lt;p&gt;Our spotlight member this week is Pooh-Bah. He writes good stuff. Read it.&lt;/p&gt; &lt;a class="moreInfoLink" href="#"&gt;Learn More&lt;/a&gt; &lt;/div&gt; &lt;div class="halfColSpacer"&gt;&amp;nbsp;&lt;/div&gt; &lt;div class="halfColWrapper"&gt; &lt;img src="images/spotlight2.png" class="spotLightImg" /&gt; &lt;p&gt;Killer Bears is a scary ass game from JimmyJones. How many bears can you escape from?&lt;/p&gt; &lt;a class="moreInfoLink" href="#"&gt;Learn More&lt;/a&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="footerWrapper"&gt; &lt;div class="footerBox"&gt; &lt;div class="footerItem"&gt; &lt;h3&gt;Community&lt;/h3&gt; &lt;a href="#"&gt;The Blog&lt;/a&gt;&lt;br /&gt; &lt;a href="#"&gt;Community Forum&lt;/a&gt;&lt;br /&gt; &lt;a href="#"&gt;RSS Feed&lt;/a&gt;&lt;br /&gt; &lt;a class="s footIco facebook" href="http://www.facebook.com/ScirraOfficial" target="_blank"&gt;&lt;/a&gt; &lt;a class="s footIco twitter" href="http://twitter.com/Scirra" target="_blank"&gt;&lt;/a&gt; &lt;a class="s footIco youtube" href="http://www.youtube.com/user/ScirraVideos" target="_blank"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="footerItem"&gt; &lt;h3&gt;About Us&lt;/h3&gt; &lt;a href="#"&gt;Contact Information&lt;/a&gt;&lt;br /&gt; &lt;a href="#"&gt;Advertising&lt;/a&gt;&lt;br /&gt; &lt;a href="#"&gt;History&lt;/a&gt;&lt;br /&gt; &lt;a href="#"&gt;Privacy Policy&lt;/a&gt;&lt;br /&gt; &lt;a href="#"&gt;Terms and Conditions&lt;/a&gt; &lt;/div&gt; &lt;div class="footerItem"&gt; &lt;h3&gt;Want to Help?&lt;/h3&gt; You can contribute to the community &lt;a href="#"&gt;in lots of ways&lt;/a&gt;. We have a large active friendly community, and there are lots of ways to join in!&lt;br /&gt; &lt;div class="ralign"&gt; &lt;a href="#"&gt;&lt;strong&gt;Learn More&lt;/strong&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="copyright"&gt; Copyright &amp;copy; 2011 Scirra.com. All rights reserved. &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>(Note head wrapper div is empty at the moment, this will have a logo at a later date).</p> <p><strong>CSS:</strong></p> <pre><code> /* Main Layout Elements */ body{ margin: 0; padding: 0; font-family: Arial, Helvetica, Verdana; background: #fff url(../images/background.png) repeat-x; color:#444; } p { margin: 0 0 20px 8px; } a{ color: #0066FF; } .smallDate{ float:right; color: #339900; } .topBar{ position:absolute; background-color: #339900; height: 30px; border-bottom:2px solid #3FBF00; width: 100%; z-index:1; -moz-box-shadow: 0px 0px 5px #555; -webkit-box-shadow: 0px 0px 5px #555; box-shadow: 0px 0px 5px #555; } h1{ margin:0; margin-bottom:5px; font-size:35px; color: #339900; font-weight:normal; } h2{ margin:0 0 5px 0; font-size:22px; color: #339900; font-weight:normal; } h3{ text-shadow: black 0.1em 0.1em 0.2em; text-transform: uppercase; font-size: 17px; font-weight: bold; margin-bottom: 3px; } .ralign{ text-align:right; } .clear{ clear:both; } /* Sprite definitions and positioning */ .s{ background-image:url(../images/sprites.png); background-repeat:no-repeat; } .facebook{ background-position: 0 0; } .twitter{ background-position: 0 -40px; } .slideShowWrapper{ height:261px; overflow:hidden; -moz-box-shadow: 0px 0px 5px #555; -webkit-box-shadow: 0px 0px 5px #555; box-shadow: 0px 0px 5px #555; } .youtube{ background-position: 0 -80px; } /* Main Wrappers */ .contentWrapper{ padding: 10px; } .headWrapper{ height: 120px; } .footerWrapper{ position:relative; z-index:1; top: -20px; height:155px; padding-top: 15px; background-image: url(../images/background-footer.png); background-repeat:repeat-x; margin-bottom: -20px; overflow: hidden; } .mainBox{ -moz-box-shadow: 0px 0px 12px #444; -webkit-box-shadow: 0px -20px 28px #c0c0c0; box-shadow: 0px 0px 12px #444; margin: 0 auto; width: 770px; border:0; z-index:2; position:relative; background-color: #ffffff; -moz-border-radius-bottomright: 10px; border-bottom-right-radius: 10px; -moz-border-radius-bottomleft: 10px; border-bottom-left-radius: 10px; } /* Footer */ .footerBox { color: white; font-size: 13px; margin: 0 auto; width: 700px; margin-top:5px; } .footerItem{ float: left; width: 33%; } .footerItem a{ font-size:13px; color:white; } .footerItem a:hover{ color: #ffaa00; } .copyright { color: white; text-align:center; background-color: #000000; font-size: 12px; padding: 3px; } .footIco{ height: 40px; width: 32px; float: left; margin-top: 7px; position:relative; left: -4px; display:block; } /* Search */ .searchWrapper{ float:right; background-color: #339900; width: 250px; height:53px; position:relative; left: 50px; -moz-border-radius-bottomright: 10px; border-bottom-right-radius: 10px; -moz-border-radius-bottomleft: 10px; border-bottom-left-radius: 10px; text-align:center; line-height:50px; } .searchBox{ position:Relative; left:12px; } .searchBox input{ height:20px; padding-left:10px; color: #c0c0c0; line-height:20px; padding-right:25px; } .searchIco{ height: 37px; width: 36px; float: right; background-position: -40px 0; position:relative; left:-33px; top:11px; } /* Menus */ .topMenu{ height:38px; background-color: #339900; font-size: 15px; font-weight: bold; line-height:38px; } .topMenu a{ text-shadow: #114400 1px 1px 1px; display: block; float:left; padding-left: 8px; padding-right: 8px; color:white; } .subMenu{ height: 33px; background-color: #1B5300; font-size: 13px; line-height:33px; } .subMenu a{ display: block; float:left; padding-left: 8px; padding-right: 8px; color:white; text-decoration: none; } .subLinkLImg{ float:left; width:11px; height:23px; background-position: -80px 0; } .subLinkSelected{ background-color:#123700; float:left; height:22px; line-height:22px; } .subSelWrapper{ text-decoration: none; margin-right: -20px; margin-left: 5px; } .subNormal{ margin-left: 25px; } .subNormal:hover{ background-color:#123700; text-decoration: none; } .ssOrient{ position:relative; top:6px; } .subLinkRImg{ float:right; width:11px; height:23px; background-repeat:no-repeat; background-position: -91px 0; } .topSelWrapper{ text-decoration: none; margin-right: -20px; margin-left: 5px; } .topLinkLImg{ float:left; width:11px; height:33px; background-position: -105px 0; } .topLinkRImg{ float:right; width:11px; height:33px; background-position: -116px 0; } .topLinkSelected{ background-color:#1B5300; float:left; height:33px; line-height:33px; } .tlOrient{ position:relative; top:5px; } .topNormal{ margin-left: 25px; text-decoration: none; } .topNormal:hover{ background-color:#2B8200; } /* Download box link */ .downloadBox{ display: block; background-position: -134px 0; width: 215px; height: 55px; margin: 0 auto; text-align:right; color:white; text-transform: uppercase; text-decoration: none; } .downloadHead{ font-weight:bold; font-size:17px; padding-top:14px; padding-right: 15px; } .downloadSize{ padding-right: 15px; font-size:14px; margin-top: -3px; } /* Other */ .moreInfoLink{ display:block; color:white; font-size:12px; font-weight:bold; text-decoration: none; float:right; height:17px; background-color:#3366CC; text-align:center; padding:0 12px 0 12px; line-height:17px; min-width:100px; -moz-border-radius: 10px; border-radius: 10px; margin-top:-12px; margin-bottom:10px; clear:both; } .moreInfoLink:hover{ text-decoration:underline; background-color: #537DD5; } .thinCol{ float:left; width:270px; } .wideCol{ float:left; margin-right:10px; width:470px; } .newsWrapper{ position:relative; top: 5px; } .halfColSpacer{ width:4%; float:left; } .halfColWrapper{ float:left; width:48%; } .spotLightImg{ float:left; margin-right:15px; -moz-border-radius: 10px; border-radius: 10px; -moz-box-shadow: 3px 3px 3px #444; -webkit-box-shadow: 3px 3px 3px #444; box-shadow: 3px 3px 3px #444; width: 90px; height: 90px; } .slideShowWrapper img{ width:470px; height: 261px; border: 0; } .slideShowWrapper a{ text-decoration: none; } </code></pre> <p>I've tried really hard to design this with progressive enhancement in mind, so I think it degrades quite nicely.</p> <p>IE7 and below aren't supported. I am completely fine with taking that decision. I'm considering adding some sort of notification though.</p> <p>It's tested in Safari, FF, IE8 and Chrome.</p> <p>I've used a sprite image to improve load speed. CSS isn't compressed/optimised yet, I'll do that later.</p> <p>Comments on CSS/HTML/JS are all welcome. I really want to nail this as being as near to perfect as possible. Main areas of importance are:</p> <ul> <li>SEO friendly</li> <li>Fast and responsive</li> <li>Accessible</li> </ul>
[]
[ { "body": "<p>I didn't have a look in detail, but some ideas/observations/remarks:</p>\n\n<ul>\n<li>You might save some <code>div</code> elements with using the <code>float</code> style (especially in your header). Try to avoid using <code>div</code>s for styling only and use the logical corresponding tags (for example in <code>&lt;div class=\"downloadHead\"&gt;Download&lt;/div&gt;</code>).</li>\n<li>Menus should be lists (<code>&lt;li&gt;</code>) from a logic point of view (e.g. <a href=\"http://www.webdesignerwall.com/tutorials/css-menu-list-design/\">like here</a>)</li>\n<li>Try to put all javascript includes at the end where possible (this has some disadvantages though, <a href=\"http://ncsuwebdev.ning.com/forum/topics/javascript-in-the-body-at-the\">(one of many discussions about that topic)</a>)</li>\n<li>As long as your code doesn't become more complicated it should render fast. I think your biggest problem will be the underlying application (assuming the site is not static). <a href=\"http://developer.yahoo.com/performance/rules.html\">Yahoo</a> has some great guidelines on how to speed up websites. </li>\n<li>Accssible: You're missing a lot of <code>title</code> and <code>alt</code> tags which are especially important for screen-readers (they also require the elements to be in a logical order, how to optimize a website for them is out of scope here). </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T11:52:49.777", "Id": "1914", "Score": "0", "body": "I only used alt on images, never really used title before in anything but the head, should these go anywhere else but images? I've also noticed img tags not closed in slideshow, that's code from the plugin source I'll fix that." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T11:58:17.240", "Id": "1915", "Score": "0", "body": "`title` can be a tag or an attribute ;) Old but should be ok to get the idea: http://www.netmechanic.com/news/vol6/html_no1.htm" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T11:39:08.193", "Id": "1083", "ParentId": "1077", "Score": "5" } }, { "body": "<p>Regarding speed, I don't think you have anything to worry about. As @Fgo mentioned, that typically has more to do with your application - not your static pages (unless they're enormous with tons of pictures and the like).</p>\n\n<p>When you're speaking of SEO and accessibility, those are really two sides to the same coin. It's important to know how your site will look in a text-only browser. Your page example will be usable, but a tad confusing without images or layout tags.</p>\n\n<p>First of all, only one <code>&lt;h1&gt;&lt;/h1&gt;</code> should appear on any single page. It should also typically be similar to your page title. I also noticed that you don't have a <code>&lt;meta keywords=\"\" /&gt;</code> tag (important). Additionally, I usually like to include my <code>&lt;h1&gt;</code> and my page's main and most important <code>&lt;p&gt;&lt;/p&gt;</code> immediately after the open <code>&lt;body&gt;</code> tag. Wrap this in a <code>&lt;div&gt;</code> and you can place it wherever you want later.</p>\n\n<p>@Fgo recommended that you should place your menu in an <code>&lt;ul&gt;&lt;/ul&gt;</code> which I think is a stylistic preference, and it's also pretty common practice. It's my opinion that a site's navigation belongs right below the first group of body text and again at the bottom of the page. This too can be moved wherever you want later in your CSS. Search engines want to see the meat-and-potatoes of your site as soon as possible and then branch off quickly without obstruction.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T13:37:56.763", "Id": "1086", "ParentId": "1077", "Score": "4" } }, { "body": "<ol>\n<li><p>You should add the meta viewport tag to ensure mobile browsers have a good standard viewport:</p>\n\n<pre><code>&lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"&gt;\n</code></pre></li>\n<li><p>You should specify <code>sans-serif</code> as the last resort for your font stack. Also if you want Helvetica to be used, move it to the front. If not, you can simply leave it out. That's because one can assume that on every system where Helvetica is installed, there is also Arial.</p>\n\n<pre><code>font-family: Helvetica, Arial, Verdana, sans-serif;\n</code></pre></li>\n<li><p>Something small: If you have a hex-based color value like <code>#0066ff</code>, <code>#ffffff</code> or <code>#000000</code> for example, you can write the shorter version: <code>#06f</code>, <code>#fff</code> and <code>#000</code></p></li>\n<li><p>Ommit the unit for zero values like <code>0px</code>: <code>box-shadow: 0 0 5px #555;</code></p></li>\n<li><p>You're resetting the margin on a lot of elements. Group this together to decrease repetition:</p>\n\n<pre><code>h1, h2, h3, h4, h5, h6,\np, blockquote {\n margin: 0;\n}\n</code></pre>\n\n<p>If you want to set a bottom margin, you only need <code>margin-bottom: 10px;</code>, not <code>margin: 0 0 10px 0;</code></p></li>\n<li><p>For clearfixing, you don't need a new <code>div</code> element. Add the following rule declaration to your CSS and add <code>clearfix</code> to the element you need to <em>fix</em>. (e.g. a navigation with floated items)</p>\n\n<pre><code>clear:after {\n content: \"\";\n display: table;\n clear: both;\n}\n</code></pre></li>\n<li><p>There is no reason to prefix <code>border-radius</code> anymore. You can use the unprefixed version safely.</p></li>\n</ol>\n\n<p>For the time, I'll stop here. I'd be great to hear some feedback. I have a few things in mind, but I don't know if you want to go this <em>deep</em>. No offense. ;) Feel free to ask questions, if you have them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-10T16:54:43.153", "Id": "41346", "ParentId": "1077", "Score": "8" } } ]
{ "AcceptedAnswerId": "1083", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-02T09:25:23.180", "Id": "1077", "Score": "8", "Tags": [ "javascript", "css", "html" ], "Title": "Demo of advertisment website" }
1077
<p>I have the following code which is a private method inside the form and retrieve all context menus from the form. I feel, that it is not that concise as it should be. Would be grateful for any suggestions.</p> <pre><code> private IEnumerable&lt;ContextMenuStrip&gt; GetContextMenus() { var type = this.GetType(); var fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance); var contextMenus = fields.Where(f =&gt; f.GetValue(this).GetType() == typeof(ContextMenuStrip)); var menus = contextMenus.Select(f=&gt; f.GetValue(this)); return menus.Cast&lt;ContextMenuStrip&gt;(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-24T09:15:47.003", "Id": "62862", "Score": "0", "body": "Kettic DataGridView is able to [create custom data grid context menus](http://www.kettic.com/winforms_ui/csharp_guide/gridview_context_menu_conditional.shtml) in C# to Data GirdView for Windows Forms applications" } ]
[ { "body": "<p>I can't imagine why do you do this via Reflection, I believe the same can be done by walking through <code>Controls</code> tree. Your method will not work if context menu has property <code>Generate member</code> set to <code>false</code> in designer.</p>\n\n<pre><code>var contextMenus = fields.Where(f =&gt; f.GetValue(this).GetType() == typeof(ContextMenuStrip));\nvar menus = contextMenus.Select(f=&gt; f.GetValue(this));\nreturn menus.Cast&lt;ContextMenuStrip&gt;(); \n</code></pre>\n\n<p>Can be replaced with:</p>\n\n<pre><code>return fields.Select(f =&gt; f.GetValue(this)).OfType&lt;ContextMenuStrip&gt;();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T14:01:58.023", "Id": "1917", "Score": "0", "body": "Thank you. Probably I should rewrite it using Controls collection." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T11:46:17.413", "Id": "1084", "ParentId": "1082", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T11:26:32.510", "Id": "1082", "Score": "3", "Tags": [ "c#", ".net", "winforms" ], "Title": "Retrieving context menus from the form" }
1082
<p>I have 3 methods(* BindingSource are bindingsources, context is data context, cache* -are some List for cache operations):</p> <pre><code> private void AddUpdateRowDocuments() { try { tRANSMITDOCDOCUMENTSRELATIONSBindingSource.EndEdit(); var t = tRANSMITDOCDOCUMENTSRELATIONSBindingSource.Current as WcfDataServiceReference.TRANSMIT_DOC_DOCUMENTS_RELATIONS; if (t.TRANSMIT_DOC_ID == 0) { if (!cachetddrList.Contains(t)) { cachetddrList.Add(t); } return; } context.UpdateObject(t); } catch (Exception ex) { logger.ErrorException(string.Empty, ex); } } private void AddUpdateRowOrganizations() { try { tRANSMITDOCORGANIZATIONRELATIONSBindingSource.EndEdit(); var t = tRANSMITDOCORGANIZATIONRELATIONSBindingSource.Current as WcfDataServiceReference.TRANSMIT_DOC_ORGANIZATION_RELATIONS; if (t.TRANSMIT_DOC_ID == 0) { if (!cachetdorList.Contains(t)) { cachetdorList.Add(t); } return; } context.UpdateObject(t); } catch (Exception ex) { logger.ErrorException(string.Empty, ex); } } private void AddUpdateRowPartators() { try { tRANSMITDOCPARTATORRELATIONSBindingSource.EndEdit(); var t = tRANSMITDOCPARTATORRELATIONSBindingSource.Current as WcfDataServiceReference.TRANSMIT_DOC_PARTATOR_RELATIONS; if (t.TRANSMIT_DOC_ID == 0) { if (!cachetdprList.Contains(t)) { cachetdprList.Add(t); } return; } context.UpdateObject(t); } catch (Exception ex) { logger.ErrorException(string.Empty, ex); } } </code></pre> <p>Any thoughts on how to improve them? My inner sense says that they can be turned into one generic method, but i have little experience with generics, so cant say if i am right.</p>
[]
[ { "body": "<p>Something along the lines of this. Generics aren't that difficult. Just replace every occurance of 'some desired type' with the generic identifier.</p>\n\n<pre><code>private void AddUpdateRow&lt;T&gt;(BindingSource bindingSource, List&lt;T&gt; cachedList)\n where T : ITransmitDocId\n{\n try\n {\n bindingSource.EndEdit();\n T t = bindingSource.Current as T;\n if (t.TRANSMIT_DOC_ID == 0)\n {\n if (!cachedList.Contains(t))\n {\n cachedList.Add(t);\n }\n return;\n }\n context.UpdateObject(t);\n }\n catch (Exception ex)\n {\n logger.ErrorException(string.Empty, ex);\n }\n}\n</code></pre>\n\n<p>The where constraint in the function definition should indicate a common interface/class in which <code>TRANSMIT_DOC_ID</code> is defined.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T14:52:45.450", "Id": "1922", "Score": "0", "body": "problem with t.TRANSMIT_DOC_ID: 'T' does not contain a definition for 'TRANSMIT_DOC_ID' and no extension method 'TRANSMIT_DOC_ID' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T14:55:25.313", "Id": "1923", "Score": "0", "body": "@nihi_l_ist: How are you calling this method? Does the error occur in the generic function or on the caller? Be sure to replace `T` with your desired type when calling the function. E.g. `AddUpdateRow<CourtWcfDataServiceReference.TRANSMIT_DOC_ORGANIZATION_RELATIONS>( bindingSource, cachedList )`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T14:58:48.193", "Id": "1924", "Score": "0", "body": "It appears in generic method(code does't even compile)..Think T must implement some interface that should be common for all that classes(like TRANSMIT_DOC_ORGANIZATION_RELATIONS and ets..)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T15:03:05.520", "Id": "1925", "Score": "0", "body": "Ok...thank you anyway .. I'll move that t.TRANSMIT_DOC_ID to method's parameters and that all..Code will become a bit wired, but it WILL wwork :) thanks for the answer." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T15:06:58.617", "Id": "1926", "Score": "0", "body": "@nihi_l_ist: oh I see the problem now! you can add a where clause to the function ... to indicate T is at least an interface you define which defines TRANSMIT_DOC_ID. WIll update the answer." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T15:12:01.240", "Id": "1928", "Score": "0", "body": "..i know :) but none of the input classes can implement common interface..Or i can create their partial versions and implement interface, but thats too much work for such piece of code. My point is reached here: I wanted to see how generic version would look like and youve shown me that." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T14:48:11.667", "Id": "1090", "ParentId": "1089", "Score": "4" } } ]
{ "AcceptedAnswerId": "1090", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T14:39:16.883", "Id": "1089", "Score": "6", "Tags": [ "c#", "linq" ], "Title": "Suggest how to extract method" }
1089
<p>How can I use a more generic method to clean up the redundancy in the switch statement below?</p> <p>I'm working on an ASP.NET webforms app that will have five identical user controls that I will be showing and hiding based on the value of a dropdown list. (I have already been down the path of trying to add and remove the controls dynamically--the issue of managing the view states for the controls would have been very complicated, so in the interest of shipping I'm opting for a fixed number of controls.)</p> <p>The approach I'm currently using works but isn't very elegant: </p> <pre><code>protected void DisplayUserControls(int numberOfControls) { switch (numberOfControls) { case 2: UserControl1.Visible = true; UserControl2.Visible = true; UserControl3.Visible = false; break; case 3: UserControl1.Visible = true; UserControl2.Visible = true; UserControl3.Visible = true; break; default: UserControl1.Visible = true; UserControl2.Visible = false; UserControl3.Visible = false; break; } } </code></pre> <p>What are some options here? The best I can come up with is using numberOfControls to build the name of the control, but that seems hacky. Suggestions appreciated.</p> <p>EDIT: I implemented a solution similar to the accepted answer below. I'm stuck on loading up the controls in the list. The commented out code is more along the lines of what I'd like to do but can't get it working. The uncommented code works. Suggestions? </p> <pre><code>private List&lt;ShiftControl&gt; PopulateShiftControlList() { ShiftControl shiftControlList = new List&lt;ShiftControl&gt;(); //ControlCollection panelControls = ShiftPanel.Controls; //foreach (ShiftControl control in panelControls) //{ // shiftControlList.Add(control); //} shiftControlList.Add(ShiftControl1); shiftControlList.Add(ShiftControl2); shiftControlList.Add(ShiftControl3); shiftControlList.Add(ShiftControl4); return shiftControlList; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T14:49:08.073", "Id": "16135", "Score": "0", "body": "Please don't use names like `UserControl`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-18T15:08:09.310", "Id": "16136", "Score": "0", "body": "Yeah... thanks? I don't, and I rarely name programs `MyProgram`. That was just to make it clear in my post what each item in the `case` statement was." } ]
[ { "body": "<p>I would create a list of usercontrols. Based on the amount of controls that need to be visible, traverse the list and set x controls to visible.</p>\n\n<pre><code>protected void DisplayUserControls(List&lt;UserControl&gt; controls, int numberOfControls)\n{\n Contract.Requires( numberOfControls &gt;= 0 &amp;&amp; numberOfControls &lt;= controls.Count );\n\n for ( int i = 0; i &lt; numberOfControls; ++i )\n {\n controls[ i ].Visible = true;\n }\n for ( int i = numberofControls; i &lt; controls.Count; ++i )\n {\n controls[ i ].Visible = false;\n }\n}\n</code></pre>\n\n<p>Or rather in one go:</p>\n\n<pre><code>protected void DisplayUserControls(List&lt;UserControl&gt; controls, int numberOfControls)\n{\n Contract.Requires( numberOfControls &gt;= 0 &amp;&amp; numberOfControls &lt;= controls.Count );\n\n for ( int i = 0; i &lt; controls.Count; ++i )\n {\n controls[ i ].Visible = i &lt; numberOfControls;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T15:10:30.937", "Id": "1927", "Score": "0", "body": "I like this a lot... It would also be useful when I need to retrieve the properties of the controls. I was thinking I would have to use a container like a panel and then grab each of the panel's children. The Contract.Requires piece... Can you explain that a little bit? Is it similar to a condensed if...else ?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T15:13:15.337", "Id": "1929", "Score": "0", "body": "That's a feature of .NET 4.0. It makes sure that when entering the function, the specified constraints are met. It's called Code Contracts. Instead of throwing an out of bounds exception when accessing controls, it will already know something is wrong when verifying the parameters. You could simply replace it with an exception you throw when the arguments aren't valid." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T15:15:08.880", "Id": "1930", "Score": "0", "body": "That's pretty neat. What happens if the constraints aren't met?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T15:17:39.297", "Id": "1931", "Score": "0", "body": "@Michael: That depends on how you set up to use code contracts in the environment options. You can either get a runtime exception with the inner condition specified as message, that's already more verbose than an index out of bounds, or you can't compile at all when using what is known as the static checker, and somewhere in your code you make a possible wrong call to this function. Unfortunately that's only available in Visual Studio Ultimate. :) This is an interesting new technology, it's a very interesting read! ;p" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T20:13:59.157", "Id": "1942", "Score": "0", "body": "I edited my original post with one more piece that needs work. Any suggestions?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T20:20:43.100", "Id": "1943", "Score": "0", "body": "@JoashEarl: Use a [list initializer](http://msdn.microsoft.com/en-us/library/bb384062.aspx) instead. ;p You could go even further and start using reflection and such, but that's too much for your purposes (and less safe)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T14:58:59.523", "Id": "1092", "ParentId": "1091", "Score": "8" } }, { "body": "<p>First thought:</p>\n\n<pre><code>UserControl1.Visible = true;\nUserControl2.Visible = true;\nUserControl3.Visible = true;\n\nswitch (numberOfControls)\n{\n case 1:\n UserControl2.Visible = false;\n UserControl3.Visible = false;\n break;\n case 2:\n UserControl3.Visible = false;\n break;\n case 3:\n} \n</code></pre>\n\n<p>EDIT: New idea:</p>\n\n<pre><code>Arraylist controls;\n\nfor (int x=0; x&lt;numberOfControls; x++)\n{\n ((Control)controls.get(x)).Visible = true;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T14:59:01.140", "Id": "1093", "ParentId": "1091", "Score": "1" } }, { "body": "<p>Man, all of these answers are way overkill for this. Just do:</p>\n\n<pre><code>protected void DisplayUserControls(int numberOfControls)\n{\n UserControl1.Visible = numberOfControls &gt; 0;\n UserControl2.Visible = numberOfControls &gt; 1;\n UserControl3.Visible = numberOfControls &gt; 2;\n}\n</code></pre>\n\n<p>Simple is good.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T01:38:37.573", "Id": "1954", "Score": "0", "body": "Simple is good, but the for loop are also three lines of code, and support as many controls as you want. ... unless you want to argue a for loop is too difficult? ;p" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T13:14:37.793", "Id": "1968", "Score": "2", "body": "This is definitely a simple approach, but it assumes that my code will remain small in scale. However, I simplified the scenario for this post. In my app, there are currently 10 controls across two panels, and there could potentially be more. The other suggestions are more lines of code, but I can add more controls without changing anything and without ending up with a big block of visibility toggles. I do like the way you're using a boolean test as the value for the visibility property; I might end up using that in other contexts." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T19:46:08.907", "Id": "1986", "Score": "0", "body": "If there are ten controls, make a collection and do a loop. If there were three I'd just do the above. Different scales call for different solutions. I wouldn't worry about \"potentially be more\". If there aren't more *now* just do the simple solution. That simpler code will be easy to change later if you need more and if you don't then you've kept things simple." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T01:24:29.500", "Id": "1110", "ParentId": "1091", "Score": "3" } } ]
{ "AcceptedAnswerId": "1092", "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T14:54:17.263", "Id": "1091", "Score": "9", "Tags": [ "c#", "asp.net" ], "Title": "Cleaning up a redundant switch statement" }
1091
<p>Is this, technically, a recursive function? It only gets called once by itself, but it cleaned up my code quite a bit, I think. Or, does it needlessly complicate the code?</p> <pre><code>sub check_backlog { my $topic = shift; my $prev_backlog = shift; my $backlog = undef; my @status = `$CMD -topicstat $topic`; foreach (@status) { if (/Message count: (\d+)/) { $backlog = $LAST_PAREN_MATCH; if ( !$prev_backlog &amp;&amp; $backlog &gt; 1 ) { sleep $topic_wait_time; check_backlog( $topic, $backlog ); } elsif ( $backlog &gt; $prev_backlog ) { check_over_thresholds($backlog); } } } return $backlog; } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T18:16:22.410", "Id": "1933", "Score": "0", "body": "Could you describe the intent of the code as well? I don't know enough PERL to entirely understand what you are actually doing, so I can't tell whether recursion is considered a good solution here." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T18:55:59.427", "Id": "1936", "Score": "0", "body": "@Steven Jeuris The intent is to query a queue, to determine if it is not moving data through it. This was written in perl because the queue is a vendor supplied JMS queue." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T19:11:48.623", "Id": "1938", "Score": "0", "body": "To see whether data is moving through, can't you just check the head element and see whether it changes over time? If I interpret that correctly, recursion isn't a good solution IMHO." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T19:18:51.370", "Id": "1940", "Score": "0", "body": "@Steven Jeuris - As for checking the head element, I don't know how I'd do that, outside of running this as Java instead. Again, it's not my code administering the queue. Any code examples would be appreciated." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T19:33:10.283", "Id": "1941", "Score": "0", "body": "I updated my answer with pseudo code with what I believe would be the proper solution for how I understand the intent of this code at the moment. To get help on how to achieve this in PERL, you probably have more luck on Stack Overflow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T23:02:26.783", "Id": "10827", "Score": "0", "body": "It's difficult to figure out what is actually happening here. I have no idea what `$CMD -topicstat $topic` returns. I can tell you that making it recursive was a mistake. If you posted the code you had before cleaning it up, then I could help you clean it up better." } ]
[ { "body": "<p>Yes, every function which calls itself is considered a <a href=\"http://en.wikipedia.org/wiki/Recursion_%28computer_science%29\" rel=\"nofollow\">recursive function</a>.</p>\n\n<p>Recursion is really useful when traversing trees and such.</p>\n\n<p>As I don't fully understand Perl, I can't really tell whether this case is proper use of recursion, perhaps also provide the intent of your code.</p>\n\n<p>UPDATE</p>\n\n<p>If you simply want to see whether data is passing (or not passing) through a queue, I wouldn't find recursion to be a suitable implemention.</p>\n\n<p>I would expect a function which returns either <code>true</code> or <code>false</code> after a given amount of time, or immediately when data is passing through.</p>\n\n<p>Consider the following pseudo code:</p>\n\n<pre><code>function isDataPassing( queue, time )\n{\n headOfQueue = queue.peek();\n dataPassing = false;\n while ( timePassed &lt; time )\n {\n if ( headOfQueue != queue.peek() )\n {\n dataPassing = true;\n break;\n }\n }\n\n return dataPassing;\n}\n</code></pre>\n\n<p>I can't help you with how you would go about implementing this in Perl. StackOverflow is a better location to ask such a question.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T22:54:35.397", "Id": "10826", "Score": "1", "body": "It's Perl not PERL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-18T00:09:59.480", "Id": "47423", "Score": "0", "body": "In Perl instead of setting a variable in the loop, and later returning it; you would just write `return 1;` ( `1` being a true value )" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-02T18:11:50.977", "Id": "1096", "ParentId": "1095", "Score": "3" } }, { "body": "<p>I don't know Perl well enough, but this looks suspicious to me. On the one hand, you return a value from <code>check_backlog</code> with:</p>\n\n<pre><code>return $backlog;\n</code></pre>\n\n<p>But when calling <code>check_backlog</code> you don't use the return value at all!</p>\n\n<pre><code>check_backlog( $topic, $backlog );\n</code></pre>\n\n<p>The only result of the recursive call is that it may <code>sleep</code> some time, but it will not affect returned value.</p>\n\n<p>But again, I know only a little Perl, so I might be wrong.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T18:56:58.037", "Id": "1937", "Score": "0", "body": "The code should flow like this: call #1 - get any count of backlog, call #2 - see that it's been called before, then check if the number of messages queued has grown. If it has, call the threshold check function." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T19:16:33.510", "Id": "1939", "Score": "0", "body": "I see what you're saying now. When it does return the $backlog var, it will return the first result, not the second, as it probably should?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-02T18:49:46.403", "Id": "1097", "ParentId": "1095", "Score": "1" } } ]
{ "AcceptedAnswerId": "1096", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-02T18:09:03.227", "Id": "1095", "Score": "4", "Tags": [ "perl", "subroutine" ], "Title": "Is calling a function only twice a good use of recursion?" }
1095
<p>This is a simple linked list program which creates a list by appending an object at the tail. It compiles and runs perfectly.</p> <p>Is the coding style, logic etc are fine? How can I improve this program? Is there anything redundant or did I miss out some important things?</p> <pre><code>#include&lt;iostream&gt; #include&lt;string&gt; using namespace std; class Link_list { private: string name; Link_list *next_node; public: void add_item(Link_list *); void add_item(); friend void show(Link_list *sptr) { while(sptr) { cout &lt;&lt; sptr-&gt;name &lt;&lt; endl; sptr = sptr-&gt;next_node; } } }; void Link_list::add_item() { cin &gt;&gt; name; next_node = NULL; } void Link_list::add_item(Link_list *pptr) { cin &gt;&gt; name; next_node = NULL; pptr-&gt;next_node = this; } int main() { Link_list *str_ptr = NULL; Link_list *curr_ptr = str_ptr; Link_list *prev_ptr; char ch = 'y'; str_ptr = new(Link_list); str_ptr-&gt;add_item(); curr_ptr = str_ptr; do { prev_ptr = curr_ptr; curr_ptr = new(Link_list); curr_ptr-&gt;add_item(prev_ptr); cout &lt;&lt;"Do you want to add the item" &lt;&lt; endl; cin &gt;&gt; ch; }while(ch != 'n'); show(str_ptr); } </code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T19:53:55.523", "Id": "1946", "Score": "0", "body": "why not just use `std::list`?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T19:57:22.333", "Id": "1947", "Score": "4", "body": "@AJG85: Education?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T20:09:12.993", "Id": "1950", "Score": "0", "body": "i think you've to separate the class definition and implementation... Create a .h and .cpp files for the class, and a main.cpp..." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T19:51:19.040", "Id": "58716", "Score": "0", "body": "Use [std::list](http://www.sgi.com/tech/stl/List.html)." } ]
[ { "body": "<p>You should use std::list...\nBut if you only wanna learn how the Linked List works, i suggest the using of templates classes and functions for make the code more generic as possible...</p>\n\n<p>It isnt very difficult:</p>\n\n<pre><code>template &lt;typename T&gt; \n\nclass List\n{\npublic:\n //Example declare the \"get\" and return a T element\n //where T is a generic element or data type\n T get_front() const;\nprivate:\n T data;\n List&lt;T&gt; *firt_Ptr;\n}\n</code></pre>\n\n<p>In the main file:</p>\n\n<pre><code>int main()\n{\n ...\n List&lt; int &gt; listofints;\n List&lt; double &gt; listofdoubles;\n ...\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T19:56:47.923", "Id": "1101", "ParentId": "1099", "Score": "4" } }, { "body": "<p>You can't remove elements from it.</p>\n\n<p>There is no search feature.</p>\n\n<p>All you can do is add stuff to it and then have its contents streamed to STDOUT.</p>\n\n<p>It can only hold strings.</p>\n\n<p>Blocking for user-input in the List class itself seems odd; usually you'd request the input in the calling scope and then pass the resultant new string to your <code>add</code> member function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T20:13:31.743", "Id": "1952", "Score": "0", "body": "for your last comment if i want to redesign class then in your case i have to change both the class and main. but here the way i have written i need to change only the class main remains untouched" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T20:17:04.813", "Id": "1953", "Score": "1", "body": "@user634615: Usually you design the class then leave it, which is what my way would give you. You expect to change things in your calling function anyway." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T19:56:53.363", "Id": "1102", "ParentId": "1099", "Score": "7" } }, { "body": "<p>In <code>main()</code> you are managing resources. Since the program manages resources( i.e., using <code>new</code> operator ), it should also return resources using <code>delete</code> operator. So, you should start deallocating the resources from the end point of the list before program termination. Else memory leaks prevail. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T20:04:12.117", "Id": "1103", "ParentId": "1099", "Score": "4" } }, { "body": "<p>Adding to Tomalak answer : </p>\n\n<p>=> destructor </p>\n\n<p>You create your linked list but how do you plan to delete it ? </p>\n\n<p>=> You can only iterate in one way</p>\n\n<p>When you have 1000 element and you want the last...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T05:15:01.700", "Id": "1961", "Score": "1", "body": "That's not the problem of the code, it's the constraint of data structure" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T20:07:51.123", "Id": "1104", "ParentId": "1099", "Score": "1" } }, { "body": "<p>I'm just going to comment on this from a high level since others have called out other details...</p>\n\n<p>Calling the object a <code>link_list</code> is misleading, since it isn't actually the list, but just a node in the full list. You might want to think about refactoring it so that you have an actual <code>list</code>, that has <code>list_node</code>'s internal to it. Your inserts also shouldn't expose those nodes directly, but have the ability to just take the data they want to insert. There's no need to expose the behavior of the list to the user.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-02T20:08:02.667", "Id": "1105", "ParentId": "1099", "Score": "5" } }, { "body": "<p>I cleaned up your code a bunch and described each change I made:</p>\n\n<pre><code>#include&lt;iostream&gt;\n#include&lt;string&gt;\n\nusing namespace std;\n\nclass List {\npublic:\n List();\n List(List* prev);\n\n static void show(List* list) {\n while (list) {\n cout &lt;&lt; list-&gt;name &lt;&lt; endl;\n list = list-&gt;next;\n }\n }\n\nprivate:\n string name;\n List* next;\n};\n\nList::List(string name)\n: name(name),\n next_node(NULL) {}\n\nList::List(string name, List *prev) \n: name(name),\n next_node(NULL) {\n prev-&gt;next = this;\n}\n\nint main() {\n string name;\n cin &gt;&gt; name;\n List* str = new List(name);\n List* curr = str;\n List* prev;\n char ch = 'y';\n do {\n prev = curr;\n cin &gt;&gt; name;\n curr = new List(name, prev);\n cout &lt;&lt; \"Do you want to add the item\" &lt;&lt; endl;\n cin &gt;&gt; ch;\n } while(ch != 'n');\n List::show(str);\n}\n</code></pre>\n\n<ol>\n<li><p>Your indentation is inconsistent, which makes it hard to understand the block structure.</p></li>\n<li><p>Those <code>add_</code> functions should be constructors. If you <code>new</code> a <code>Link_list</code> node and then don't call one, you get a broken uninitialized node. Good style is that a class shouldn't allow itself to be in an incomplete state. Moving that <code>add_</code> functionality directly into the constructors fixes that.</p></li>\n<li><p>There's no need for <code>show</code> to use <code>friend</code>.</p></li>\n<li><p>Either put <code>{</code> on the same line, or on their own, but don't mix the two. Style should be consistent or it's distracting.</p></li>\n<li><p><code>new(Link_list)</code> is not the normal syntax for dynamic allocation. Should be <code>new Link_list()</code>.</p></li>\n<li><p><code>pptr</code> and <code>sptr</code> aren't helpful names. You don't really need to add <code>_ptr</code> all over the place either.</p></li>\n<li><p><code>show()</code> doesn't access any instance state, so doesn't need to be an instance method.</p></li>\n<li><p><code>Link_list</code> is a weird naming style. People using underscores for word separators rarely use capital letters too.</p></li>\n<li><p>Reading user input directly in the list class is weird. Try to keep different responsibilities separate. List's responsibility is the data structure, not talking to stdin.</p></li>\n<li><p>In C++ (as opposed to older C) you don't have to declare variables at the top of a function. Convention is to declare them as late as possible to minimize their scope.</p></li>\n<li><p>Use constructor initialization lists when you can.</p></li>\n<li><p><code>next_node</code> is a strange name since you don't use \"node\" anywhere else to refer to the list.</p></li>\n<li><p>I tend to put public stuff before private stuff since that what user's of your code will need to read the most.</p></li>\n<li><p>You never actually de-allocate the nodes you create, but I didn't fix that here.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T15:18:19.083", "Id": "3876", "ParentId": "1099", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-02T19:47:02.693", "Id": "1099", "Score": "9", "Tags": [ "c++", "linked-list" ], "Title": "Linked List program" }
1099
<p>Just as a refresher I put together a simple Map implementation and I would love to get some feedback on it.</p> <pre><code>open System open System.Collections.Generic type Node&lt;'a, 'b when 'a : comparison&gt; = { key : 'a value : 'b left : option&lt;Node&lt;'a, 'b&gt;&gt; right : option&lt;Node&lt;'a, 'b&gt;&gt; } type Map&lt;'a, 'b when 'a : comparison&gt;(root : option&lt;Node&lt;'a, 'b&gt;&gt;) = let comparer = LanguagePrimitives.FastGenericComparer&lt;'a&gt; let rec add (key : 'a) (value : 'b) (node : Node&lt;'a, 'b&gt;) = match comparer.Compare (key, node.key) with | r when r &lt; 0 -&gt; match node.left with | Some n -&gt; match comparer.Compare (key, n.key) with | r when r &gt; 0 -&gt; let left = Some { key = key value = value left = node.left right = None } Some { node with left = left } | _ -&gt; Some { node with left = add key value n } | None -&gt; let left = Some { key = key value = value left = None right = None } Some { node with left = left } | r when r &gt; 0 -&gt; match node.right with | Some n -&gt; match comparer.Compare (key, n.key) with | r when r &lt; 0 -&gt; let right = Some { key = key value = value left = None right = node.right } Some { node with right = right } | _ -&gt; Some { node with right = add key value n } | None -&gt; let right = Some { key = key value = value left = None right = None } Some { node with right = right } | _ -&gt; Some { node with value = value } let rec find (key : 'a) (node : Node&lt;'a, 'b&gt;) = match comparer.Compare (key, node.key) with | r when r &lt; 0 -&gt; match node.left with | Some node -&gt; find key node | None -&gt; raise (KeyNotFoundException()) | r when r &gt; 0 -&gt; match node.right with | Some node -&gt; find key node | None -&gt; raise (KeyNotFoundException()) | _ -&gt; node.value member x.Item key = match root with | Some node -&gt; find key node | None -&gt; raise (KeyNotFoundException()) member x.Add (key : 'a, value : 'b) = match root with | Some node -&gt; Map (add key value node) | None -&gt; let node = Some { key = key value = value left = None right = None } Map node static member Empty = Map&lt;'a, 'b&gt;(None) static member FromSeq (s:seq&lt;'a * 'b&gt;) = s |&gt; Seq.fold (fun (m:Map&lt;'a, 'b&gt;) (k, v) -&gt; m.Add (k, v)) Map&lt;'a, 'b&gt;.Empty </code></pre> <p>After running some basic tests I found my implementation is comparable to the <code>FSharpMap</code>class in performance and sometimes better. Obviously I don't have the time/desire to test this extensively so take that with a grain of salt. I'm wondering if anyone can spot a characteristic of this code that will cause a performance breakdown under certain conditions or for certain types of keys.</p> <p><strong>Improved Version</strong></p> <pre><code>open System open System.Collections.Generic type Node&lt;'a, 'b when 'a : comparison&gt; = { key : 'a value : 'b height : int left : option&lt;Node&lt;'a, 'b&gt;&gt; right : option&lt;Node&lt;'a, 'b&gt;&gt; } type Map&lt;'a, 'b when 'a : comparison&gt;(root : option&lt;Node&lt;'a, 'b&gt;&gt;) = let comparer = LanguagePrimitives.FastGenericComparer&lt;'a&gt; let height node = match node with | Some node -&gt; node.height | None -&gt; 0 let make key value left right = let h = match height left, height right with | l, r when l &gt;= r -&gt; l + 1 | l, r -&gt; r + 1 Some { key = key; value = value; height = h; left = left; right = right } let balance key value left right = match height left, height right with | l, r when r &gt; l + 2 -&gt; match right with | Some rn -&gt; match height rn.left with | rl when rl &lt;= l + 1 -&gt; let left = make key value left rn.left make rn.key rn.value left rn.right | _ -&gt; match rn.left with | Some rnl -&gt; let left = make key value left rnl.left let right = make rn.key rn.value rnl.right rn.right make rnl.key rnl.value left right | None -&gt; make key value left right | None -&gt; make key value left right | l, r when l &lt;= r + 2 -&gt; make key value left right | l, r -&gt; match left with | Some ln -&gt; match height ln.right with | rl when rl &lt;= l + 1 -&gt; let right = make key value ln.right right make ln.key ln.value ln.left right | _ -&gt; match ln.right with | Some lnr -&gt; let left = make ln.key ln.value ln.left lnr.left let right = make key value lnr.right right make lnr.key lnr.value left right | None -&gt; make key value left right | None -&gt; make key value left right let rec add key value node = match comparer.Compare (key, node.key) with | r when r &lt; 0 -&gt; match node.left with | Some n -&gt; balance node.key node.value (add key value n) node.right | None -&gt; let left = Some { key = key value = value height = node.height + 1 left = None right = None } balance node.key node.value left node.right | r when r &gt; 0 -&gt; match node.right with | Some n -&gt; balance node.key node.value node.left (add key value n) | None -&gt; let right = Some { key = key value = value height = node.height + 1 left = None right = None } balance node.key node.value node.left right | _ -&gt; Some { node with value = value } let rec find key node = match comparer.Compare (key, node.key) with | r when r &lt; 0 -&gt; match node.left with | Some node -&gt; find key node | None -&gt; raise (KeyNotFoundException()) | r when r &gt; 0 -&gt; match node.right with | Some node -&gt; find key node | None -&gt; raise (KeyNotFoundException()) | _ -&gt; node.value member x.Item key = match root with | Some node -&gt; find key node | None -&gt; raise (KeyNotFoundException()) member x.Add (key, value) = match root with | Some node -&gt; Map (add key value node) | None -&gt; let node = Some { key = key value = value height = 1 left = None right = None } Map node static member Empty = Map&lt;'a, 'b&gt;(None) static member OfSeq (s:seq&lt;'a * 'b&gt;) = s |&gt; Seq.fold (fun (m:Map&lt;'a, 'b&gt;) (k, v) -&gt; m.Add (k, v)) Map&lt;'a, 'b&gt;.Empty </code></pre>
[]
[ { "body": "<h3>Second revision</h3>\n\n<p>Ok, first of all it would really help if you added some comments. I would also suggest giving your variables names which have more than one letter.</p>\n\n<p>In particular it would be a good idea to describe the algorithms being used. In particular you should document what kind of tree and balancing algorithm you're using.</p>\n\n<p>Speaking of: your tree kind of looks like an AVL tree except that in AVL trees the maximum difference between heights is 1, while you allow a difference of 2. Since you never said that you were trying to implement an AVL tree, I'm not sure whether that's intentional or not.</p>\n\n<hr>\n\n<p>Some notes on particular pieces of code:</p>\n\n<pre><code>match height left, height right with\n| l, r when l &gt;= r -&gt; l + 1\n| l, r -&gt; r + 1\n</code></pre>\n\n<p>That's just a cumbersome way to write <code>max (height left) (height right)</code>.</p>\n\n<hr>\n\n<pre><code>Some {\n key = key\n value = value\n height = node.height + 1\n left = None\n right = None\n}\n</code></pre>\n\n<p>This looks like a mistake. If both the subtrees are empty, then clearly the height is 1 and not dependent on <code>node</code>.</p>\n\n<hr>\n\n<p>I would also recommend that instead of using <code>Node option</code>s you define an actual tree type like this: <code>type ('a * 'b) tree = Node of ('a, 'b) Node | EmptyTree</code>. This way you can refer to empty trees as <code>EmptyTree</code> rather than <code>None</code> and to nodes as <code>Node {...}</code> rather than <code>Some {...}</code>. Of course that's just cosmetics, but I do think it reads much nicer.</p>\n\n<hr>\n\n<h3>First revision</h3>\n\n<p>One minor style point is that you might want to call your <code>FromSeq</code> method <code>ofSeq</code> instead as that is what the equivalent function of F#'s <code>Map</code> module is called.</p>\n\n<hr>\n\n<p>Regarding performance the most obvious problem is that your tree is not balanced in any way. If you create a map from a sorted list of keys, it will degenerate into a linked list and have much worse performance than F#'s standard map class. Just compare the time it takes to create your map from <code>Seq.zip [1..500000] [1..500000]</code> to the time the standard Map needs for the same input.</p>\n\n<p>To address this, you should implement some kind of balancing. For example you may use <a href=\"http://en.wikipedia.org/wiki/Red_black_trees\">red-black trees</a>, which is what F#'s standard map uses.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-05T21:27:27.743", "Id": "2065", "Score": "0", "body": "You were so right about my implementation. I tried adding 50k keys and it exploded with a `StackOverflowException`. After I implemented balancing, my implementation comes out to be oh so slightly faster the the built-in version which I crop up to slightly less object creation and less robust code. Anyway, thanks so much and feel free to comment on my latest version." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-06T00:02:34.667", "Id": "2067", "Score": "0", "body": "@Chaos: I've edited my answer in response to your revision." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-06T00:15:23.687", "Id": "2068", "Score": "0", "body": "Damn, you're right. I can't half ass this. I'm gonna tidy things up and drop you a comment sometime next week just in case you are curious." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T20:29:50.683", "Id": "1165", "ParentId": "1107", "Score": "8" } } ]
{ "AcceptedAnswerId": "1165", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-02T20:38:17.347", "Id": "1107", "Score": "7", "Tags": [ "f#", "hash-map" ], "Title": "Map implementation in F#" }
1107
<p>I have a function that returns an array and I want to check that a certain value is not set in the array.</p> <pre><code>function testFunction() { return array('key' =&gt; 404) } if (testFunction()['key'] &lt; 404) { // stay calm and carry on } else { // uh oh } </code></pre> <p>I understand that the above will not work in php 5.3 (or anything below), however, I'd like to know what I should do in the above case. That is - what should I call the temporary array I create for the if statement? Or is there another way of dealing with this situation?</p> <p>The following is what I would roughly do currently:</p> <pre><code>function testFunction() { return array('key' =&gt; 404) } $test_array = testFunction(); if ($test_array['key'] &lt; 404) { // stay calm and carry on } else { // uh oh } </code></pre> <p>Is this an acceptable thing to do?</p>
[]
[ { "body": "<p>So, .. you want to simply check whether a certain key in an array is set to a certain value.</p>\n\n<p>You can't do this directly on the function call because <a href=\"https://stackoverflow.com/q/2282051/590790\">older PHP versions don't support array dereferencing</a>. You are right when saying you'll need an intermediate variable.</p>\n\n<p>The only question remaining is what to name it. Considering that the variable will probably be situated in a really small scope, don't worry about it too much. There is a saying which says, <strong>the bigger the scope, the bigger the name</strong>. You could just name it <code>$list</code>.</p>\n\n<p>Old replies:</p>\n\n<blockquote>\n <p>Your code does something else as what\n you describe? If you want to see\n whether a given value is present in\n the array, use <a href=\"http://php.net/manual/en/function.in-array.php\" rel=\"nofollow noreferrer\"><code>in_array()</code></a>.</p>\n \n <p>UPDATE:</p>\n \n <p>I believe I understand what you are\n trying to accomplish now. You just\n want to see whether the key is set?</p>\n \n <p><a href=\"http://php.net/manual/en/function.array-key-exists.php\" rel=\"nofollow noreferrer\"><code>array_key_exists()</code></a></p>\n \n <p>PHP has got a pretty good online API,\n be sure to check it for existing\n implementations when looking for a\n solution.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T02:44:39.633", "Id": "1955", "Score": "0", "body": "According to the code, Jonathan also wants to compare against the value mapped to that key if there is one." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T02:56:12.530", "Id": "1957", "Score": "0", "body": "I want to know if a specific key has the value 404. so in_array() will not work because the value may exist somewhere else and array_key_exist will not work because I know the key exists. I want to know if a specific key I know is there has the value 404." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T03:21:18.070", "Id": "1959", "Score": "0", "body": "@Jonathan Mayhak: K, I finally understand your question now. ;p I updated the answer." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T03:36:12.057", "Id": "1960", "Score": "0", "body": "I was just curious if there was some standard in php for dealing with this situation. Good to know what I've been doing is acceptable." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T02:01:13.710", "Id": "1112", "ParentId": "1111", "Score": "3" } }, { "body": "<p>Your question does not match your code. You ask to check that a key does not exist in the array, yet you are actually testing <em>the value mapped to that key</em> against some other value, presumably doing something else if the key doesn't exist.</p>\n\n<pre><code>$result = testFunction();\nif (!isset($result['key']) || $result['key'] &lt; 404) {\n // ok\n}\nelse {\n // panic\n}\n</code></pre>\n\n<p>You can create a helper method with a suggestive name that does the full check and use that in your <code>if</code> clause.</p>\n\n<pre><code>function omgWeGotTheDreaded404() {\n $result = testFunction();\n return isset($result['key'] &amp;&amp; $result['key'] &gt;= 404;\n}\n\n...\n\nif (omgWeGotTheDreaded404()) ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T02:59:38.597", "Id": "1958", "Score": "0", "body": "Your answer is the same thing I wrote above for the second example. I know I can do what you wrote. I want to know if what we both wrote is the best way. What do you think is a good thing to name the temporary array? (you used $result and I used $test_array)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T08:02:46.460", "Id": "1962", "Score": "0", "body": "Steven's answer about the name is good advice. It lives such a short life, give it a terse name. My point is that I'd still put it inside a function that returns `bool` so you don't need a temporary array outside the function. If you only do this in one place, it's not of much value." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T02:43:51.290", "Id": "1113", "ParentId": "1111", "Score": "1" } } ]
{ "AcceptedAnswerId": "1112", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T01:47:57.990", "Id": "1111", "Score": "1", "Tags": [ "php" ], "Title": "Best way to use an array that is returned from a function immediately in PHP" }
1111
<p>I would really appreciate it if someone could review my quicksort implementation. Additionally, I generated my list dynamically and wrote a couple of tests. Of course, I realize that the tests are not complete, but I decided to stop where I was and see if I could get some feedback.</p> <pre><code>(defun categorize_list(pivot thelist less more) (let ((comparee (car thelist)) (therest (cdr thelist))) (if (null thelist) (list less more) (if (&lt; comparee pivot) (categorize_list pivot therest (append less (list comparee)) more) (categorize_list pivot therest less (append more (list comparee))) ) ) ) ) (defun quicksort(thelist) (if (null thelist) () (let ( (pivot (car thelist)) (therest (cdr thelist)) ) (let ((categorized_list (categorize_list pivot therest () ()))) (append (quicksort (nth 0 categorized_list)) (list pivot) (quicksort (nth 1 categorized_list))) ) ) ) ) (defun make_list(thelist remaininglength) (if (eq remaininglength 0) thelist (make_list (append (list (random 25)) thelist) (- remaininglength 1)) ) ) (defun should_be_least_to_greatest(thelist) (if (&lt; (length thelist) 2) nil (if (&lt;= (nth 0 thelist) (nth 1 thelist)) (should_be_least_to_greatest (cdr thelist)) (error "Out of order: ~d !&lt; ~d ~%" (nth 0 thelist) (nth 1 thelist)) ) ) ) (defun test_should_become_in_order(thelist) (let ((sortedList (quicksort thelist))) (format t "IN: ~a ~% SD: ~a ~% Testing sort.~%" thelist sortedList) (should_be_least_to_greatest sortedList) ) ) (defun test_should_maintain_length(thelist) (if (not (eql (length thelist) (length (quicksort thelist)))) (error "The sorted list is a different length than the original list! ~%") ) ) (let ((thelist (make_list () 10))) (test_should_become_in_order thelist) (test_should_maintain_length thelist) ) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-27T09:30:39.707", "Id": "136241", "Score": "0", "body": "Asymptotically, this isn't a quicksort... appending lists the way you do it makes it more expensive than the textbook version. This also conses a lot of memory. Quicksort is best suited for in-place updates of arrays with O(1) random access cost, it's not so great for lists. I think most Lisp implementations use mergesort for Lists." } ]
[ { "body": "<p>Your formatting is weird. It's going to be a lot easier for other programmers to read your code if you use a more standard style. For example, you have lots of lines with nothing but a hanging parenthesis. Your functions have no docstrings. Sometimes you <code>use_underscores</code> and sometimes you use <code>compoundwords</code> but the Lisp style is <code>hypenated-words</code>. Your indentation is inconsistent: learn the command in your text editor to indent your source code for you, and use it.</p>\n\n<p>Instead of:</p>\n\n<pre><code>(if (not (eql (length thelist) (length (quicksort thelist))))\n</code></pre>\n\n<p>Using EQL for numbers seems odd. I think = would be preferred. An IF with only one branch is strange, too: WHEN or UNLESS tends to be preferred. Thus:</p>\n\n<pre><code>(unless (= (length thelist) (length (quicksort thelist)))\n</code></pre>\n\n<p>In another place, you do a comparison with:</p>\n\n<pre><code>(eq remaininglength 0)\n</code></pre>\n\n<p>The behavior of EQ with integers is undefined. You can use = or in this case:</p>\n\n<pre><code>(zerop remaininglength)\n</code></pre>\n\n<p>You're using recursion a lot even when it's not needed, e.g., in <code>make_list</code> and <code>should_be_least_to_greatest</code>. Common Lisp doesn't require tail-call optimization, and it's not generally common style. LOOP (or ITERATE) would probably be simpler and more efficient here.</p>\n\n<p>You walk a list applying <code>&lt;=</code>. Lisp's <code>&lt;=</code> already takes any number of arguments, so if you don't need to know the specific elements which are out of order, you can just apply it once.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T07:12:43.093", "Id": "1115", "ParentId": "1114", "Score": "8" } }, { "body": "<p>You have several negative conditionals, which is a bad idea in any language.</p>\n\n<pre><code>(if (null thelist)\n ()\n</code></pre>\n\n<p>I'd change it to:</p>\n\n<pre><code>(defun quicksort(thelist)\n (unless (null thelist)\n ; Sort list\n ) ; Pardon the dangling ), but there's a comment on the last line\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-05T15:42:08.713", "Id": "2055", "Score": "1", "body": "That doesn't bother me as much: it's making the \"return an empty list\" case clear." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T16:21:39.193", "Id": "1123", "ParentId": "1114", "Score": "2" } }, { "body": "<p>I don't know what the policy is about where/how to put subsequent code reviews, since the Stackexchange system doesn't really seem well-suited to their threadlike nature. Anyway, here goes.</p>\n\n<pre><code>(let ((pivot (car the-list)) (the-rest (cdr the-list)))\n (let ((categorized-list (categorize-list pivot the-rest () ())))\n</code></pre>\n\n<p>Look up <code>LET*</code>.</p>\n\n<pre><code>(let ((the-list ()))\n (loop for l from 1 to length do (setq the-list (append the-list (list (random 25))))) the-list))\n</code></pre>\n\n<p>This seems pretty awkward. It's just:</p>\n\n<pre><code>(loop for l from 1 to length collect (random 25))\n</code></pre>\n\n<p>And here:</p>\n\n<pre><code>(loop for l from 0 to (- (length the-list) 2) do\n (unless (&lt;= (nth l the-list) (nth (+ l 1) the-list)) (error \"Out of order: ~d &lt; ~d ~%\" (nth l the-list) (nth (+ l 1) the-list)))))\n</code></pre>\n\n<p>Every call to <code>LENGTH</code> or <code>NTH</code> has to walk the linked list. You don't want to do that in a loop. (I think you should not often need <code>NTH</code> with lists, and almost never in a loop.)</p>\n\n<pre><code>(loop for p on the-list while (second p)\n when (&lt; (second p) (first p))\n do (error \"Out of order: ~d &lt; ~d~%\" (second p) (first p)))\n</code></pre>\n\n<p>If you're going to be writing Common Lisp code, it pays to learn the <code>LOOP</code> DSL (or <code>ITERATE</code>, its spiritual successor).</p>\n\n<p>Other random things:</p>\n\n<ul>\n<li>Your code has gotten a lot ... wider. While I appreciate taking fewer lines, there's a limit. I don't often see multiple <code>LET</code> bindings on one line, for example.</li>\n<li>You sometimes still leave out the space before a paren, like <code>list(pivot</code>, which looks funny to me.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-05T16:26:23.327", "Id": "1169", "ParentId": "1114", "Score": "5" } } ]
{ "AcceptedAnswerId": "1169", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-03T04:13:02.420", "Id": "1114", "Score": "5", "Tags": [ "lisp", "quick-sort", "common-lisp" ], "Title": "Lisp quicksort code" }
1114
<p>What it does is:</p> <ol> <li>Reads from a RSS feed using Google Feed API</li> <li>Shows the list in an unordered list</li> </ol> <p>How good/bad is the code snippet?</p> <pre><code>$(document).ready(function(){ var FeedManager = { config : { feedContainer : $('#feedContainer'), feedUrl : 'http://rss.bdnews24.com/rss/english/home/rss.xml', feedLimit : 10 }, init: function(){ var feed = new google.feeds.Feed(FeedManager.config.feedUrl); feed.setNumEntries(FeedManager.config.feedLimit) ; feed.load(function(result) { if (!result.error) { FeedManager.$feedContainer = FeedManager.config.feedContainer; for (var i = 0; i &lt; result.feed.entries.length; i++) { var entry = result.feed.entries[i]; $('&lt;li/&gt;').append( $('&lt;a&gt;'+entry.title+'&lt;/a&gt;').attr( { 'title': entry.title, 'href': entry.link } ).bind('click',FeedManager.showStory) ).appendTo(FeedManager.$feedContainer); } } else{ FeedManager.handleError(result.error.message); } }); }, showStory: function(){ var href = event.currentTarget.href; FeedManager.showURL(href); event.preventDefault(); }, showURL: function(url){ if (url.indexOf("http:") != 0 &amp;&amp; url.indexOf("https:") != 0) { return; } chrome.tabs.create({ url: url }); }, handleError: function(errorText){ $('&lt;li/&gt;') .css("color","red") .append("Error:"+errorText) .appendTo(FeedManager.config.feedContainer); } }; FeedManager.init(); }); </code></pre> <p>At the 2nd stage, I wanted to add custom accordion feature and news snippet:</p> <pre><code>processFeedResult: function(result) { if (result.error) { FeedManager.handleError(result.error.message); return; } FeedManager.$feedContainer = FeedManager.config.feedContainer; $.each(result.feed.entries, function() { $('&lt;li/&gt;').append( $('&lt;a&gt;', { // this should not be an anchor tag,right? TBD title: 'Published at: '+this.publishedDate, text: this.title }) ).append($('&lt;div&gt;', { text: this.contentSnippet, css : {'display':'none', 'padding-top':'2px'} }).append( $('&lt;a&gt;', { text: '[more..]', href: this.link, click: FeedManager.showStory })) ) .bind('click',FeedManager.showSnippet) .appendTo(FeedManager.$feedContainer); }); }, showSnippet: function() { var $obj = $(event.currentTarget), $snippetDiv = $obj.find('div').slideDown('normal'); if(FeedManager.$lastOpenedDiv === undefined){ FeedManager.$lastOpenedDiv = $snippetDiv ; } else{ FeedManager.$lastOpenedDiv.slideUp('normal'); FeedManager.$lastOpenedDiv = $snippetDiv ; } } }; </code></pre> <p>I feel that I have put some tightly coupled code in my <code>processFeedResult</code> such as text and CSS. I also wanted to know if my <code>showSnippet</code> function good enough or not. However, it works, and I know that there are 3rd party good accordion available, but I wanted to learn it.</p> <p>So far I've kept the anchor tag to show the news title and I used anchor title as a tooltip that shows the time. Maybe there is a good alternate, like span or paragraph? </p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-05T16:42:02.963", "Id": "2056", "Score": "0", "body": "I think that you should take a look at jQuery TMPL." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-10T18:06:17.980", "Id": "2175", "Score": "0", "body": "you should run it through jsLint. Also, you should use *one* var statement per function." } ]
[ { "body": "<p>Looks ok, to be honest. A few minor changes I would make:</p>\n\n<p>I would pull this code out into a function</p>\n\n<pre><code>function ProcessFeedResult(result) {\n if (!result.error) {\n FeedManager.$feedContainer = FeedManager.config.feedContainer;\n for (var i = 0; i &lt; result.feed.entries.length; i++) {\n var entry = result.feed.entries[i];\n $('&lt;li/&gt;').append(\n $('&lt;a&gt;'+entry.title+'&lt;/a&gt;').attr(\n {\n 'title': entry.title,\n 'href': entry.link\n }\n ).bind('click',FeedManager.showStory)\n ).appendTo(FeedManager.$feedContainer);\n }\n }\n else{\n FeedManager.handleError(result.error.message);\n }\n}\n</code></pre>\n\n<p>Then I would reverse the condition and return, to reduce the level of indent a bit</p>\n\n<pre><code>function ProcessFeedResult(result) {\n if (result.error) {\n FeedManager.handleError(result.error.message);\n return;\n }\n\n FeedManager.$feedContainer = FeedManager.config.feedContainer;\n for (var i = 0; i &lt; result.feed.entries.length; i++) {\n var entry = result.feed.entries[i];\n $('&lt;li/&gt;').append(\n $('&lt;a&gt;'+entry.title+'&lt;/a&gt;').attr(\n {\n 'title': entry.title,\n 'href': entry.link\n }\n ).bind('click',FeedManager.showStory)\n ).appendTo(FeedManager.$feedContainer);\n }\n}\n</code></pre>\n\n<p>Further, I would replace the loop with jQuery's <code>$.each()</code></p>\n\n<pre><code>function ProcessFeedResult(result) {\n if (result.error) {\n FeedManager.handleError(result.error.message);\n return;\n }\n\n FeedManager.$feedContainer = FeedManager.config.feedContainer;\n $.each(result.feed.entries, function() {\n $('&lt;li/&gt;').append(\n $('&lt;a&gt;' + this.title + '&lt;/a&gt;').attr(\n {\n 'title': this.title,\n 'href': this.link\n }\n ).bind('click',FeedManager.showStory)\n ).appendTo(FeedManager.$feedContainer);\n });\n}\n</code></pre>\n\n<p>You can do any or all of these, I don't think any of it is vastly important. I can read your intent easily enough, it just looks a bit neater to me after refactoring.</p>\n\n<p>Thinking about your later comment a bit, I would also be tempted to append the title, rather than stringing it together.</p>\n\n<pre><code>function ProcessFeedResult(result) {\n if (result.error) {\n FeedManager.handleError(result.error.message);\n return;\n }\n\n FeedManager.$feedContainer = FeedManager.config.feedContainer;\n $.each(result.feed.entries, function() {\n $('&lt;li/&gt;').append(\n $('&lt;a/&gt;').append(this.title).attr(\n {\n 'title': this.title,\n 'href': this.link\n }\n ).bind('click',FeedManager.showStory)\n ).appendTo(FeedManager.$feedContainer);\n });\n}\n</code></pre>\n\n<p>Otherwise this is the correct approach to generating elements, as far as I know.</p>\n\n<p>As a final step, I would tidy up the braces around the attributes, for consistency</p>\n\n<pre><code>function ProcessFeedResult(result) {\n if (result.error) {\n FeedManager.handleError(result.error.message);\n return;\n }\n\n FeedManager.$feedContainer = FeedManager.config.feedContainer;\n $.each(result.feed.entries, function() {\n $('&lt;li/&gt;').append(\n $('&lt;a/&gt;').append(this.title).attr({\n 'title': this.title,\n 'href': this.link\n }).bind('click',FeedManager.showStory)\n ).appendTo(FeedManager.$feedContainer);\n });\n}\n</code></pre>\n\n<p>I really don't think you're going to get it any cleaner than that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T18:38:45.580", "Id": "1983", "Score": "0", "body": "Thanks for the nice help! No worries,The code worked fine :D , Still I am wondering, how to build the li and anchor tags in a nice way." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T19:04:07.490", "Id": "1985", "Score": "0", "body": "@user1234 - See latest edit" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T20:44:12.623", "Id": "1989", "Score": "0", "body": "@nezz - Happy to help, it was a good question. Don't forget to vote and accept on the left" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T20:51:34.130", "Id": "1992", "Score": "0", "body": "sure,but I still don't have 15 reputation to qualify for voting :(" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-05T21:29:53.060", "Id": "2066", "Score": "0", "body": "@pdr - I've added some new features,would you give a look please." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T14:59:00.323", "Id": "2082", "Score": "0", "body": "@nezz - if you want a second review, post a second question, otherwise it gets real messy in here if I don't have time to answer in full this week" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T15:25:31.210", "Id": "1120", "ParentId": "1118", "Score": "13" } }, { "body": "<p>You can use jQuery 1.4's <a href=\"http://api.jquery.com/jquery/#jQuery2\" rel=\"nofollow\">new element creation syntax</a> to shorten things a little (rewriting pdr's answer): </p>\n\n<pre><code>$('&lt;li&gt;').append(\n $('&lt;a&gt;', {\n title: this.title,\n text: this.title,\n href: this.link,\n click: FeedManager.showStory\n })\n).appendTo(FeedManager.$feedContainer);\n</code></pre>\n\n<p>And the same can be done with the element created in the <code>handleError</code> function </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-05T02:46:12.990", "Id": "1167", "ParentId": "1118", "Score": "5" } }, { "body": "<p>There is no comments.</p>\n\n<p>This:</p>\n\n<blockquote>\n <p>What it does is:</p>\n \n <p>Reads from a RSS feed using google\n feed API shows the list in an\n unordered list.</p>\n</blockquote>\n\n<p>Should be a comment somewhere in top of the code</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-05T10:06:13.977", "Id": "1168", "ParentId": "1118", "Score": "1" } } ]
{ "AcceptedAnswerId": "1120", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-03T14:08:45.567", "Id": "1118", "Score": "15", "Tags": [ "javascript", "jquery", "css", "rss" ], "Title": "Displaying RSS feeds from Google Feed API as HTML list" }
1118
<pre><code>class Pool(type): pool = dict() def __new__(clas, *a, **k): def __del__(self): Pool.pool[self.__class__] = Pool.pool.get(self.__class__, []) + [self] a[-1]['__del__'] = __del__ return type.__new__(clas, *a, **k) def __call__(clas, *a, **k): if Pool.pool.get(clas): print('Pool.pool is not empty: return an already allocated instance') r = Pool.pool[clas][0] Pool.pool[clas] = Pool.pool[clas][1:] return r else: print('Pool.pool is empty, allocate new instance') return type.__call__(clas, *a, **k) class Foo(metaclass=Pool): def __init__(self): print('Foo &gt; .', self) def foo(self): print('Foo &gt; foo:', self) f1 = Foo() f1.foo() print('## now deleting f1') del f1 print('## now create f2') f2 = Foo() f2.foo() print('## now create f3') f3 = Foo() f3.foo() </code></pre> <p>what do you think about this piece of code?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T16:54:13.780", "Id": "1976", "Score": "0", "body": "Well, calling class variables \"clas\" annoys the heck out of me. klass or class_ is better IMO. But that's a matter of taste." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T22:35:14.517", "Id": "1998", "Score": "0", "body": "i don't like k in place of c, but i'm agree with bad sound of 'clas' too : )" } ]
[ { "body": "<p>Name your arguments. If you know enough about what you'll have passed in to take item -1 of the positional argument list, you know enough to give it a name.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T18:38:36.483", "Id": "1134", "ParentId": "1119", "Score": "2" } }, { "body": "<pre><code>class Pool(type):\n</code></pre>\n\n<p>The defaultdict class will automatically create my list when I access it</p>\n\n<pre><code> pool = collection.defaultdict(list)\n</code></pre>\n\n<p>The python style guide suggests using the form class_ rather then clas\nIt is also not clear why you are capturing the incoming arguments as variable.\nThis being a metaclass it is going to have consistent parameters</p>\n\n<pre><code> def __new__(class_, name, bases, classdict):\n def __del__(self):\n</code></pre>\n\n<p>Since pool now automatically creates the list, we can just append to it\n Pool.pool[self.<strong>class</strong>].append(self)</p>\n\n<p>Getting rid of the variable arguments also makes this much clearer. </p>\n\n<pre><code> classdict['__del__'] = __del__\n return type.__new__(class_, name, bases, classdict)\n</code></pre>\n\n<p>args and kwargs are often used as the names for variable parameters. I recommend using them to make code clearer</p>\n\n<pre><code> def __call__(class_, *args, **kwargs):\n</code></pre>\n\n<p>Thanks to the use of defaultdict above we can make this code quite a bit cleaner. Also, this code doesn't pretend its using a functional programming language. Your code created lists by adding them together, slicing, etc. That is not a really efficient or clear way to use python.</p>\n\n<pre><code> instances = Pool.pool[class_]\n if instances:\n</code></pre>\n\n<p>There is a subtle and dangerous problem here. When you create a new instance, you pass along your parameters.\nHowever, if an instance is already created, you return that ignoring what the parameters were doing.\nThis means that you might get an object back which was created using different parameters then you just passed.\nI haven't done anything to fix that here</p>\n\n<pre><code> print('Pool.pool is not empty: return an already allocated instance')\n return instances.pop()\n else:\n print('Pool.pool is empty, allocate new instance')\n return type.__call__(class_, *args, **kwargs)\n</code></pre>\n\n<p>Your technique is to install a <code>__del__</code> method on the objects so that you can detect when they are no longer being used and keep them in your list for the next person who asks for them. the <code>__del__</code> method is invoked when the object is about to be deleted. You prevent the deletion by storing a reference to the object in your list. This is allowed but the python documentation indicates that it is not recommended.</p>\n\n<p><code>__del__</code> has a number of gotchas. If an exception is caused while running the <code>__del__</code> method it will be ignored. Additionally, it will tend to cause objects in references cycles to not be collectable. If your code is ever run on Jython/IronPython then you can't be sure that <code>__del__</code> will be called in a timely manner. For these reasons I generally avoid use of <code>__del__</code>. </p>\n\n<p>You are using a metaclass so the fact that the given object is pooled is hidden from the user. I don't really think this is a good idea. I think it is far better to be explict about something like pooling. You also lose flexibility doing it this way. You cannot create multiple pools, etc.</p>\n\n<p>The interface that I would design for this would be:</p>\n\n<pre><code>pool = Pool(Foo, 1, 2, alpha = 5) # the pool gets the arguments that will be used to construct Foo\nwith pool.get() as f1:\n # as long as I'm in the with block, I have f1, it'll be returned when I exit the block\n f1.foo()\nwith pool.get() as f2:\n f2.foo()\n with pool.get() as f3:\n f3.foo()\n\nf4 = pool.get()\nf4.foo()\npool.repool(f4)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T17:07:13.240", "Id": "2033", "Score": "0", "body": "yeah i would pooling to be transparent to the user because i thought it was a good thing. thanks to point me in right way. but i don't understand thw with usage" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T17:09:20.750", "Id": "2034", "Score": "0", "body": "\"This means that you might get an object back which was created using different parameters then you just passed\" recalling __init__ method could be help or it make pooling useless?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T17:12:11.873", "Id": "2035", "Score": "0", "body": "\"Also, this code doesn't pretend its using a functional programming language. Your code created lists by adding them together, slicing, etc. That is not a really efficient or clear way to use python.\" i thought functional python was more pythonic. thanks to point this" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T17:15:28.250", "Id": "2036", "Score": "0", "body": "@nkint, for with see: http://docs.python.org/reference/datamodel.html#context-managers basically, it allows you to provide code which is run before and after the with. That way you can write code that returns the Foo back to the pool as soon as the with block exits." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T17:17:21.563", "Id": "2037", "Score": "0", "body": "@nkint, if you recall __init__, you are probably not saving any noticeable amount of time by pooling. Why do we want to pool objects anyways? Typically, you pool objects because they are expensive to create." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T17:18:41.053", "Id": "2038", "Score": "0", "body": "@nkint, python has some influence from functional languages. In some cases functional techniques are pythonic. Basically, you should use the method that provides the most straightforward implementation. Sometimes that is functional, in this case its not." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T15:33:11.150", "Id": "1161", "ParentId": "1119", "Score": "3" } } ]
{ "AcceptedAnswerId": "1161", "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T14:23:53.130", "Id": "1119", "Score": "6", "Tags": [ "python", "design-patterns" ], "Title": "python object pool with metaclasses" }
1119
<p>This takes an array of numbers then splits it into all possible combinations of the number array of size 4 then in another array puts the leftovers. As I want to take the difference in averages of the first column and the second.</p> <pre><code>import itertools #defines the array of numbers and the two columns number = [53, 64, 68, 71, 77, 82, 85] col_one = [] col_two = [] #creates an array that holds the first four results = itertools.combinations(number,4) for x in results: col_one.append(list(x)) #attempts to go through and remove those numbers in the first array #and then add that array to col_two for i in range(len(col_one)): holder = list(number) for j in range(4): holder.remove(col_one[i][j]) col_two.append(holder) col_one_average = [] col_two_average = [] for k in col_one: col_one_average.append(sum(k)/len(k)) for l in col_two: col_two_average.append(sum(l)/len(l)) dif = [] for i in range(len(col_one_average)): dif.append(col_one_average[i] - col_two_average[i]) print dif </code></pre> <p>So for example, if I have</p> <pre><code>a = [1,2,3] </code></pre> <p>and I want to split it into an array of size 2 and 1, I get</p> <pre><code>col_one[0] = [1,2] </code></pre> <p>and</p> <pre><code>col_two[0] = [3] </code></pre> <p>then</p> <pre><code>col_one[1] = [1,3] </code></pre> <p>and</p> <pre><code>col_two[1] = [2] </code></pre> <p>After I get all those I find the average of <code>col_one[0]</code> - average of <code>col_two[0]</code>.</p> <p>I hope that makes sense. I'm trying to do this for a statistics class, so if there is a 'numpy-y' solution, I'd love to hear it.</p>
[]
[ { "body": "<p>Not using numpy or scipy, but there are several things that can be improved about your code:</p>\n\n<ul>\n<li>This is minor, but in your comments you call your lists arrays, but it in python they're called lists</li>\n<li>Variable names like <code>col_one</code> and <code>col_two</code> aren't very meaningful. Maybe you should call them <code>combinations</code> and <code>rests</code> or something like that.</li>\n<li>You should definitely refactor your code into functions</li>\n<li>You often use index-based loops where it is not necessary. Where possible you should iterate by element, not by index.</li>\n<li>You're also often setting lists to the empty list and then appending to them in a loop. It is generally more pythonic and often faster to use list comprehensions for this.</li>\n</ul>\n\n<p>If I were to write the code, I'd write something like this:</p>\n\n<pre><code>import itertools\n\ndef average(lst):\n \"\"\"Returns the average of a list or other iterable\"\"\"\n\n return sum(lst)/len(lst)\n\ndef list_difference(lst1, lst2):\n \"\"\"Returns the difference between two iterables, i.e. a list containing all\n elements of lst1 that are not in lst2\"\"\"\n\n result = list(lst1)\n for x in lst2:\n result.remove(x)\n return result\n\ndef differences(numbers, n):\n \"\"\"Returns a list containing the difference between a combination and the remaining\n elements of the list for all combinations of size n of the given list\"\"\"\n\n # Build lists containing the combinations of size n and the rests\n combinations = list(itertools.combinations(numbers, n))\n rests = [list_difference(numbers, row) for row in col_one]\n\n # Create a lists of averages of the combinations and the rests\n combination_averages = [average(k) for k in combinations]\n rest_averages = [average(k) for k in rests]\n\n # Create a list containing the differences between the averages\n # using zip to iterate both lists in parallel\n diffs = [avg1 - avg2 for avg1, avg2 in zip(combination_averages, rest_averages)]\n return diffs\n\nprint differences([53, 64, 68, 71, 77, 82, 85], 4)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T17:05:32.897", "Id": "1128", "ParentId": "1121", "Score": "5" } }, { "body": "<pre><code>import itertools\nimport numpy\n\nnumber = [53, 64, 68, 71, 77, 82, 85]\n\n\nresults = itertools.combinations(number,4)\n# convert the combination iterator into a numpy array\ncol_one = numpy.array(list(results))\n\n# calculate average of col_one\ncol_one_average = numpy.mean(col_one, axis = 1).astype(int)\n\n# I don't actually create col_two, as I never figured out a good way to do it\n# But since I only need the sum, I figure that out by subtraction\ncol_two_average = (numpy.sum(number) - numpy.sum(col_one, axis = 1)) / 3\n\ndif = col_one_average - col_two_average\n\nprint dif\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-14T17:05:13.897", "Id": "38806", "Score": "2", "body": "Using `np.fromiter(combinations(` is far faster than `np.array(list(combinations(`, (0.1 seconds vs 2 seconds, for instance) but it's also more complicated: http://numpy-discussion.10968.n7.nabble.com/itertools-combinations-to-numpy-td16635.html" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T21:28:33.287", "Id": "1140", "ParentId": "1121", "Score": "8" } } ]
{ "AcceptedAnswerId": "1140", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-03T16:05:48.193", "Id": "1121", "Score": "7", "Tags": [ "python", "array", "combinatorics" ], "Title": "Splitting an array of numbers into all possible combinations" }
1121
<p>Is there a simple way to create a comma delimited string from a list of items <strong>without</strong> adding an extra ", " to the end of the string?</p> <p>I frequently need to take an ASP.NET CheckBoxList and format the selected values as a string for insertion into an e-mail. It's straightforward to loop over the selected checkboxes, get the values, and add them to a StringBuilder with a ", " separating them, but the Count property returns the number of items in the list total, not the number of items that are actually selected. So it's hard to know when you've reached the last item, and you end up with a stray ", " on the end. </p> <p>I've played around with several different approaches to this problem. Lately I've been doing something like this:</p> <pre><code>private string ConcatenateCheckBoxListItems() { StringBuilder sb = new StringBuilder(); char[] characters = new char[] {" ", ","}; String trimmedString; foreach (ListItem item in MyList) { sb.Append(item.Value + ", "); } trimmedString = sb.ToString().TrimEnd(characters); return trimmedString; } </code></pre> <p>But it's definitely clunky. So do the various for loop approaches I've tried. Any suggestions for a cleaner implementation?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T21:25:04.690", "Id": "1995", "Score": "1", "body": "Despite the answers, in this code, your delimiter should be a string, and trim end should call `delimiter.ToCharArray()` in order to make maintenance just a tad bit easier." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T16:35:06.343", "Id": "58730", "Score": "0", "body": "Does this [built-in](http://msdn.microsoft.com/en-us/library/system.string.join.aspx) do what you want?" } ]
[ { "body": "<p>As <a href=\"https://codereview.stackexchange.com/questions/1122/comma-delimited-string-from-list-of-items/1125#1125\"><strong>pdr</strong></a> has pointed out, it's best to use <a href=\"http://msdn.microsoft.com/en-us/library/57a79xd0.aspx\" rel=\"nofollow noreferrer\"><code>String.Join</code></a>, instead of doing it yourself as I stated earlier.</p>\n\n<blockquote>\n <p>Maybe I'm missing something, but can't\n you just do the following? </p>\n\n<pre><code>private string ConcatenateCheckBoxListItems()\n{\n StringBuilder sb = new StringBuilder();\n\n for ( int i = 0; i &lt; MyList.Items.Count; ++i )\n {\n ListItem item = MyList.Items[ i ];\n sb.Append( item.Value );\n if ( i &lt; MyList.Items.Count - 1 )\n {\n sb.Append( \", \" );\n }\n }\n\n return sb.ToString();\n}\n</code></pre>\n \n <p>UPDATE:</p>\n \n <p>As a sidenote, I know it's easy to\n quickly lose the overview of the\n intent with code like this. That's why\n I've been working on an experimental\n class which allows to do the\n following.</p>\n\n<pre><code>StringBuilder sb = new StringBuilder();\nLoop loop = Loop.ForEach( MyList.Items, i =&gt; sb.Append( i.Value ) );\nloop.After.AllButLast( () =&gt; sb.Append( \", \" ) );\nloop.Run();\n</code></pre>\n \n <p>I'm still deciding whether or not I\n like this solution. :) Haven't used it\n that often.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T17:35:01.727", "Id": "1978", "Score": "0", "body": "This is similar to the other approach that I've tried. In this case, the number of items in MyList is different from the number of _selected_ items, which is what I want to work with. Otherwise I'd just be repeating the values of the entire CheckBoxList." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T17:44:34.327", "Id": "1979", "Score": "0", "body": "@JoshEarl: I don't see any check in the other samples where the non-selected items are excluded, nor in your example?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T12:58:53.597", "Id": "2021", "Score": "0", "body": "@Steven Sorry, the non-selected item issue was described in the body of my question, but I didn't include that part in my code for simplicity's sake." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T13:06:37.220", "Id": "2022", "Score": "0", "body": "@JoshEarl: no problem, but you do understand then, that the number of selected items is irrelevant? :) `Count` is always to total amount of items, selected and non-selected." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T16:32:56.660", "Id": "2030", "Score": "0", "body": "@Steven Well, it's relevant if you don't want to include the \", \" after the last selected item. If you just loop through with the count and don't have a way of knowing when you reach the last _selected_ item, you end up with a \", \" after the last item, no? That was the problem I was trying to address with the silly string trim." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T16:41:20.530", "Id": "2031", "Score": "0", "body": "@JoshEarl: I finally get it. :) The join does allow you to do this by adding the `where` clause. I believe this would result in the same as doing the for over the filtered list of selected items instead of over the total list." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T16:30:48.030", "Id": "1124", "ParentId": "1122", "Score": "1" } }, { "body": "<p>Would this not suffice?</p>\n\n<pre><code>private string ConcatenateCheckBoxListItems()\n{\n return string.Join(\", \", from item in MyList select item.Value);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T16:42:19.723", "Id": "1974", "Score": "0", "body": "Cool, how didn't I know that one. :O :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T16:46:10.587", "Id": "1975", "Score": "12", "body": "@Steven That's the thing with the .NET Framework. You can't know it all; you only know what you've had to know. And that's why sites like this exist." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T17:30:55.940", "Id": "1977", "Score": "0", "body": "I absolutely love this site. Yes, that's perfect, compact, elegant... I feel like more of a novice every day. :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T18:01:58.540", "Id": "1981", "Score": "0", "body": "Does this take care of escaping your list values from any contained ',' characters ?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T18:23:57.307", "Id": "1982", "Score": "2", "body": "@thedev No, but it could easily be extended for that. Simply change the bit after select to either replace commas `item.Value.Replace(\",\", @\"\\,\")` or surround the string in quotes `item.Value.Contains(\",\") ? string.Format(@\"\"\"{0}\"\"\", item.Value) : item.Value`. Whatever you require" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T21:33:48.623", "Id": "1996", "Score": "3", "body": "Python? In *my* C#? In all seriousness, I didn't know you could do such wizardry in C#. Great answer." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T16:35:02.877", "Id": "1125", "ParentId": "1122", "Score": "72" } }, { "body": "<p>Why not <code>string.Join()</code>?</p>\n\n<pre><code>var result = string.Join(\", \", MyList.Items.Select(i =&gt; i.Value));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-18T23:59:29.807", "Id": "192327", "Score": "2", "body": "I very much prefer to do this inline over wrapping it in a method like in the accepted answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T16:36:14.263", "Id": "1127", "ParentId": "1122", "Score": "25" } }, { "body": "<p><code>string.Join()</code> is a good answer, but I prefer to create an extension method:</p>\n\n<pre><code>namespace StringExtensions\n{\n static class _\n {\n public static string JoinString&lt;T&gt;(this IEnumerable&lt;T&gt; source, string seperator = \"\")\n {\n return string.Join(seperator, source);\n }\n }\n}\n</code></pre>\n\n<p>which is used like this:</p>\n\n<pre><code>return MyList.Select(i =&gt; i.Value).JoinString(\", \");\n</code></pre>\n\n<p>(I'm using my unconventional method of organizing extension methods, which you can read about here: <a href=\"http://jbazuzicode.blogspot.com/2009/01/way-to-manage-extension-methods-in-c.html\" rel=\"noreferrer\">http://jbazuzicode.blogspot.com/2009/01/way-to-manage-extension-methods-in-c.html</a>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T13:52:05.247", "Id": "2024", "Score": "3", "body": "I have an even more unconventional method, I put them in the corresponding `System` namespaces. :) No need to add usings. I'm still deciding whether I'm gonna [keep this practice or not](http://stackoverflow.com/q/5011623/590790)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-05T14:04:42.857", "Id": "2053", "Score": "0", "body": "I prefer the concept of stashing utility functions in extension methods. @Steven - I had never thought of placing my extension methods in a System namespace -- +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-27T20:21:36.920", "Id": "74108", "Score": "0", "body": "@StevenJeuris that thread gave me cancer" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T23:43:50.257", "Id": "1146", "ParentId": "1122", "Score": "5" } } ]
{ "AcceptedAnswerId": "1125", "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T16:20:24.897", "Id": "1122", "Score": "57", "Tags": [ "c#", "asp.net" ], "Title": "Comma delimited string from list of items" }
1122
<pre><code>$privilegeStrings = array_filter($privileges, function ($s) { return is_string($s); } ); </code></pre> <p>Is there a better way to specify that I want just the string values in the given array?</p>
[]
[ { "body": "<p>You could do:</p>\n\n<pre><code>$privilegeStrings = array_filter($privileges, 'is_string');\n</code></pre>\n\n<p><code>array_filter</code> passes every value of the array to the specified function. So you can just specify the function name and everything will be taken care of.</p>\n\n<p><a href=\"http://php.net/manual/en/function.array-filter.php\">Reference</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T20:58:45.373", "Id": "1993", "Score": "0", "body": "Ah.. didn't know you could pass the name of a function like that. Yuck!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T03:19:39.227", "Id": "2003", "Score": "2", "body": "@Billy ONeal - The name of a function is one acceptable form a [callback](http://php.net/manual/en/language.pseudo-types.php) may take." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T18:38:30.947", "Id": "1133", "ParentId": "1129", "Score": "11" } } ]
{ "AcceptedAnswerId": "1133", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T18:06:40.230", "Id": "1129", "Score": "7", "Tags": [ "php", "callback" ], "Title": "Do nothing lamda..." }
1129
<p>I've been using FlexLib for its dockable toolbar feature. When you shrink the window, it will try to wrap rows if the stage width is less than the row width. Unfortunately, it won't reverse the process when you expand the window. To get around that, I wrote the following method to add to the class (the caller is responsible for looping through all current toolbar rows and calling this method on them).</p> <p>It does the job, but it's not quite as fast as I'd like. I'm hoping for suggestions to improve both performance and code style, if possible.</p> <pre><code>/** * @private * Moves ToolBars to the previous row if there is sufficient space in that row to display * another ToolBar properly. */ private function unwrapRow(row:HBox, rowIndex:int, toolbar:VBox):void { if (rowIndex == 0) { return; } var prevRow:HBox = HBox(toolbar.getChildAt(rowIndex-1)); var prevRowW:int = 0; var totalW:int = 0; //First, get the width of the previous row for (var j:int = 0; j &lt; prevRow.numChildren; j++) { var ch:DockableToolBar = DockableToolBar(prevRow.getChildAt(j)); prevRowW += ch.measuredWidth; } //Second, cycle through the children of the "row of interest", moving them //up to the previous row if there's room. for (var k:int = 0; k &lt; row.numChildren; k++) { var child:DockableToolBar = DockableToolBar(row.getChildAt(k)); if ((prevRowW + child.measuredWidth) &gt;= toolbar.width) { break; } //Move child. child.parent.removeChild(child); prevRow.addChild(child); prevRowW += child.measuredWidth; --k; } if (row.numChildren == 0) { toolbar.removeChild(row); } } </code></pre> <p>You can see the rest of this class <a href="http://code.google.com/p/flexlib/source/browse/trunk/src/flexlib/containers/Docker.as" rel="nofollow">here</a> (that listing doesn't include my code; I plan to submit this as a patch once it's in good enough shape).</p>
[]
[ { "body": "<p>I have one little suggestion with regard to style. It is much better to invert your conditions to have the simpler code run first when it involves yielding control. It also helps you avoid excessive indentation. </p>\n\n<pre><code>var child:DockableToolBar = DockableToolBar(row.getChildAt(k));\n\n//Skip the rest of the row if we can't move the first child up.\nif (prevRowW + child.measuredWidth &gt;= toolbar.width) {\n break;\n}\n\n//Move child.\nchild.parent.removeChild(child);\nprevRow.addChild(child);\nprevRowW += child.measuredWidth;\n--k;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T18:41:51.487", "Id": "1135", "ParentId": "1132", "Score": "5" } } ]
{ "AcceptedAnswerId": "1135", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-03T18:31:46.363", "Id": "1132", "Score": "4", "Tags": [ "actionscript-3", "actionscript", "flex" ], "Title": "Getting better speed from adjusting rows in a DockableToolBar" }
1132
<p>I often see this for custom events:</p> <pre><code>void InvokeCustomEvent(EventArgs e) { var handler = CustomEvent; if (handler != null) handler(this, e); } </code></pre> <p>But is creating the handler variable required, best practice, or superfluous, when compared to:</p> <pre><code>void InvokeCustomEvent(EventArgs e) { if (CustomEvent != null) CustomEvent(this, e); } </code></pre> <p>?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T09:19:34.847", "Id": "2004", "Score": "0", "body": "IMO, it should be moved to StackOverflow, though I believe this question is already present there." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T11:57:40.573", "Id": "2007", "Score": "0", "body": "@Snowbear: Yep, there's [this one](http://stackoverflow.com/questions/672638/use-of-null-check-in-event-handler). I should have checked..." } ]
[ { "body": "<blockquote>\n <p>But is creating the handler variable required, best practice, or superfluous, when compared to:</p>\n</blockquote>\n\n<p>Yes, it is needed. Otherwise, <code>CustomEvent</code> could be set to <code>null</code> after you've checked for <code>null</code>, but before you've invoked it. This can happen if it gets set in another thread, or if one of the event handlers unregisters itself or another one.</p>\n\n<p>I usually have this declared somewhere in my codebase:</p>\n\n<pre><code>public static class EventExtensions\n{\n public static void Raise&lt;T&gt;(this EventHandler&lt;T&gt; handler, T args) {\n if (handler != null) handler(args);\n }\n}\n</code></pre>\n\n<p>Now, with any event handler, you can just do:</p>\n\n<pre><code>handler.Raise(args);\n</code></pre>\n\n<p>You can call an extension method with a <code>null</code> this, so it will do the right thing even if <code>handler</code> is <code>null</code>. Furthermore, by copying <code>handler</code> into the local variable used by <code>Raise</code>, you automatically get the copy you need to make sure the handler won't disappear under you. Works like a charm.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T23:36:16.830", "Id": "2000", "Score": "1", "body": "Too bad the inventers of C# didn't simply make that the default behavior for invoking an event. Mind boggling to me that they didn't, since invoking an event with no subscribers should be a perfectly legitimate \"do nothing\" operation." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T01:45:54.253", "Id": "2001", "Score": "1", "body": "There is no concept of \"an event with no subscribers\". When you create an object that has some `event` fields, they will be `null` to begin with. When you register the first handler with `myObj.SomeEvent += SomeHandler`, that `+=` is creating a new EventHandler object from scratch. This way an object doesn't pay a price for instantiating empty EventHandlers on creation if it never uses them. Does make them a bit uglier to use though. :(" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T03:04:22.723", "Id": "2002", "Score": "1", "body": "My initial (and maybe a bit naive) belief was pretty much like what @supercat wants, that the event at least registered \"transparently\" a base, \"do nothing\" operation." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T23:42:51.473", "Id": "2046", "Score": "1", "body": "@MPelletier: That might be nice, but that means you'd have to create the EventHandler to begin with. Imagine you have a class with fifty events on it. When you instantiate that class, it won't waste any time touching them. They'll just all be `null` fields. The first time you register a handler on one of them using `+=`, it will get created. That way you don't pay the price of constructing a bunch of unused `EventHandlers` every time you create an object. What you propose might be a better idea, but you'd lose that performance advantage." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T21:17:06.353", "Id": "45013", "Score": "0", "body": "Seems I can't call this extension method on more specific kinds of `EventHandler<T>` like `PropertyChangedEventHandler`. This makes it not so useful I think." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T23:13:36.620", "Id": "1143", "ParentId": "1142", "Score": "15" } }, { "body": "<p>You actually don't need the null check at all if you use the following trick. Simply create a default, empty handler that is always registered, so the event is guaranteed to never be null.</p>\n\n<p>Declare your event like so (notice the <code>= delegate { }</code> bit)</p>\n\n<pre><code>public event EventHandler CustomEvent = delegate { };\n</code></pre>\n\n<p>And you can then invoke it without any null checks.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-05T03:19:27.583", "Id": "2050", "Score": "0", "body": "I like this answer (and choosing was truly heart-breaking) for its simplicity. I'd rather do this in cases of a very light structure, and not, as suggested above, dozens of events in many instances of the same class." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T23:55:17.750", "Id": "1147", "ParentId": "1142", "Score": "8" } } ]
{ "AcceptedAnswerId": "1143", "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-03T23:03:22.930", "Id": "1142", "Score": "8", "Tags": [ "c#" ], "Title": "Checking if an event is not null before firing it in C#" }
1142
<p>In answering a question on SO, I provided this example. The intention was to provide a thread safe service that queues requests to make directories. I figured I could definitely use some review on my use of threading, singletons and general Java skills. </p> <pre><code>package mkdir; import java.io.File; import java.util.concurrent.ConcurrentLinkedQueue; public class MkDirService implements Runnable { private static MkDirService service; private static ConcurrentLinkedQueue&lt;File&gt; pendingDirs; private MkDirService() { pendingDirs = new ConcurrentLinkedQueue&lt;File&gt;(); } public static MkDirService getService() { if (service == null) { service = new MkDirService(); new Thread(service).start(); } return service; } public void makeDir(File dir) { pendingDirs.add(dir); } @Override public void run() { while (true) { while (!pendingDirs.isEmpty()) { File curDir = pendingDirs.poll(); if (curDir !=null &amp;&amp; !curDir.exists()) { curDir.mkdir(); } } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } </code></pre>
[]
[ { "body": "<p><code>pendingDirs</code> should not be static. It's one thing to maintain a static instance to implement a singleton, but that object should interact with its state using normal instance variables. And you may as well initialize it in its declaration instead of the constructor.</p>\n\n<p>The service should create the thread itself instead of creating it in <code>getService()</code> to make it self-contained. This allows another implementation to use a thread pool for parallel directory creation and easier testing.</p>\n\n<p><code>getService()</code> is not thread-safe and could allow two or more instances to be created.</p>\n\n<p>Use a <a href=\"http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html\" rel=\"nofollow\">blocking queue</a>, so you don't have to poll and sleep. The thread will be put to sleep if the queue is empty and be awoken once a new directory is added to the queue. This will shrink your run loop to a few lines and allow you to rely on the well-tested thread-management in <code>java.util.concurrent</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T14:25:01.353", "Id": "2027", "Score": "0", "body": "You mean the service using MkDirService should create the Thread? That makes sense to me. Thanks for great feedback." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T14:35:31.270", "Id": "2028", "Score": "0", "body": "One of the requirements that I didn't mention, is that there should never be more than 1 thread of this service. This is to prevent conflicts. The idea behind designing this service was to give a multi-threaded application a centralized way of creating directories that could avoid conflicts. In this case would letting getService() create the thread and start it, make sense?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T19:15:56.557", "Id": "2040", "Score": "0", "body": "@bconneen - I meant to have the constructor of `MkDirService` create and start the thread so it's entirely self-contained. In fact, it should have `start()` and `stop()` methods where `stop()` a) blocks all further `makeDir()` calls and b) sets a flag which `run()` uses to exit once the queue is drained. That might be overkill for your requirements, but that's how you would allow a graceful shutdown of the service." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T07:44:32.383", "Id": "1153", "ParentId": "1150", "Score": "2" } }, { "body": "<p>Also to create even one thread it is recommended to use concurrent package:\nExecutors.newSingleThreadExecutor().submit(new MkDirService());</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T18:49:49.143", "Id": "1163", "ParentId": "1150", "Score": "2" } } ]
{ "AcceptedAnswerId": "1153", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T05:37:50.993", "Id": "1150", "Score": "5", "Tags": [ "java", "thread-safety" ], "Title": "Thread Safe Service to Perform Tasks in a Queue" }
1150
<p>I have the following code:</p> <pre><code>private ScatterViewItem FindScatterViewOfSourceFile(SourceFile find) { foreach (ScatterViewItem svi in classScatterViews) { if ((svi.Tag as SourceFile).Equals(find)) { return svi; } } return null; } </code></pre> <p>Now I'm asking myself if this is valid or if I should better use:</p> <pre><code>private ScatterViewItem FindScatterViewOfSourceFile(SourceFile find) { ScatterViewItem result = null; foreach (ScatterViewItem svi in classScatterViews) { if ((svi.Tag as SourceFile).Equals(find)) { result = svi; break; } } return result; } </code></pre> <p>Is there any common practive which one to use? And are both loops doing the same?</p>
[]
[ { "body": "<p>So you have heard about the good practice that a method should only have one return statement.\nThis is generally true, but in your case I find it not to be necessary because the method is so small. The main reason for this 'rule' is readability, so you know what is going on. Both code samples are equally clear. When you have several places where a <code>return</code> would occur, it's best to use the second approach.</p>\n\n<p>However, I would rewrite it by using LINQ. I believe this should work:</p>\n\n<pre><code>private ScatterViewItem FindScatterViewOfSourceFile(SourceFile find)\n{\n return classScatterViews.FirstOrDefault( svi =&gt; svi.Tag.Equals(find) );\n}\n</code></pre>\n\n<p>UPDATE:</p>\n\n<p>Also note that the cast to the specific type to call the <code>Equals()</code> is dropped. This is redundant as the correct Equals() will be called anyhow.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T12:28:45.427", "Id": "2008", "Score": "0", "body": "[nitpick] It will be called *only* if `ScatterViewItems` implemented in obvious way" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T12:34:31.273", "Id": "2010", "Score": "0", "body": "@Snowbear: I can't think of the nonobvious way right now, perhaps I'm missing something. :O Enlighten me. ;p" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T12:37:04.593", "Id": "2012", "Score": "2", "body": "`public new bool Equals(object other)` in `SourceFile` ;-)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T12:48:56.800", "Id": "2016", "Score": "0", "body": "Ugh!, ... thanks for me reminding me why I never use `new`. ;p" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T13:58:24.260", "Id": "2025", "Score": "0", "body": "Exactly, though I believe on `code review` site we should discuss only your version because such `new Equals` will never pass good review." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T14:00:24.430", "Id": "2026", "Score": "0", "body": "@Snowbear: Just update your answer accordingly. ;p" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T23:47:52.683", "Id": "2047", "Score": "1", "body": "\"The main reason for this 'rule' is readability, so you know what is going on.\" That's simply not true. This rule was created for languages like C that don't automatically manage resources. Returning early from a function that may have allocated early makes it too easy to forget to deallocate it. In a GC language like C#, there's no need for this rule." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-06T07:10:56.720", "Id": "2069", "Score": "0", "body": "@munificent: Agreed, most likely that rule lessens readability as it forces a lot of nesting." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-06T16:29:19.403", "Id": "2071", "Score": "1", "body": "@munificent: Thanks for the history lesson, I didn't know that. However, I can give you examples where multiple return statements ARE less readable. Also the fact that there are other reasons doesn't exclude the fact that it also is a practice known to improve readability. I'll rephrase, the [only reason I knew of](http://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement). ;p" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T11:57:44.817", "Id": "1157", "ParentId": "1156", "Score": "9" } }, { "body": "<p>First one is hundred times better then the second one. I would avoid defining a variable if you don't really need to. Also I don't believe in <code>one return</code> methods. Especially I don't believe that they improve readability. </p>\n\n<p>LINQ would definitely improve it: </p>\n\n<pre><code>return classScatterViews.FirstOrDefault(v =&gt; v.Tag.Equals(find));\n</code></pre>\n\n<p>Also I would not use <code>as</code> operator if I do not check result for <code>null</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T12:03:06.917", "Id": "1158", "ParentId": "1156", "Score": "22" } } ]
{ "AcceptedAnswerId": "1158", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-04T11:46:01.330", "Id": "1156", "Score": "10", "Tags": [ "c#", "algorithm" ], "Title": "Is this a valid loop?" }
1156
<p>I'm currently creating an <a href="http://oauth.net/core/1.0a/" rel="nofollow noreferrer">OAuth</a> provider in Java using <a href="http://jersey.java.net/" rel="nofollow noreferrer">Jersey</a>. To the best of my knowledge Jersey does not provide a method to create oauth tokens so I'm creating my own.</p> <p>For those unfamiliar with OAuth, the tokens will be used in a somewhat similar fashion to public/private keys to sign and verify all requests to the server.</p> <p>A <code>String</code> is formed using a token issued by the server (me) and then encrypted with that token secret (which only the server and the application know). The signature is then sent to the server and verified.</p> <p>Each token must be:</p> <ul> <li>non-sequential</li> <li>non-guessable</li> <li>unique (the tokens will be stored in a database so uniqueness can be verified)</li> </ul> <p>This is the code I'm thinking of using to generate the keys:</p> <pre><code>public String generateToken() { SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); MessageDigest digest = MessageDigest.getInstance("SHA-256"); secureRandom.setSeed(secureRandom.generateSeed(128)); return new String(digest.digest((secureRandom.nextLong() + "").getBytes())); } </code></pre> <p>I'm generating a <code>Long</code> using Java's SecureRandom with SHA-1-PRNG. Using a 128 bit seed again generated by SecureRandom.</p> <p>I'm then using SHA-256 to hash the resulting <code>Long</code> to get a 32 character Unicode String as the token.</p> <ul> <li>Is anyone able to see any issues with this style of token generation?</li> <li>If multiple tokens were requested in a row, is there a chance of predicting the next one?</li> <li>I assume that 32 characters is more than enough for this kind of request signing.</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-07T21:21:42.403", "Id": "31079", "Score": "0", "body": "I realize this is quite old, but any reason you wouldn't want to use `java.security.KeyPairGenerator` and generate, for example an _RSA key pair_ and use those?" } ]
[ { "body": "<blockquote>\n <p>Each token must be;</p>\n \n <ul>\n <li>non-sequential</li>\n <li>non-guessable</li>\n <li>unique</li>\n </ul>\n</blockquote>\n\n<p>Without reading into any of the OAuth specifics, if the above is the only criteria to which you must adhere, then I would suggest what you're doing is quite a huge effort to achieve what's already been done with <a href=\"http://en.wikipedia.org/wiki/Globally_unique_identifier\">GUID (Globally Unique Identifier)</a>.</p>\n\n<p>Java has an implementation of this, a <a href=\"http://download.oracle.com/javase/1.5.0/docs/api/java/util/UUID.html\">class named UUID</a>:</p>\n\n<blockquote>\n <p>...that represents an immutable\n universally unique identifier (UUID).\n A UUID represents a 128-bit value.</p>\n</blockquote>\n\n<p>Conveniently, a GUID is also a 32 character string.</p>\n\n<p>Some <a href=\"http://www.kodejava.org/examples/486.html\">code I found</a> to utilise this using Java:</p>\n\n<pre><code>UUID uuid = UUID.randomUUID();\nString randomUUIDString = uuid.toString();\n</code></pre>\n\n<p>Note that I'm not really qualified to be an authority on this where Java is concerned, though the topic I'm concerning myself with here is very transferable, you will need to determine whether A) a GUID satisfies all criteria of an OAuth token, and B) that the Java implementation works as the rest of the world expects - I can't vouch for that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-09T07:32:43.060", "Id": "3036", "Score": "0", "body": "That looks like it fits what I need :) Thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-04-08T18:20:03.790", "Id": "1737", "ParentId": "1159", "Score": "14" } } ]
{ "AcceptedAnswerId": "1737", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-04T12:27:51.577", "Id": "1159", "Score": "14", "Tags": [ "java", "random", "oauth", "jersey" ], "Title": "OAuth Provider token generation" }
1159
<p>I'm using <em>Entity Framework Code First CTP 5</em> for a current project. There is still no enum support in Entity Framework so this is what I am using in order to avoid having magic numbers or casts littered throughout my code.</p> <p>Simplified Example:</p> <p><strong>Domain Model Consumed by Code First</strong></p> <pre><code>public class Address { // This would normally be an enum public int Type { get; set; } } </code></pre> <p><strong>Repository</strong></p> <pre><code>public class AddressRepository { public Add(Address address) { // Compare using enum semantics if (address.Type == AddressType.Home) // Do something context.Add(address); } } </code></pre> <p><strong>View Model</strong></p> <pre><code>public class AddressVM { // Using the AddressType class for the view model public AddressType Type { get; set; } public AddressVM(Address address) { this.Type = address.Type; } } </code></pre> <p><strong>Enum Replacement Class</strong></p> <pre><code>public interface IEnumClass { List&lt;string&gt; Properties { get; } } public class AddressType : IEnumClass { public static int Home { get { return 0; } } public static int Work { get { return 1; } } public List&lt;string&gt; Properties { get { return properties; } } private List&lt;string&gt; properties; private int id; public AddressType() { SetProperties(); } public AddressType(int id) { this.id = id; SetProperties(); } private void SetProperties() { properties = this.GetType().GetProperties(BindingFlags.Public|BindingFlags.Static) .Select(x =&gt; x.Name).ToList(); } public static implicit operator AddressType(int id) { return new AddressType(id); } public static implicit operator String(AddressType addressType) { return addressType.properties[addressType.id]; } public static implicit operator int(AddressType addressType) { return addressType.id; } } </code></pre> <p><strong>My Personal Assessment</strong></p> <p>Pros:</p> <ul> <li>Allows me to write business rules without using magic numbers</li> <li>Uses the same semantics/syntax as enums for easy refactoring down the road</li> <li>Allows for an implicit conversion to a string for the view model</li> <li>My select list factory class can easily be made to accept any <code>IEnumClass</code> and generate a select list for the view model</li> </ul> <p>Cons:</p> <ul> <li>A little verbose</li> <li>As far as I can tell it is impossible to use a nice abstract generic class because all the actual work uses implicit type casting</li> </ul> <p>I'm asking for feedback here because I'm a total novice programmer so I want to solicit some critiques before implementing something I just came up with!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T17:36:06.577", "Id": "53733", "Score": "0", "body": "I second Saeed's approach. Implementations here also might be of interest: [C# String Enums](http://stackoverflow.com/questions/424366/c-string-enums/4881040#4881040)" } ]
[ { "body": "<p>I think the biggest drawback to your approach is that you're adding complexity but not really getting the main benefit you're after, which is to avoid magic numbers. This code doesn't prevent you from using magic numbers since it automatically converts from any <code>int</code> to an <code>AddressType</code>, and it still exposes its values as an <code>int</code>. So I would suggest one of the following two approaches. The first one is very simple but seems to give the same benefits as your code. The second one is more along the lines of what you're after, so there's some complexity, but has some added benefits as well.</p>\n\n<p><strong>Simple solution</strong></p>\n\n<p>I think the simplest thing would be to just have a static class with constants defined in it, like so:</p>\n\n<pre><code>public static class AddressType\n{\n public const int Home = 1;\n public const int Work = 2;\n}\n</code></pre>\n\n<p>(Note: as with any enum, 0 should not be a valid value)</p>\n\n<p>You would then store your values as <code>int</code> on your entities, but always compare them against these constants. This would give you the same usage pattern as you showed in your question.</p>\n\n<p><strong>More complicated solution</strong></p>\n\n<p>Alternatively, if you want to go with your approach, you should restrict it to only allow you to instantiate an <code>AddressType</code> with known values, which will prevent the use of magic numbers and make it more strongly typed than using a plain <code>int</code>.</p>\n\n<p>So for example, something like the following:</p>\n\n<pre><code>public class AddressType\n{\n public static readonly AddressType Home = new AddressType(1);\n public static readonly AddressType Work = new AddressType(2);\n\n private int value;\n\n private AddressType(int value)\n {\n this.value = value;\n }\n\n public override bool Equals(object obj)\n {\n AddressType rhs = obj as AddressType;\n return\n rhs != null &amp;&amp;\n this.value == rhs.value;\n }\n\n public override int GetHashCode()\n {\n return this.value.GetHashCode();\n }\n}\n</code></pre>\n\n<p>In your model, you would use it like so:</p>\n\n<pre><code>public class Address\n{\n public AddressType AddressType { get; set; }\n}\n</code></pre>\n\n<p>Now assigning and comparing these <code>AddressType</code> values looks just like an enum, but explicitly prevents you from using any magic numbers. If you really need it, you can also add conversions to/from <code>int</code>, but only allow it if they are known values.</p>\n\n<p>You could use something like the following, though if you have more than 2 values you'll probably want to use a dictionary to map from <code>int</code> to <code>AddressType</code>:</p>\n\n<pre><code>public static implicit operator AddressType(int value)\n{\n if (value == AddressType.Home.value)\n {\n return AddressType.Home;\n }\n else if (value == AddressType.Work.value)\n {\n return AddressType.Work;\n }\n\n throw new InvalidCastException();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-06T19:59:02.383", "Id": "2072", "Score": "0", "body": "Thanks for the suggestions! I'll definitely put some logic in there to make sure any int passed in are valid." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-05T01:23:39.497", "Id": "1166", "ParentId": "1162", "Score": "5" } }, { "body": "<p>I keep seeing all these really complex solutions to the lack of enum support, but most make things tricky when taking into account that next entity framework release is probably going to have enum support.</p>\n\n<p>Here's my solution. A sample class, <em>before</em> our workaround:</p>\n\n<pre><code>public class Widget\n{\n public int ID { get; set; }\n public Status Status { get; set; }\n}\n</code></pre>\n\n<p>Obviously <code>Status</code> won't be saved as it's an enum, and if we provide a fancy workaround, things will probably break when we upgrade to the next entity framework release, as it'll suddenly start trying to read and write that property. So we do the following:</p>\n\n<pre><code>public class Widget\n{\n public int ID { get; set; }\n [NotMapped] // stop future entity frameworks from accidentally using this column\n public Status Status { get; set; }\n\n [Column(\"Status\")]\n private int StatusEnum\n {\n get { return (int)Status; }\n set { Status = (Status)value; }\n }\n}\n</code></pre>\n\n<p>The new property is private so we can't see it externally, so it doesn't exist to the outside world for all intents and purposes. The entity framework can see it as you've marked it with a [Column] attribute and so it'll be found via reflection. The original enum column will be skipped even if we upgrade to a later version of the framework, and then all we have to do is remove those few lines of workaround code and things should still work seamlessly.</p>\n\n<p>The result?</p>\n\n<ul>\n<li>The class looks the same to anything consuming it, but now enums are saved and loaded</li>\n<li>No additional code complexity</li>\n<li>Future-proofed against entity framework upgrades</li>\n<li>Super easy to remove the additional code when upgrading to a version of the framework that supports enum persistence</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-11T16:33:49.090", "Id": "2367", "ParentId": "1162", "Score": "10" } } ]
{ "AcceptedAnswerId": "1166", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-04T17:20:48.717", "Id": "1162", "Score": "15", "Tags": [ "c#", "beginner", "entity-framework" ], "Title": "Dealing with Entity Framework's lack of enum support" }
1162
<p>I've been spending a long time working on this template, I'd like to know if its CSS/HTML is good, and mainly if it is speedy to load, accessible, semantic and SEO friendly.</p> <p>I've tested it in IE7+, Chrome, FF and Safari and am happy with the output in each.</p> <p><a href="http://69.24.73.172/demos/newDemo" rel="nofollow">Working URL</a></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>/* Main Layout Elements */ body{ margin: 0; padding: 0; font-family: Arial, Helvetica, Verdana; background: #EAFDE6 url(../images/background.png) repeat-x; color:#444; } label{ cursor: pointer; } p { margin: 0 0 20px 8px; position:relative; } .news-wrapper p { margin: 0 0 10px 8px; } a{ color: #1B676B; } .time-ago{ float:right; color: #1B676B; } .top-bar{ position:absolute; top:0; left:0; background-color: #519548; height: 30px; border-bottom:2px solid #3E7236; width: 100%; z-index:1; } h1{ margin:0; margin-bottom:5px; font-size:35px; color: #519548; font-weight:normal; } h2{ margin:0; margin-bottom:5px; font-size:35px; color: #519548; font-weight:normal; } h3{ margin:0 0 5px 0; font-size:22px; color: #519548; font-weight:normal; } h3 a { color: #519548; text-decoration:underline; } h3 a:hover { color: #1B676B; text-decoration:none; } h4{ text-shadow: black 0.1em 0.1em 0.2em; text-transform: uppercase; font-size: 17px; font-weight: bold; margin-bottom: 3px; margin-top: 30px; } a.ralign{ text-align:right; display: block; } .clear{ clear:both; } /* Sprite definitions and positioning */ .s{ background-image:url(../images/sprites.png); background-repeat:no-repeat; } .facebook{ background-position: 0 0; } .twitter{ background-position: 0 -40px; } .slideshow-wrapper{ height:261px; overflow:hidden; -moz-box-shadow: 0px 0px 5px #555; -webkit-box-shadow: 0px 0px 5px #555; box-shadow: 0px 0px 5px #555; } .youtube{ background-position: 0 -80px; } /* Main Wrappers */ .content-wrapper{ width:750px; margin: 0 auto; } .head-wrapper{ height: 120px; padding-left:11px; } .footer-wrapper{ position:relative; z-index:1; top: -35px; height:155px; background-image: url(../images/background-footer.png); background-repeat:repeat-x; margin-bottom: -35px; overflow: hidden; } .main-wrapper{ margin: 0 auto; width: 792px; background-image: url(../images/mainbox-background.png); z-index:2; position:relative; padding: 0 0 0px 0; } .main-end{ width: 786px; background-image: url(../images/mainbox-background-bottom.png); background-color:transparent; height:32px; position:relative; z-index:2; margin: 0 auto; padding:0; } /* Footer */ .footer-inner-wrapper { color: white; font-size: 13px; margin: 0 auto; width: 700px; margin-top:5px; } .footer-item{ float: left; width: 33%; } .footer-item ul{ list-style-type: none; margin: 0; padding: 0; } .footer-item p{ padding: 0; margin: 0; } .footer-item a{ font-size:13px; color:white; } .footer-item a:hover{ color: #ffaa00; } .copyright { color: #9FCAD5; text-align:center; background-color: #2A525A; background-image: url(../images/copyright-background.png); font-size: 14px; line-height:35px; height:35px; text-shadow: 0px 1px 1px #2A525A; } .social-icon{ height: 40px; width: 32px; float: left; margin-top: 7px; position:relative; left: -4px; display:block; } /* Search */ .search-wrapper{ background-position: -46px -70px; width: 259px; height:62px; position:absolute; right: -50px; top: 0; text-align:center; line-height:50px; } .search-wrapper input{ height:24px; padding-left:15px; color: #c0c0c0; line-height:24px; padding-right:25px; border: 0; position:absolute; top: 15px; left:30px; } .search-icon{ height: 37px; width: 36px; background-position: -40px 0; position:absolute; left:205px; top:13px; } /* Menus */ .menu-main{ height:38px; background-color: #88C425; font-size: 15px; font-weight: bold; line-height:38px; margin:0; padding: 0; padding-left: 20px; } .menu-wrapper{ width: 770px; padding-left:11px; margin-bottom:10px; } .menu-main li{ margin: 0; list-style-type: none; float:left; } .menu-main a{ text-shadow: #114400 1px 1px 1px; display: block; padding-left: 20px; padding-right: 20px; color:white; text-decoration: none; } .menu-main a:hover{ background-color:#3E7236; } a.main-item-selected{ background-color:#519548; } .main-item-selected a:hover{ background-color:#519548 !important; /* Stupid firefox bug */ } .mainSelLPan{ float:left; width:11px; height:33px; background-position: -105px 0; margin-left: -11px; } .mainSelPos{ position:relative; top: 5px; } .mainSelRPan{ float:left; width:11px; height:33px; background-repeat:no-repeat; background-position: -116px 0; margin-right: -11px; } .mainSelTxt{ float:left; background-color:#519548; height:33px; line-height:33px; } .sub-menu{ height: 33px; background-color: #519548; font-size: 13px; line-height:33px; margin: 0; padding: 0; padding-left:20px; } .sub-menu li{ margin: 0; list-style-type: none; float:left; } .sub-menu a{ display: block; padding-left: 20px; padding-right: 20px; color:white; text-decoration: none; } a.sub-item-selected{ background-color:#3E7236; color: white !important; } .sub-menu a:hover{ background-color:#3E7236; } .underSelLPan{ float:left; width:11px; height:33px; background-position: -78px 0; margin-left: -11px; } .underSelPos{ position:relative; top: 6px; } .underSelRPan{ float:left; width:11px; height:23px; background-repeat:no-repeat; background-position: -91px 0; margin-right: -11px; } .underSelTxt{ float:left; background-color:#3E7236; height:22px; line-height:22px; } /* Download box link */ .download{ display: block; background-position: -134px 0; width: 215px; height: 55px; margin: 0 auto; text-align:right; color:white; text-transform: uppercase; text-decoration: none; } .download-title{ font-weight:bold; font-size:17px; padding-top:14px; padding-right: 15px; } .download-size{ padding-right: 15px; font-size:14px; margin-top: -3px; } /* Other */ .moreInfoLink{ display:block; color:white; font-size:12px; font-weight:bold; text-decoration: none; float:right; height:17px; background-color:#1B676B; text-align:center; padding:0 12px 0 12px; line-height:17px; min-width:100px; -moz-border-radius: 10px; border-radius: 10px; position:absolute; bottom: 0; right: 0; } .moreInfoLink:hover{ text-decoration:underline; background-color: #23868B; } .column-thin{ float:left; width:270px; } .column-wide{ float:left; margin-right:10px; width:470px; } .news-wrapper{ position:relative; top: -25px; margin-bottom:-25px; } .column-half{ float:left; width:48%; position:relative; } .r{ float:right; } .spotlight{ float:left; margin-right:15px; width: 90px; height: 90px; position:relative; } .spotlight img{ position:absolute; } .slideshow-wrapper img{ width:470px; height: 261px; border: 0; } .slideshow-wrapper a{ text-decoration: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8" /&gt; &lt;title&gt;Make Games with Scirra Software&lt;/title&gt; &lt;meta name="description" content="Game making with Construct." /&gt; &lt;meta name="keywords" content="game maker, game builder, html5, create games, games creator" /&gt; &lt;link rel="stylesheet" href="css/default.css" /&gt; &lt;link rel="stylesheet" href="plugins/coin-slider/coin-slider-styles.css" /&gt; &lt;link rel="shortcut icon" href="images/favicon.ico" /&gt; &lt;link rel="apple-touch-icon" href="images/favicon_apple.png" /&gt; &lt;script src="js/googleAnalytics.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="top-bar"&gt;&lt;/div&gt; &lt;div class="main-wrapper"&gt; &lt;header&gt; &lt;div class="head-wrapper"&gt; &lt;div class="s search-wrapper"&gt; &lt;input type="text" name="SearchBox" id="SearchBox" tabindex="1" /&gt; &lt;div class="s search-icon" title="Search Scirra"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- Logo placeholder --&gt; &lt;/div&gt; &lt;div class="menu-wrapper"&gt; &lt;nav&gt; &lt;ul class="menu-main"&gt; &lt;li&gt;&lt;a href="#" class="main-item-selected"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Forum&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Construct&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Arcade&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Manual&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul class="sub-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Homepage&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="sub-item-selected"&gt;Construct&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Products&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Community Forum&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Contact Us&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; &lt;/header&gt; &lt;div class="content-wrapper"&gt; &lt;div class="column-wide"&gt; &lt;div id="coin-slider" class="slideshow-wrapper"&gt; &lt;a href="#" title="Features for making your games" target="_blank"&gt; &lt;img src="images/screenshot1.jpg" alt="Features to help you make your games" /&gt; &lt;span&gt; Packed with hundreds of exciting features &lt;/span&gt; &lt;/a&gt; &lt;a href="#" title="Functional and intuitive games editor"&gt; &lt;img src="images/screenshot2.jpg" alt="Games editing has never been easier" /&gt; &lt;span&gt; Construct's intuitive editor means it's never been easier to create &lt;/span&gt; &lt;/a&gt; &lt;a href="#" title="High performance optimised games"&gt; &lt;img src="images/screenshot3.jpg" alt="Screenshot" alt="Optimised for performance" /&gt; &lt;span&gt; Squeeze every drop of performance from your platforms &lt;/span&gt; &lt;/a&gt; &lt;a href="#" title="Professional and stunning game making"&gt; &lt;img src="images/screenshot4.jpg" alt="Make stunning professionally finished games" /&gt; &lt;span&gt; Design stunning and professionally finished games &lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="news-wrapper"&gt; &lt;h2&gt;Latest from Scirra&lt;/h2&gt; &lt;section&gt; &lt;h3&gt;New from our &lt;a href="http://twitter.com/Scirra" title="Construct game making on Twitter"&gt;Twitter&lt;/a&gt; feed&lt;/h3&gt; &lt;p&gt;The news on the block is this. Something has happened some news or something. &lt;span class="time-ago"&gt;About 1 hour ago&lt;/span&gt;&lt;/p&gt; &lt;p&gt;Another thing has happened lets tell the world some news or something. Lots to think about. Lots to do.&lt;span class="time-ago"&gt;About 6 hours ago&lt;/span&gt;&lt;/p&gt; &lt;/section&gt; &lt;section&gt; &lt;h3&gt;Scirra's &lt;a href="#" title="Developement blog"&gt;Developer Blog&lt;/a&gt;&lt;/h3&gt; &lt;p&gt;Tom describes why he thinks Adobe Flash is on the out, and HTML5 is going to take over the web.&lt;span class="time-ago"&gt;About 1 day ago&lt;/span&gt;&lt;/p&gt; &lt;/section&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="column-thin"&gt; &lt;h1&gt;Make Games&lt;/h1&gt; &lt;p&gt;Game making has never been easier with &lt;a href="#" title="Make games with Construct"&gt;Construct&lt;/a&gt;. Design unique worlds where only your imagination is the limit. Want to get more involved? Visit our &lt;a href="#" title="Plugins for Construct"&gt;plugin library&lt;/a&gt;, and throw yourself into our active &lt;a href="#" title="Visit the helpful Scirra community"&gt;community&lt;/a&gt;&lt;/p&gt; &lt;h3&gt;Export in Multiple Formats&lt;/h3&gt; &lt;p&gt;The &lt;a href="#" title="Alternative to Flash"&gt;HTML5 Exporter&lt;/a&gt; allows you to export your games to a web page, a truly multi platform solution. With an &lt;a href="#" "Construct executable exporter"&gt;EXE Exporter&lt;/a&gt; and &lt;a href="#" title="Construct mobile phone exporter"&gt;Mobile Exporters&lt;/a&gt; planned you will soon be able to save your games for the mobile and desktop platforms. &lt;a class="moreInfoLink" href="#" title="Exporting your games"&gt;Learn More&lt;/a&gt;&lt;/p&gt; &lt;h3&gt;Packed with Features&lt;/h3&gt; &lt;p&gt;Hundreds of exciting &lt;a href="#" title="Features of game making in Construct"&gt;features&lt;/a&gt;, designed to aid you in every way as you make your games and develop your projects. Get involved today.&lt;/p&gt; &lt;a href="#" class="s download" title="Download Construct 2 Now"&gt; &lt;div class="download-title"&gt;Download&lt;/div&gt; &lt;div class="download-size"&gt;24.5 MB&lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;section&gt; &lt;h2&gt;This Weeks Spotlight&lt;/h2&gt; &lt;div class="column-half"&gt; &lt;div class="spotlight"&gt;&lt;img src="images/spotlight1.png" alt="Spotlight member" /&gt;&lt;img src="images/spotlight-mask.png" alt="Mask" /&gt;&lt;/div&gt; &lt;p&gt;Our spotlight member this week is Pooh-Bah. He writes good stuff. Read it. &lt;a class="moreInfoLink" href="#"&gt;Learn More&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;div class="column-half r"&gt; &lt;div class="spotlight"&gt;&lt;img src="images/spotlight2.png" alt="Spotlight game" /&gt;&lt;img src="images/spotlight-mask.png" alt="Mask" /&gt;&lt;/div&gt; &lt;p&gt;Killer Bears is a scary ass game from JimmyJones. Escape is mandatory! &lt;a class="moreInfoLink" href="#"&gt;Learn More&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/section&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="main-end"&gt;&lt;/div&gt; &lt;footer&gt; &lt;div class="footer-wrapper"&gt; &lt;div class="footer-inner-wrapper"&gt; &lt;div class="footer-item"&gt; &lt;h4&gt;Community&lt;/h4&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#" title="Scirra developers blog"&gt;The Blog&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" title="Game making community"&gt;Community Forum&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" title="Scirra's available RSS feeds"&gt;RSS Feeds&lt;/a&gt;&lt;/li&gt; &lt;li&gt; &lt;a class="s social-icon facebook" href="http://www.facebook.com/ScirraOfficial" target="_blank" title="Visit Scirra on Facebook"&gt;&lt;/a&gt; &lt;a class="s social-icon twitter" href="http://twitter.com/Scirra" target="_blank" title="Follow Scirra on Twitter"&gt;&lt;/a&gt; &lt;a class="s social-icon youtube" href="http://www.youtube.com/user/ScirraVideos" target="_blank" title="Visit Scirra on Youtube"&gt;&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="footer-item"&gt; &lt;h4&gt;About Us&lt;/h4&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#" title="Contact Scirra"&gt;Contact Information&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" title="Advertise on Scirra"&gt;Advertising&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" title="Scirra's History"&gt;History&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" title="Scirra's Privacy Policies"&gt;Privacy Policy&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" title="Scirra's Terms and Conditions"&gt;Terms and Conditions&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="footer-item"&gt; &lt;h4&gt;Want to Help?&lt;/h4&gt; &lt;p&gt;You can contribute to the community &lt;a href="#" title="Ways to contribute"&gt;in lots of ways&lt;/a&gt;. We have a large active friendly community, and there are lots of ways to join in!&lt;/p&gt; &lt;a href="#" class="ralign" title="Involve yourself in the game making community"&gt;&lt;strong&gt;Learn More&lt;/strong&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="copyright"&gt; Copyright &amp;copy; 2011 Scirra.com. All rights reserved. &lt;/div&gt; &lt;/footer&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="js/common.js"&gt;&lt;/script&gt; &lt;script src="plugins/coin-slider/coin-slider.min.js"&gt;&lt;/script&gt; &lt;script src="js/homepage.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>My first point is that you have no :focus style for your links. If you navigate the page with the keyboard that would really help a lot to see where you are. Take this rule for example:</p>\n\n<pre><code>h3 a:hover\n{\n color: #1B676B;\n text-decoration:none;\n}\n</code></pre>\n\n<p>Just add:</p>\n\n<pre><code>h3 a:hover, h3 a:focus\n{\n color: #1B676B;\n text-decoration:none;\n}\n</code></pre>\n\n<p>Another thing that is nice to do for people navigating with the keyboard is to place a hidden link with a text similar to \"Skip to content\" or something like that close to the top. This link should be a shortcut to the content and only show on :focus. The reason for that is that it takes a lot of tabbing to get through the menu otherwise. </p>\n\n<p>Another tip that doesn't have to do with this question is that vertically aligning your content often creates a more resful reading experience. Indenting the paragraphs make it look more chaotic then it would be they were properly aligned.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-06T08:03:12.663", "Id": "2070", "Score": "0", "body": "If it is decided to add a skip link, do not use `display: none;`, as that would hide it from screen readers and prevent tabbing to it. It is necessary to use another method such as offscreen positioning." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-10T17:38:23.977", "Id": "2174", "Score": "0", "body": "@idealmachine, it is also important to make the skip links visible when focused, as they may also be used by sighted keyboard-only users." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-06T06:33:22.960", "Id": "1174", "ParentId": "1170", "Score": "5" } }, { "body": "<p>I had a really quick look, and here are some suggestions that weren’t already mentioned in other answers:</p>\n\n<ol>\n<li><p>I see you’re using a favicon: </p>\n\n<pre><code>&lt;link rel=\"shortcut icon\" href=\"images/favicon.ico\" /&gt;\n</code></pre>\n\n<p>Did you know that <a href=\"http://mathiasbynens.be/notes/rel-shortcut-icon\"><code>shortcut</code> is not a valid link relation</a>? The good news is: you don’t need it at all. Just move the <code>favicon.ico</code> file to the root of the domain, and remove this clutter from the HTML. For more info, see the link I just gave you.</p></li>\n<li><p>For the <code>apple-touch-icon</code> you could do the same: name it <code>apple-touch-icon.png</code>, place it in the root, and remove the reference from the HTML. For more info, and/or if you want to support multiple resolution icons, have a look at <a href=\"http://mathiasbynens.be/notes/touch-icons\">everything you ever wanted to know about touch icons (but were afraid to ask)</a>.</p></li>\n<li><p>What’s inside the <code>js/googleAnalytics.js</code> file? I assume it (only) contains the GA snippet.</p>\n\n<p>Here’s <a href=\"http://mathiasbynens.be/notes/async-analytics-snippet\">an optimized version of the asynchronous Google Analytics snippet</a> (as featured in the HTML5 Boilerplate). Please use that one if you aren’t doing so already.</p>\n\n<p>Anyhow, I’d recommend not using a separate file for this. Since you have other JavaScript files in the document, I’d suggest to just append the GA snippet to one of those files. I know Google recommends placing the GA snippet in the <code>&lt;head&gt;</code>, but <a href=\"http://mathiasbynens.be/notes/async-analytics-snippet#comment-50\">I’d actually recommend placing it near the closing <code>&lt;/body&gt;</code> tag, along with other scripts</a>. For more information, check out that link.</p></li>\n<li><p>Concatenate and minify all CSS files together, to reduce the total number of HTTP requests. Do the same for JavaScript files (except maybe jQuery, which you’re loading from Google’s CDN).</p></li>\n<li><p>Why are you using character entities like <code>&amp;copy;</code> when you declare the character set as UTF-8? Just save yourself the trouble and use <code>©</code>.</p></li>\n<li><p>What’s with the <code>font-family: Arial, Helvetica;</code> in the CSS? I don’t know of any system where the Helvetica font is available but not Arial.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-25T13:15:20.637", "Id": "2523", "Score": "0", "body": "Great post thanks. In regards to point 3, I favour having the GA code in the head as it catches people who visit the page and exit before footer code has had a chance to run." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-28T11:04:30.227", "Id": "2597", "Score": "0", "body": "@Tom: Personally I would prefer _not_ to count that as a page view, but again, it’s your decision :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-25T13:07:47.553", "Id": "1450", "ParentId": "1170", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-05T16:34:40.530", "Id": "1170", "Score": "6", "Tags": [ "html", "css" ], "Title": "Web-page template" }
1170
<p>I've used jQuery for a long time, and now I'm going to do some animations with vanilla JS. Here's my code so far:</p> <pre><code>var box = document.getElementById('box'), a1end, a2end, cdend, a3end, a4end, animate1 = setInterval(function() { if (box.style.top === (window.innerHeight - 120) + 'px') { clearInterval(animate1); a1end = true; } box.style.top = ( +box.style.top.replace('px', '') + 1 ) + 'px'; }, 1), animate2 = setInterval(function() { if (box.style.left === (window.innerWidth - 120) + 'px') { clearInterval(animate2); a2end = true; } box.style.left = ( +box.style.left.replace('px', '') + 1 ) + 'px'; }, 1); checkEnd1(function() { box.style.background = 'greenyellow'; box.innerText = 'Next stage starts in 5 seconds'; var i = 4, cd = setInterval(function() { if (!i) { clearInterval(cd); cdend = true; } box.innerText = 'Next stage starts in ' + i + ' seconds'; i--; }, 1000); }); checkEnd2(function() { box.style.background = 'white'; box.innerText = ''; var animate3 = setInterval(function() { if (box.style.left === '20px') { clearInterval(animate3); a3end = true; } box.style.left = ( +box.style.left.replace('px', '') - 1 ) + 'px'; }, 1); }); checkEnd3(function() { var animate4 = setInterval(function() { if (box.style.top === '20px') { clearInterval(animate4); a4end = true; } box.style.top = ( +box.style.top.replace('px', '') - 1 ) + 'px'; }, 1); }); checkEnd4(function() { box.style.background = 'lightcyan'; box.innerText = 'Animation complete'; }); function checkEnd1(fn) { (a1end &amp;&amp; a2end) ? fn() : setTimeout(function() { checkEnd1(fn); }, 200); } function checkEnd2(fn) { (cdend) ? fn() : setTimeout(function() { checkEnd2(fn); }, 200); } function checkEnd3(fn) { (a3end) ? fn() : setTimeout(function() { checkEnd3(fn); }, 200); } function checkEnd4(fn) { (a4end) ? fn() : setTimeout(function() { checkEnd4(fn); }, 200); } </code></pre> <p><a href="http://jsfiddle.net/stGcj/3/embedded/result,js" rel="nofollow">jsFiddle demo</a></p> <p>I've also noticed that the first animation isn't working as excepted. Out of curiousity, I tried it with jQuery's <code>.animate()</code> and it worked as excepted:</p> <pre><code>$('#box').animate({ top: window.innerHeight - 120, left: window.innerWidth - 120 }); </code></pre> <p><strong>Note</strong>: please don't tell me to use jQuery or other libs, I want to use vanilla.</p> <hr> <h2>Bounty Edit</h2> <p>Currently, the animation goes diagonally for a while, then when it reaches the bottom, it continues to go sideways. If you tell me how to make it go diagonally all the time, I'll give you a bounty.</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-05T19:28:51.123", "Id": "2057", "Score": "3", "body": "I see you're trying to use javascript. You should totally drop that and use jQuery. *smirk*" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-05T19:48:01.950", "Id": "2060", "Score": "2", "body": "@Ólafur No, I want to use vanilla JS. ;)" } ]
[ { "body": "<p>You're repeating code blocks all over the place; you may want to abstract some out. For example, calling something like</p>\n\n<pre><code>function animatePxProperty(prop, limit, step, interval){\n if(!step) step = 1; //I miss optional arguments :(\n if(!interval) interval = 1;\n var anim = setInterval(\n function() {\n if(parseInt(prop) === parseInt(limit)) clearInterval(anim);\n prop = parseInt(prop) + step + 'px';\n }, interval\n );\n}\n</code></pre>\n\n<p>instead of providing inline anonymous functions to <code>interval</code> (I haven't tested the above, so tweakery may be required).</p>\n\n<hr>\n\n<p>When making comparisons/assignments like</p>\n\n<pre><code>(box.style.left === (window.innerWidth - 120) + 'px') {\n</code></pre>\n\n<p>and</p>\n\n<pre><code>box.style.left = (\n +box.style.left.replace('px', '') + 1\n) + 'px'\n</code></pre>\n\n<p>it's probably better to use <code>parseInt</code> instead of <code>.replace</code>. So</p>\n\n<pre><code>var left_val = parseInt(box.style.left);\n...\n(left_val === (window.innerWidth - 120)) {\n...\nbox.style.left = left_val + 1 + 'px';\n</code></pre>\n\n<hr>\n\n<p>Indulge me, because I'm curious. If you can express exactly what you want with three lines of jQuery, why would you want to implement the same with 88 lines of convoluted side-effects?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T20:18:08.980", "Id": "2086", "Score": "1", "body": "I want to learn vanilla JS. Though I'm still thinking if I really want do to this. I may change my mind. Or not. I tried `parseInt`, but for some reason, it didn't work." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T20:54:18.937", "Id": "2088", "Score": "0", "body": "Doing it as a thought exercise is ok, but god help you if I find this in production code that I have to maintain. What do you mean by \"didn't work\"? I really can't help diagnose it without additional information other than to point you to [its documentation](http://www.w3schools.com/jsref/jsref_parseInt.asp)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T09:59:13.770", "Id": "2101", "Score": "0", "body": "`box.style.top = (parseInt(box.style.top) + 1) + 'px';` – this didn't work. http://jsfiddle.net/Nyuszika7H/stGcj/6/. Though if I do `var num = '120px'; num = parseInt(num) + 1 + 'px'` in the console, it works; `num` becomes `'121px'`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T13:58:47.890", "Id": "2103", "Score": "0", "body": "@Nyuszika7H - That is odd. I assumed `box.style.top` returned something like `\"100px\"`, in which case `parseInt(box.style.top)` should give you `100`. Try using an intermediate variable (`t = parseInt(box.style.top) + 1; box.style.top = t+\"px\"`), although I have to admit that's a bit of programming by superstition." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-21T09:35:55.700", "Id": "3979", "Score": "0", "body": ", The elem.style object doesn't have the styles from external css. It only has values if you set them in the javascript, or inline on the element." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T20:11:27.490", "Id": "1191", "ParentId": "1171", "Score": "5" } }, { "body": "<p>Rather than use your code as a base, I chose to rewrite from scratch to incorporate a couple of ideas to get it to move diagonally properly, as well as hopefully make some cleaner code.</p>\n\n<pre><code>var speed = 2;\n\nfunction animateTo(dom_elem, x, y, finishedCallback) {\n var pos = {\n x: dom_elem.offsetLeft,\n y: dom_elem.offsetTop\n };\n\n function animate() { \n var xToTarget = x - pos.x;\n var yToTarget = y - pos.y;\n\n xToTarget = Math.max(0, xToTarget);\n yToTarget = Math.max(0, yToTarget);\n\n if (xToTarget == 0 &amp;&amp; yToTarget == 0) {\n finishedCallback();\n }\n\n var scale = speed/Math.sqrt(Math.pow(xToTarget, 2) + Math.pow(yToTarget, 2));\n\n var delta_x = xToTarget * scale;\n var delta_y = yToTarget * scale;\n\n pos.x += delta_x;\n pos.y += delta_y;\n\n pos.x = Math.min(x, pos.x);\n pos.y = Math.min(y, pos.y);\n\n dom_elem.style.left = pos.x + 'px';\n dom_elem.style.top = pos.y + 'px';\n\n setTimeout(animate, 1);\n }\n\n setTimeout(animate, 1);\n}\n\nvar box = document.getElementById('box');\nanimateTo(box, window.innerWidth - box.offsetWidth, window.innerHeight - box.offsetHeight, function() {\n alert('done');\n});\n</code></pre>\n\n<p>Firstly, I have abstracted it into the idea of animating a dom element to a particular position. You can then chain together the animations needed using the <code>finishedCallback</code>.</p>\n\n<p>The trick to getting it to animate diagonally properly, instead of hitting the bottom and sliding along, is to move along x and y by different amounts depending on the ratio needed to reach the target instead of always incrementing by 1.</p>\n\n<p>Imagine the current position of the box as one point on the hypotenuse of a triangle, and the destination as the other end of the hypotenuse. The distance along the x-axis forms one of the other edges, and the distance on the y-axis the final edge.</p>\n\n<p>The hypotenuse shows us the line we want the box to travel along. But we don't want to travel there all in one go, we want to move along it slowly. If we take the triangle we have formed, and scale it down the angle of the hypotenuse is still the same, meaning if we keep moving in that direction we will eventually reach the end point, but the distance on the x and y axis are much smaller.</p>\n\n<p>These smaller x and y distances (or deltas) are what we want to add to our position instead of 1.</p>\n\n<p><img src=\"https://i.stack.imgur.com/6YRK0.gif\" alt=\"The triangle\"></p>\n\n<p>If we were trying to animate from A to B, the red line shows how you would move if you always added 1. The dotted lines show the scaled triangles.</p>\n\n<p><code>Math.sqrt(Math.pow(xToTarget, 2) + Math.pow(yToTarget, 2))</code> calculates the length of the hypotenuse in our triangle from current position to the target. We then use <code>speed/length</code> to create the scale we multiply the x and y lengths by. In this way the box will always move the equivalent of <code>speed</code> pixels diagonally towards the target.</p>\n\n<p>I chose to keep track of the x and y position manually instead of reading it back from the dom element because I think it makes the code cleaner, and I <em>think</em> it should be faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-21T12:51:59.320", "Id": "3981", "Score": "0", "body": "Thanks so much! I've subtracted 20 both from `window.innerWidth - box.offsetWidth` and `window.innerHeight - box.offsetHeight`, since the box's original position is `20, 20`, and it [works like a charm](http://jsfiddle.net/stGcj/9/embedded/result%2Cjs/). You only did the first animation, but doing further animations in the callback is easy, I can do it myself." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-21T09:33:23.067", "Id": "2520", "ParentId": "1171", "Score": "7" } } ]
{ "AcceptedAnswerId": "2520", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-05T18:58:37.233", "Id": "1171", "Score": "8", "Tags": [ "javascript" ], "Title": "Animations with vanilla JS" }
1171
<p>This is going to be rather long and generic, so apologies in advance.</p> <p>I've been reading a lot about Haskell lately, but I've never really programmed anything with it beyond simple experiments in ghci. So, I wanted to finally try and do some coding exercise that was easy but non-trivial and ended up choosing the "Recluse" problem from a book called Eloquent JavaScript. </p> <p>The aim is to make a program that takes a text document with simple, custom markup and formats it into HTML according to the following rules:</p> <ol> <li>Paragraphs are separated by blank lines.</li> <li>A paragraph that starts with a '%' symbol is a header. The more '%' symbols, the smaller the header.</li> <li>Inside paragraphs, pieces of text can be emphasised by putting them between asterisks.</li> <li>Footnotes are written between braces.</li> </ol> <p>So for example, the text document</p> <pre>% Heading %% Sub-heading Text with *emphasis*. Another {an example footnote} paragraph.</pre> <p>would be formatted as</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h1&gt;Heading&lt;/h1&gt; &lt;h2&gt;Sub-heading&lt;/h2&gt; &lt;p&gt;Text with &lt;i&gt;emphasis&lt;/i&gt;.&lt;/p&gt; &lt;p&gt;Another&lt;a href="#footnote1"&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/a&gt; paragraph.&lt;/p&gt; &lt;p&gt;&lt;small&gt;&lt;a name="footnote1"&gt;1. an example footnote&lt;/a&gt;&lt;/small&gt;&lt;/p&gt;</code></pre> </div> </div> </p> <p>The main program should read the text document from stdin and output the HTML to stdout.</p> <p>This seemed like a simple enough task at first (I'd estimate that using Python, a language I have a lot of experience with, I could've finished it in about 15-30 minutes), but as I got deeper into the implementation, I realized I have no clue how to do something like this in Haskell. The footnotes seemed particularily challenging, as you kind of have to accumulate them on the side while building the rest of the document, and I didn't have any idea how to express that in functional terms (at least not without dragging an extra footnotes argument in every single function call).</p> <p>I hacked at the problem for a few evenings, re-reading Haskell tutorials and perusing the standard library reference, and finally ended up with a solution that works correctly, with some assumptions (for example, nested markup is not supported). However, my solution feels like it's over-complicated for such a simple problem and it consumes relatively high amounts of memory.</p> <p>So, my question is: how could I simplify the program and turn it into more idiomatic Haskell? The <code>formatText</code> function especially is something that turned out really ugly in my opinion. I'm not expecting anyone to rewrite the whole program, but small fixes here and there would be greatly appreciated.</p> <p>Secondly, how would I make the program more memory efficient? The current implementation allocates about 400KB of heap for every 1KB of input text, which isn't really a problem for this program, but I think it indicates that I'm doing something stupid. I've read articles about reducing memory consumption by forcing strictness, but it's not readily apparent to me where strictness should be applied in my program for the best effect.</p> <p>Thanks!</p> <pre><code>import Char import Data.List import Control.Monad.State data Footnote = Footnote Int String data Footnotes = Footnotes Int [Footnote] type TrackNotes = State Footnotes type HTML = String -- |Enclose content in the given HTML element -- e.g. html &quot;span&quot; &quot;foo&quot; -&gt; &quot;&lt;span&gt;foo&lt;/span&gt;&quot; html :: String -&gt; String -&gt; HTML html tag content = foldl1' (++) [&quot;&lt;&quot;, tag, &quot;&gt;&quot;, content, &quot;&lt;/&quot;, tag, &quot;&gt;&quot;] -- |Generate a HTML link element ahref :: String -&gt; String -&gt; HTML ahref link txt = foldl1' (++) [&quot;&lt;a href=\&quot;&quot;, link, &quot;\&quot;&gt;&quot;, txt, &quot;&lt;/a&gt;&quot;] -- |Replace &lt;, &gt; and &amp; with HTML entities htmlEscape :: String -&gt; HTML htmlEscape &quot;&quot; = &quot;&quot; htmlEscape (x:xs) = prefix $! htmlEscape xs where prefix = case x of '&amp;' -&gt; showString &quot;&amp;amp;&quot; '&lt;' -&gt; showString &quot;&amp;lt;&quot; '&gt;' -&gt; showString &quot;&amp;gt;&quot; _ -&gt; (x:) -- |Add a new footnote addFootnote :: String -&gt; TrackNotes Int addFootnote s = State $ \(Footnotes i ns) -&gt;(i, Footnotes (i+1) $ ns ++ [Footnote i s]) -- |Format a text section into HTML formatSection :: String -&gt; TrackNotes HTML formatSection s = case s of ('%'):xs -&gt; formatHeading s _ -&gt; formatParagraph s -- |Format a text heading into HTML heading formatHeading :: String -&gt; TrackNotes HTML formatHeading s = liftM headingTag content where headingTag = html (&quot;h&quot; ++ show level) level = length prefix content = formatText $ htmlEscape $ dropWhile isSpace postfix (prefix,postfix) = span (=='%') s -- |Format a text paragraph into HTML paragraph formatParagraph :: String -&gt; TrackNotes HTML formatParagraph = liftM (html &quot;p&quot;) . formatText . htmlEscape -- |Format inline markup in text contents, e.g. &quot;*foo* bar&quot; -&gt; &quot;&lt;i&gt;foo&lt;/i&gt; bar&quot; formatText :: String -&gt; TrackNotes HTML formatText &quot;&quot; = return &quot;&quot; formatText s = do (content,rest) &lt;- processTag $ postfix rest' &lt;- formatText $ rest return $ prefix ++ (content ++ rest') where (prefix,postfix) = break (`elem` &quot;*{&quot;) s processTag &quot;&quot; = return (&quot;&quot;, &quot;&quot;) processTag (tag:rest) = do html' &lt;- format $ between return (html', tail') where (format, endChar) = case tag of '*' -&gt; (formatEmph, '*') '{' -&gt; (formatNote, '}') (between, _:tail') = break (==endChar) rest formatEmph = return . html &quot;i&quot; formatNote s = do idx &lt;- liftM show $ addFootnote s let link = &quot;#footnote&quot; ++ idx let text = html &quot;sup&quot; idx return $ ahref link text -- |Split a string into sections. -- Two consecutive line breaks form a section break. splitSections :: String -&gt; [String] splitSections = sections . lines where sections (x:[]:xs) = x : sections xs sections (x:y:xs) = sections $ (x ++ ('\n' : y)) : xs sections x = x -- | Format a footnote at the end of the document formatFootnote :: Footnote -&gt; HTML formatFootnote (Footnote i s) = html &quot;p&quot; $ html &quot;small&quot; $ anchor where anchor = &quot;&lt;a name=\&quot;footnote&quot; ++ show i ++ &quot;\&quot;&gt;&quot; ++ text ++ &quot;&lt;/a&gt;&quot; text = show i ++ &quot;. &quot; ++ s -- |Format a text document into HTML document formatDocument :: String -&gt; String formatDocument txt = unlines $ sections ++ footnotes where (sections, state) = runState stateMonad (Footnotes 1 []) stateMonad = mapM formatSection $ splitSections txt Footnotes _ notes = state footnotes = map formatFootnote notes main = interact formatDocument</code></pre> <p>UPDATE: I rewrote the program so that parsing and output are separate as per sepp2k's suggestion, and while that does make the program a bit longer, it keeps the individual functions a lot simpler. </p> <pre><code>import Char import Data.List import Data.Maybe import Control.Monad.State type HTML = String type HeadingLevel = Int {---------------------------------------------------------------- Data types and functions for parsing the markup to a parse tree -----------------------------------------------------------------} data Section = Heading HeadingLevel [DocNode] | Paragraph [DocNode] data DocNode = PlainText String | Emphasis [DocNode] | Footnote [DocNode] parseMarkup :: String -&gt; [Section] parseMarkup = mapMaybe parseSection . splitSections parseSection :: String -&gt; Maybe Section parseSection &quot;&quot; = Nothing parseSection s = case s of ('%':_) -&gt; Just $ parseHeading s _ -&gt; Just $ Paragraph $ parseNodes s parseHeading :: String -&gt; Section parseHeading s = Heading lvl nodes where lvl = length prefix nodes = parseNodes $ dropWhile isSpace postfix (prefix,postfix) = span (=='%') s parseNodes :: String -&gt; [DocNode] parseNodes &quot;&quot; = [] parseNodes s = fst $ parseNodes' Nothing $ zipper s where parseNodes' g ((i,(c:t)):_) | (g == Just c) = ([PlainText i], t) parseNodes' _ [(i,&quot;&quot;)] = ([PlainText i], &quot;&quot;) parseNodes' g ((i,t):xs) = case t of ('*':_) -&gt; continue Emphasis '*' i t ('{':_) -&gt; continue Footnote '}' i t _ -&gt; parseNodes' g xs continue f end &quot;&quot; t = parseNonText f end $ tail t continue f end i t = (PlainText i : moreNodes, rest) where (moreNodes, rest) = parseNonText f end $ tail t parseNonText f end t = ((f nodes) : moreNodes, rest') where (nodes, rest) = parseNodes' (Just end) $ zipper t (moreNodes, rest') = parseNodes' Nothing $ zipper rest {------------------------------------------------ Data types and functions for tracking footnotes -------------------------------------------------} data Footnotes = Footnotes Int [String] type TrackNotes = State Footnotes addFootnote :: String -&gt; TrackNotes Int addFootnote s = State $ \(Footnotes i ns) -&gt;(i, Footnotes (i+1) $ ns ++ [s]) {--------------------------------------- Functions for converting nodes to HTML ----------------------------------------} docToHTML :: [Section] -&gt; HTML docToHTML ss = unlines $ sections ++ footnotes where (sections, state) = runState stateMonad $ Footnotes 1 [] stateMonad = mapM sectionToHTML ss (Footnotes _ notes) = state footnotes = map formatFootnote $ zip notes [1..] sectionToHTML :: Section -&gt; TrackNotes HTML sectionToHTML (Heading lvl nodes) = liftM htag $ nodesToHTML nodes where htag = html $ &quot;h&quot; ++ show lvl sectionToHTML (Paragraph nodes) = liftM ptag $ nodesToHTML nodes where ptag = html &quot;p&quot; nodesToHTML :: [DocNode] -&gt; TrackNotes HTML nodesToHTML = liftM (foldl' (++) &quot;&quot;) . mapM nodeToHTML -- | Convert a single DocNode to HTML nodeToHTML :: DocNode -&gt; TrackNotes HTML nodeToHTML (PlainText s) = return s nodeToHTML (Emphasis nodes) = liftM (html &quot;i&quot;) $ nodesToHTML nodes nodeToHTML (Footnote nodes) = do content &lt;- nodesToHTML nodes idx &lt;- liftM show $ addFootnote content let link = &quot;#footnote&quot; ++ idx let text = html &quot;sup&quot; idx return $ ahref link text -- | Format a footnote at the end of the document formatFootnote :: (String, Int) -&gt; HTML formatFootnote (s,i) = html &quot;p&quot; $ html &quot;small&quot; $ anchor where anchor = &quot;&lt;a name=\&quot;footnote&quot; ++ show i ++ &quot;\&quot;&gt;&quot; ++ text ++ &quot;&lt;/a&gt;&quot; text = show i ++ &quot;. &quot; ++ s -- |Enclose content in the given HTML element -- e.g. html &quot;span&quot; &quot;foo&quot; -&gt; &quot;&lt;span&gt;foo&lt;/span&gt;&quot; html :: String -&gt; String -&gt; HTML html tag content = foldl1' (++) [&quot;&lt;&quot;, tag, &quot;&gt;&quot;, content, &quot;&lt;/&quot;, tag, &quot;&gt;&quot;] -- |Generate a HTML link element ahref :: String -&gt; String -&gt; HTML ahref link txt = foldl1' (++) [&quot;&lt;a href=\&quot;&quot;, link, &quot;\&quot;&gt;&quot;, txt, &quot;&lt;/a&gt;&quot;] -- |Replace &lt;, &gt; and &amp; with HTML entities htmlEscape :: String -&gt; HTML htmlEscape &quot;&quot; = &quot;&quot; htmlEscape (x:xs) = prefix $! htmlEscape xs where prefix = case x of '&amp;' -&gt; showString &quot;&amp;amp;&quot; '&lt;' -&gt; showString &quot;&amp;lt;&quot; '&gt;' -&gt; showString &quot;&amp;gt;&quot; _ -&gt; (x:) {------------------------------ Miscellanous string utilities -------------------------------} -- |Split a string into sections. -- Two consecutive line breaks form a section break. splitSections :: String -&gt; [String] splitSections = sections . lines where sections (x:[]:xs) = x : sections xs sections (x:y:xs) = sections $ (x ++ ('\n' : y)) : xs sections x = x -- | A &quot;zipper&quot; for navigating a string -- Generates a list of (init,tail) pairs that traverse the list -- E.g. zipper &quot;foo&quot; -&gt; [(&quot;&quot;,&quot;foo&quot;), (&quot;f&quot;,&quot;oo&quot;), (&quot;fo&quot;,&quot;o&quot;), (&quot;foo&quot;,&quot;&quot;)] zipper :: String -&gt; [(String,String)] zipper s = zip (inits s) (tails s) {----- Main ------} formatDoc :: String -&gt; HTML formatDoc = docToHTML . parseMarkup main = interact formatDoc</code></pre>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T15:16:36.483", "Id": "2083", "Score": "0", "body": "Maybe a more meaningful topic name?" } ]
[ { "body": "<p>One of Haskell's advantages is that there's a good number of high-quality parser libraries for it. Using one for this case might be a bit overkill, but since this is a learning exercise anyway it might be a good chance to pick up a parser library (e.g. parsec) as well. This could certainly come in handy later. Also using such a library, you could support nested markup without any trouble.</p>\n\n<hr>\n\n<p>About memory: Haskell strings, being (lazy) linked lists of characters, just aren't very memory efficient. For this reason it is often recommended to use bytestrings or <code>Data.Text</code> in favor of plain strings if you need memory-efficient string handling.</p>\n\n<hr>\n\n<blockquote>\n <p>The footnotes seemed particularily challenging, as you kind of have to accumulate them on the side while building the rest of the document, and I didn't have any idea how to express that in functional terms (at least not without dragging an extra footnotes argument in every single function call).</p>\n</blockquote>\n\n<p>As you already found out one solution to track state through the program without adding extra arguments is the State monad. However in this case I feel that it made the program more complicated than it needed to be.</p>\n\n<p>I think an extra footnotes argument (and a second one to count them) would actually have been the simplest solution here.</p>\n\n<hr>\n\n<p>As a general design note, I think a two-step approach would make the code more manageable and extensible: First parse the string into an internal representation (I would call it a tree, except that until you support nested markup, it won't actually be a tree), and then write a function which turns that representation into HTML.</p>\n\n<p>This way you separate the code that does the parsing from the code that produces the HTML, which is good style. It also allows you to add another output format later without having to duplicate any parsing code. It should also be easier to support nested markup using this approach and it also makes it easier to replace your manual parsing code with a parsing library should you decide to do so.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T06:19:35.447", "Id": "2073", "Score": "0", "body": "Thanks! The reason I didn't use an existing parsing library is because I want to learn the standard libraries before adding any external dependencies, and also because I wanted to get a feel for working with strings directly in Haskell. Separating the parsing and HTML was a great suggestion. As for the State monad, I tried rewriting the footnotes without it, but it seemed a lot messier that way. In addition to extra parameters, you also need to return multiple values from everything and end up having tuple unpackings all over the place." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-06T15:13:47.833", "Id": "1177", "ParentId": "1176", "Score": "7" } } ]
{ "AcceptedAnswerId": "1177", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-06T12:05:18.200", "Id": "1176", "Score": "14", "Tags": [ "functional-programming", "haskell" ], "Title": "Converting simple markup to HTML" }
1176
<p>I am doing a CS practice exercise in which you are supposed to sort exactly three numbers using only if statements. I wrote the following code in LISP and would appreciate any suggestions how to improve on my code. Thank you!</p> <pre><code>(defun generate-three () (loop for l from 1 to 3 collect (random 25))) (defun result (a b c) (format t "The sorted result is (~d,~d,~d)~%" a b c)) (let (a b c (the-three (generate-three))) (format t "~a ~%" the-three) (setq a (first the-three) b (second the-three) c (third the-three)) (if (&lt; a b) (if (&lt; b c) (result a b c) (if (&lt; a c) (result a c b) (result c a b))) (if (&lt; a c) (result b a c) (if (&lt; b c) (result b c a) (result c b a))))) </code></pre> <p>Based on feedback from commenters, the revised code looks as follows:</p> <pre><code>(defun my-sort-3 (a b c) (if (&lt; a b) (if (&lt; b c) (list a b c) (if (&lt; a c) (list a c b) (list c a b))) (if (&lt; a c) (list b a c) (if (&lt; b c) (list b c a) (list c b a))))) (destructuring-bind (a b c) (loop repeat 3 collect (random 25)) (format t "The sorted result of (~d,~d,~d) is ~a ~%" a b c (my-sort-3 a b c))) </code></pre> <p>Latest iteration - note the changes in the final "format" statement:</p> <pre><code>(defun my-sort-3 (a b c) (if (&lt; a b) (if (&lt; b c) (list a b c) (if (&lt; a c) (list a c b) (list c a b))) (if (&lt; a c) (list b a c) (if (&lt; b c) (list b c a) (list c b a))))) (destructuring-bind (a b c) (loop repeat 3 collect (random 25)) (format t "The sorted result of (~{~d~^, ~}) is (~{~d~^, ~})~%" (list a b c) (my-sort-3 a b c))) </code></pre>
[]
[ { "body": "<p>It's been a while since I've used lisp, so I can't really critique your code for style or any common lisp gotchas.</p>\n\n<p>That said, the biggest thing I notice here is that the code for generating the 3 numbers, sorting them, and printing the result are all tightly coupled with each other. I would suggest defining a separate function that takes three numbers and returns them in sorted order, which can then be combined with your existing functions for generating three numbers and printing three numbers to give the desired output. The added benefit, of course, is that this sort function can later be used to sort any three numbers, not just the three in this bit of code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T02:48:44.740", "Id": "1181", "ParentId": "1179", "Score": "3" } }, { "body": "<p>Since you have to use <code>if</code>s, I won't comment on that other than to say that <code>cond</code> (or, more likely, a recursive call) is probably the right choice here.</p>\n\n<hr>\n\n<p>The <code>loop</code> you use in <code>generate-three</code> is slightly more complicated than you need it to be. You can specify what you need with <code>(loop repeat 3 collect (random 25))</code>. That's short enough that you won't need an intermediate function for this exercise. <code>loop</code> is a fairly complicated construct (probably the most complicated in Lisp). If you really want to come to grips with it, read through <a href=\"http://cl-cookbook.sourceforge.net/loop.html\" rel=\"nofollow\">The CL Cookbook entry</a> and <a href=\"http://www.gigamonkeys.com/book/loop-for-black-belts.html\" rel=\"nofollow\">Seibels' Loop chapter from Practical Common Lisp</a>.</p>\n\n<hr>\n\n<p>There's no need to declare variables in Lisp, so the <code>a b c</code> (effectively <code>(a nil) (b nil) (c nil)</code>) in the initial <code>let</code> statement is unnecessary. Since the only reason you're declaring those <code>nil</code> variables is to assign them later, this would be a good place to use <code>destructuring-bind</code></p>\n\n<pre><code>(destructuring-bind (a b c) (loop repeat 3 collect (random 25))\n (format t \"~a ~%\" (list a b c))\n (if (&lt; a b)\n (if (&lt; b c) \n (result a b c)\n (if (&lt; a c) (result a c b) (result c a b)))\n (if (&lt; a c) \n (result b a c)\n (if (&lt; b c) (result b c a) (result c b a)))))\n</code></pre>\n\n<hr>\n\n<p>Is there a particular reason that you didn't define the final statement as a function that accepts three arguments (or a three-element list), and then call it? Also, is there any reason that your function prints out a summarizing sentence of its results, rather than returning a sorted list? Both of these points severely limit the reusability of your code. Had you, for example, defined this as <code>my-sort-3</code>, instead of making it a naked <code>let</code> call, you could have used it in your triangle-related assignment.</p>\n\n<p>This would also further simplify the code</p>\n\n<pre><code>(defun my-sort-3 (a b c)\n (if (&lt; a b)\n (if (&lt; b c) \n (list a b c)\n (if (&lt; a c) (list a c b) (list c a b)))\n (if (&lt; a c) \n (list b a c)\n (if (&lt; b c) (list b c a) (list c b a)))))\n\n(format t \"The sorted result is ~a~%\" \n (apply #'my-sort-3 (loop repeat 3 collect (random 25))))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T23:52:41.520", "Id": "2091", "Score": "0", "body": "Thank you! This looks fantastic. I see how redefining it that way makes it more elegant and reusable. I am a bit confused about how it would be used in the triangle code, but otherwise I am very happy with this feedback - thank you." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T23:58:40.030", "Id": "2092", "Score": "0", "body": "@jaresty - I left a pretty extensive answer there too (and it explains where you would use this) :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T05:36:00.997", "Id": "2096", "Score": "0", "body": "Sorry - I just got to looking at the triangle explanation and I clearly see it written there. Thanks!" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T03:01:58.423", "Id": "2117", "Score": "0", "body": "By the way, why do you need the 'apply' in the last example? Would it work the same if written \"(my-sort-3 (loop repeat 3 collect (random 25)))\"?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T03:10:17.503", "Id": "2118", "Score": "0", "body": "It will if you have `my-sort-3` take a list as its argument. If you want it to take three numeric arguments, you have to apply it (or get into multiple-value returns and calls)." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T03:19:09.057", "Id": "2119", "Score": "0", "body": "@jaresty - So, something like `(defun my-sort-3 (val-list) ...`. Thing is, you have to take `val-list` apart into `a`, `b` and `c` yourself." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T17:08:17.143", "Id": "1187", "ParentId": "1179", "Score": "2" } }, { "body": "<p>In response to your follow-up. If you're really keen to keep the final formatting of the result \"(~d, ~d, ~d)\", you can still do that by formatting a list, you'd just have a slightly more complicated directive.</p>\n\n<pre><code>(format t \"The sorted result is (~{~d~^, ~})~%\" \n (apply #'my-sort-3 (loop repeat 3 collect (random 25))))\n</code></pre>\n\n<p>In a format directive <code>~{ ~}</code> denotes a loop. It expects a list, and applies the contained directive to each element. Within curlies in a format directive, <code>~^</code> denotes a joining string. Anything after it is repeated except on the last iteration. So, assuming the <code>loop</code> generated <code>(1 2 3)</code>, the result of the above statement would be</p>\n\n<pre><code>The sorted result is (3, 2, 1)\nNIL\n</code></pre>\n\n<p>For more information on <code>format</code>, check <a href=\"http://www.gigamonkeys.com/book/a-few-format-recipes.html\" rel=\"nofollow\">Seibels' chapter on format</a> (in fact <a href=\"http://www.gigamonkeys.com/book/\" rel=\"nofollow\">the entire book</a> might be useful to you. (That wasn't <a href=\"http://rads.stackoverflow.com/amzn/click/1590592395\" rel=\"nofollow\">the Amazon link</a>, by the way, the entire Practical Common Lisp is available for free online)), and the <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm\" rel=\"nofollow\">CLHS section on formatted output</a>.</p>\n\n<p>If you're up for a challenge, after reading some of the above you should be able to replace this</p>\n\n<pre><code>(cond ((eq 'right triangle-type) (status-message \"is a right triangle.\" a b c))\n ((eq 'equilateral triangle-type) (status-message \"is an equilateral triangle.\" a b c))\n ((eq 'isoceles triangle-type) (status-message \"is an isoceles triangle.\" a b c))\n ((eq 'triangle triangle-type) (status-message \"is a non-right, non-isoceles, non-equilateral triangle.\" a b c))\n (t (status-message \"is not a triangle.\" a b c)))\n</code></pre>\n\n<p>with a single <code>format</code> statement in your triangle assignment.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T14:00:47.043", "Id": "1197", "ParentId": "1179", "Score": "2" } } ]
{ "AcceptedAnswerId": "1197", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T02:14:47.887", "Id": "1179", "Score": "5", "Tags": [ "lisp", "common-lisp" ], "Title": "Sorting numbers in LISP" }
1179
<p>I wrote the following Ruby script several years ago and have been using it often ever since on a Bioinformatics computer cluster.</p> <p>It pulls out a list of hosts from the Torque queuing system <code>qnodes</code>. It <code>ssh</code>'es and runs a command on all the nodes. Then it prints the output and/or errors in a defined order (alphabetical sort of the hostnames).</p> <p>A nice feature: results are printed immediately for the host that is next in the order.</p> <p><img src="https://i.stack.imgur.com/4cxca.png" alt="on-all-nodes-run"></p> <p>I would like to use it as an example for a Ruby workshop. Could you please suggest best-practice and design pattern improvements?</p> <pre><code>#!/usr/bin/ruby EXCLUDE = [/girkelab/, /biocluster/, /parrot/, /owl/] require "open3" # Non-interactive, no password asking, and seasonable timeouts SSH_OPTIONS = ["-o PreferredAuthentications=publickey,hostbased,gssapi,gssapi-with-mic", "-o ForwardX11=no", "-o BatchMode=yes", "-o SetupTimeOut=5", "-o ServerAliveInterval=5", "-o ServerAliveCountMax=2" ].join(" ") SSH = "/usr/bin/ssh #{SSH_OPTIONS}" MKDIR = "/bin/mkdir" raise "Pleae give this command at least one argument" if ARGV.size &lt; 1 COMMAND = ARGV[0..-1].join(' ') output_o = {} output_e = {} IO_CONNECTIONS_TO_REMOTE_PROCESSES = {} def on_all_nodes(&amp;block) nodes = [] Kernel.open('|qnodes | grep -v "^ " | grep -v "^$"') do |f| while line = f.gets i = line.split(' ').first nodes.push(i) if EXCLUDE.select{|x| i =~ x}.empty? end end nodes.sort.each {|n| block.call(n)} end # Create processes on_all_nodes do |node| stdin, stdout, stderr = Open3.popen3("#{SSH} #{node} \"#{COMMAND}\"") IO_CONNECTIONS_TO_REMOTE_PROCESSES[node] = [stdin, stdout, stderr] end has_remote_errors = false # Collect results on_all_nodes do |node| stdin, stdout, stderr = IO_CONNECTIONS_TO_REMOTE_PROCESSES[node] stdin.close e_thread = Thread.new do while line = stderr.gets line.chomp! STDERR.puts "#{node} ERROR: #{line}" has_remote_errors = true end end o_thread = Thread.new do while line = stdout.gets line.chomp! puts "#{node} : #{line}" end end # Let the threads finish t1 = nil t2 = nil while [t1, t2].include? nil if t1.nil? t1 = e_thread.join(0.1) # Gives 1/10 of a second to STDERR end if t2.nil? t2 = o_thread.join(0.1) # Give 1/10 of a second to STDOUT end end end exit(1) if has_remote_errors </code></pre>
[]
[ { "body": "<p>First of all, take a look at the <a href=\"http://net-ssh.github.com/ssh/v2/api/index.html\"><code>Net::SSH</code></a> library. I don't have much experience with it, so I don't know whether it supports all the options you need. But if it does, using it might be more robust than using the command line utility (you wouldn't have to worry about whether <code>ssh</code> is installed in the place you expect (or at all) and you wouldn't have to worry about escaping the arguments).</p>\n\n<p>Assuming you can't (or won't) use <code>Net::SSH</code>, you should at least replace <code>/usr/bin/ssh</code> with just <code>ssh</code>, so at least it still works if <code>ssh</code> is installed in another location in the PATH.</p>\n\n<hr>\n\n<pre><code>nodes = []\nKernel.open('|qnodes | grep -v \"^ \" | grep -v \"^$\"') do |f|\n while line = f.gets\n i = line.split(' ').first\n nodes.push(i) if EXCLUDE.select{|x| i =~ x}.empty?\n end\nend\n</code></pre>\n\n<ol>\n<li>When you initialize an empty array and then append to it in a loop, that is often a good sign you want to use <code>map</code> and/or <code>select</code> instead.</li>\n<li><code>line = f.gets</code> is a bit of an anti-pattern in ruby. The <code>IO</code> class already has methods to iterate a file line-wise.</li>\n<li><p>To find out whether none of the elements in an array meet a condition, negating <code>any?</code> seems more idiomatic than building an array with <code>select</code> and check whether it's empty.</p>\n\n<pre><code>nodes = Kernel.open('|qnodes | grep -v \"^ \" | grep -v \"^$\"') do |f|\n f.lines.map do |line|\n line.split(' ').first\n end.reject do |i|\n EXCLUDE.any? {|x| i =~ x}\n end\nend\n</code></pre></li>\n</ol>\n\n<hr>\n\n<pre><code>nodes.sort.each {|n| block.call(n)}\n</code></pre>\n\n<p>I would recommend that instead of taking a block and yielding each element, you just return <code>nodes.sort</code> and rename the function to <code>all_nodes</code>. This way you can use <code>all_nodes.each</code> to execute code on all nodes, but you could also use <code>all_nodes.map</code> or <code>all_nodes.select</code> when it makes sense.</p>\n\n<hr>\n\n<pre><code>Open3.popen3(\"#{SSH} #{node} \\\"#{COMMAND}\\\"\")\n</code></pre>\n\n<p>Note that this will break if <code>COMMAND</code> contains double quotes itself. Generally trying to escape command line arguments by surrounding them with quotes is a bad idea. <code>system</code> and <code>open3</code> accept multiple arguments exactly to avoid this.</p>\n\n<p>If you make <code>SSH</code> an array (with one element per argument) instead of a string, you can use the multiple-arguments version of <code>popen3</code> and can thus avoid the fickle solution of adding quote around <code>COMMAND</code> to escape spaces, i.e.:</p>\n\n<pre><code>Open3.popen3(*(SSH + [node, COMMAND]))\n</code></pre>\n\n<hr>\n\n<pre><code>IO_CONNECTIONS_TO_REMOTE_PROCESSES = {}\n# ...\non_all_nodes do |node|\n stdin, stdout, stderr = Open3.popen3(\"#{SSH} #{node} \\\"#{COMMAND}\\\"\")\n IO_CONNECTIONS_TO_REMOTE_PROCESSES[node] = [stdin, stdout, stderr]\nend\n</code></pre>\n\n<p>If you heeded my above advice about <code>all_nodes</code> you can simplify this using <code>map</code>. I also would suggest not using a Hash here. If you use an array instead, the nodes will stay in the order in which you inserted them, which will mean that you can iterate over that array instead of invoking <code>all_nodes</code> again.</p>\n\n<pre><code>has_remote_errors = false\n\nall_nodes.map do |node|\n [node, Open3.popen3(*(SSH + [node, COMMAND]))]\nend.each do |node, (stdin, stdout, stderr)|\n stdin.close\n\n ethread = # ...\n # ...\nend\n</code></pre>\n\n<p>This way you removed the complexity of first putting everything into a hash and then getting it out again.</p>\n\n<hr>\n\n<pre><code>while line = stderr.gets\n</code></pre>\n\n<p>Again, this can be written more idiomatically as <code>stderr.each_line do |line|</code>. Same with stdout.</p>\n\n<hr>\n\n<pre><code>first = true\n</code></pre>\n\n<p>This is never used. I can only assume that it's a left over of previous iterations of the code, which is no longer necessary. Obviously it should be removed.</p>\n\n<hr>\n\n<pre><code># Let the threads finish\nt1 = nil\nt2 = nil\nwhile [t1, t2].include? nil\n if t1.nil?\n t1 = e_thread.join(0.1) # Gives 1/10 of a second to STDERR\n end\n if t2.nil?\n t2 = o_thread.join(0.1) # Give 1/10 of a second to STDOUT\n end\nend\n</code></pre>\n\n<p>I don't see any benefit of doing it this way. Just do:</p>\n\n<pre><code>e_thread.join\no_thread.join\n</code></pre>\n\n<p>Note that <code>join</code>ing on one thread does not mean that the other threads stop running - only the main thread does, but that's perfectly okay as you want that anyway.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T03:15:53.447", "Id": "2094", "Score": "2", "body": "`e_thread.join; o_thread.join` works just fine. I am not able to reproduce nether dead-locks nor the out-of-order problems. This alone cuts 10 lines." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T21:21:19.100", "Id": "1193", "ParentId": "1180", "Score": "10" } }, { "body": "<p>One can also use the '<a href=\"https://github.com/grosser/parallel\" rel=\"nofollow\">parallel</a>' gem to similar effect:</p>\n\n<pre><code>host_hash = { \"hosta\" =&gt; {}, \"hostb\" =&gt; {} } \nParallel.each(host_hash.keys, :in_threads =&gt; host_hash.keys.size) do |host|\n\n cmd = \"ssh #{host} whoami\" # assuming keys are setup.\n Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thr|\n host_hash[host]['stdout'] = stdout.read\n host_hash[host]['stderr'] = stderr.read\n host_hash[host]['exit_code'] = wait_thr.value\n if wait_thr.value != 0\n $stderr.puts \"ssh #{host} failed with #{wait_thr.value}\"\n end\n end\nend\n# then loop through hash to see results.\n</code></pre>\n\n<p>The one issue I see is that you have to wait for the SSH commands to complete before you see any output. There may be a way to '<a href=\"https://nickcharlton.net/posts/ruby-subprocesses-with-stdout-stderr-streams.html\" rel=\"nofollow\">stream</a>' the output as it happens.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-15T07:05:37.290", "Id": "101000", "ParentId": "1180", "Score": "3" } } ]
{ "AcceptedAnswerId": "1193", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-07T02:44:22.653", "Id": "1180", "Score": "10", "Tags": [ "ruby", "multithreading", "networking", "child-process" ], "Title": "Ruby script on-all-nodes-run not only for teaching" }
1180
<p>This is a simple LISP program to read in three sides of a triangle and report what kind of triangle it is (or isn't). Any feedback would be much appreciated.</p> <pre><code>(defun read-side (side) (format t "Enter a value for side ~d: ~%" side) (read)) (defun is-a-triangle (a b c) (if (and (&lt; a (+ b c)) (&lt; b (+ a c)) (&lt; c (+ a b))) t nil)) (defun is-equilateral (a b c) (if (and (= a b c)) t nil)) (defun is-isoceles (a b c) (if (or (= a b) (= b c)) t nil)) (defun is-right-triangle (a b c) (let ((square-of-short-sides-sum 0) (short-sides ()) (large-side 0) (sides (list a b c))) (loop for p in sides do (if (&gt; p large-side) (progn (if (/= 0 large-side) (setq short-sides (append short-sides (list large-side)))) (setq large-side p)) (setq short-sides (append short-sides (list p))))) (format t "short-sides: ~a ~%" short-sides) (format t "large-side: ~a ~%" large-side) (loop for p in short-sides do (setq square-of-short-sides-sum (+ square-of-short-sides-sum (expt p 2)))) (if (= (expt large-side 2) square-of-short-sides-sum) t nil))) (defun status-message (message a b c) (format t "The shape ~d,~d,~d ~a ~%" a b c message)) (let ((a (read-side 1)) (b (read-side 2)) (c (read-side 3))) (status-message "is being checked..." a b c) (if (is-equilateral a b c) (status-message "is an equilateral triangle." a b c) (if (is-a-triangle a b c) (progn (if (is-isoceles a b c) (status-message "is an isoceles triangle." a b c) (if (is-right-triangle a b c) (status-message "is a right triangle." a b c) (status-message "is a non-isoceles, non-equilateral, non-right triangle." a b c)))) (status-message "is not a triangle." a b c)))) </code></pre> <p>Thanks to the previous commenters for your suggestions. I have since modified the code based on the feedback I have received and am posting the revised code below. If you have any further feedback on this new revision, it is welcome. Thank you!</p> <pre><code>(defun read-side (side) (format t "Enter a value for side ~d: ~%" side) (read)) (defun triangle-p (a b c) (and (&lt; a (+ b c)) (&lt; b (+ a c)) (&lt; c (+ a b)))) (defun equilateral-p (a b c) (= a b c)) (defun isoceles-p (a b c) (or (= a b) (= b c))) (defun right-triangle-p (a b c) (destructuring-bind (long-side &amp;rest short-sides) (sort (list a b c) #'&gt;) (= (expt long-side 2) (+ (expt (first short-sides) 2) (expt (second short-sides) 2))))) (defun status-message (message a b c) (format t "The shape ~d,~d,~d ~a ~%" a b c message)) (defun classify-triangle (a b c) (cond ((not (triangle-p a b c))) ((right-triangle-p a b c) 'right) ((equilateral-p a b c) 'equilateral) ((isoceles-p a b c) 'isoceles) (t 'triangle))) (let (triangle-type (a (read-side 1)) (b (read-side 2)) (c (read-side 3))) (format t "classify triangle says ~a ~%" (classify-triangle a b c)) (setq triangle-type (classify-triangle a b c)) (cond ((eq 'right triangle-type) (status-message "is a right triangle." a b c)) ((eq 'equilateral triangle-type) (status-message "is an equilateral triangle." a b c)) ((eq 'isoceles triangle-type) (status-message "is an isoceles triangle." a b c)) ((eq 'triangle triangle-type) (status-message "is a non-right, non-isoceles, non-equilateral triangle." a b c)) (t (status-message "is not a triangle." a b c)))) </code></pre> <p>Here is the latest revision:</p> <pre><code>(defun read-side (side) (format t "Enter a value for side ~d: ~%" side) (read)) (defun triangle-p (a b c) (and (&lt; a (+ b c)) (&lt; b (+ a c)) (&lt; c (+ a b)))) (defun equilateral-p (a b c) (= a b c)) (defun isoceles-p (a b c) (or (= a b) (= b c))) (defun right-triangle-p (a b c) (destructuring-bind (long-side &amp;rest short-sides) (sort (list a b c) #'&gt;) (= (expt long-side 2) (+ (expt (first short-sides) 2) (expt (second short-sides) 2))))) (defun status-message (message a b c) (format t "The shape ~d,~d,~d ~a ~%" a b c message)) (defun classify-triangle (a b c) (cond ((not (triangle-p a b c))) ((right-triangle-p a b c) 'right) ((equilateral-p a b c) 'equilateral) ((isoceles-p a b c) 'isoceles) (t 'triangle))) (let* ((a (read-side 1)) (b (read-side 2)) (c (read-side 3)) (triangle-type (classify-triangle a b c))) (format t "classify triangle says ~a ~%" triangle-type) (cond ((eq 'right triangle-type) (status-message "is a right triangle." a b c)) ((eq 'equilateral triangle-type) (status-message "is an equilateral triangle." a b c)) ((eq 'isoceles triangle-type) (status-message "is an isoceles triangle." a b c)) ((eq 'triangle triangle-type) (status-message "is a non-right, non-isoceles, non-equilateral triangle." a b c)) (t (status-message "is not a triangle." a b c)))) </code></pre> <p>After reading through your suggestion on my sorting question and then reading up on 'format', I tried to write a format statement to simplify the logic at the bottom of the code. I couldn't figure out how to do a format conditional based on a symbol, so instead I defined the triangle types as global variables with 'defineparameter' (is there a better way to define constants?). I also used the format loop which you described in your response to the my-sort-3 question to shorten the expression. The new code is as follows:</p> <pre><code>(defparameter *right* 0) (defparameter *equilateral* 1) (defparameter *isoceles* 2) (defparameter *triangle* 3) (defparameter *non-triangle* 4) (defun read-side (side) (format t "Enter a value for side ~d: ~%" side) (read)) (defun triangle-p (a b c) (and (&lt; a (+ b c)) (&lt; b (+ a c)) (&lt; c (+ a b)))) (defun equilateral-p (a b c) (= a b c)) (defun isoceles-p (a b c) (or (= a b) (= b c) (= a c))) (defun right-triangle-p (a b c) (destructuring-bind (long-side &amp;rest short-sides) (sort (list a b c) #'&gt;) (= (expt long-side 2) (+ (expt (first short-sides) 2) (expt (second short-sides) 2))))) (defun status-message (message a b c) (format t "The shape ~d,~d,~d ~a ~%" a b c message)) (defun classify-triangle (a b c) (cond ((not (triangle-p a b c)) *non-triangle*) ((right-triangle-p a b c) *right*) ((equilateral-p a b c) *equilateral*) ((isoceles-p a b c) *isoceles*) (t *triangle*))) (let* ((a (read-side 1)) (b (read-side 2)) (c (read-side 3)) (triangle-type (classify-triangle a b c))) (format t "classify triangle says ~a ~%" triangle-type) (format t "The shape (~{~d~^, ~}) is ~[a right~;an equilateral~;an isoceles~;a non-right, non-isoceles, non-equilateral~;not a~] triangle." (list a b c) triangle-type)) </code></pre> <p>Thanks, everyone, for your continued feedback. Here is the latest revision.</p> <pre><code>(defun read-side (side) (format t "Enter a value for side ~d: ~%" side) (read)) (defun triangle-p (a b c) (and (&lt; a (+ b c)) (&lt; b (+ a c)) (&lt; c (+ a b)))) (defun equilateral-p (a b c) (= a b c)) (defun isoceles-p (a b c) (or (= a b) (= b c))) (defun right-triangle-p (a b c) (destructuring-bind (long-side short-side-1 short-side-2) (sort (list a b c) #'&gt;) (= (expt long-side 2) (+ (expt short-side-1 2) (expt short-side-2 2))))) (defun status-message (message a b c) (format t "The shape ~d,~d,~d ~a ~%" a b c message)) (defun classify-triangle (a b c) (cond ((not (triangle-p a b c)) nil) ((right-triangle-p a b c) 'right) ((equilateral-p a b c) 'equilateral) ((isoceles-p a b c) 'isoceles) (t 'triangle))) (let* ((a (read-side 1)) (b (read-side 2)) (c (read-side 3)) (triangle-type (classify-triangle a b c)) (article (if (member triangle-type '(isoceles equilateral)) "an" "a")) (tri-name (if (eq triangle-type 'triangle) "non-right, non-isoceles, non-equilateral" triangle-type))) (format t "The shape (~d, ~d, ~d) is ~:[not a triangle~;~a ~(~a~) triangle~]." a b c triangle-type article tri-name)) </code></pre>
[]
[ { "body": "<p>Keep in mind that every form in lisp returns something. <code>(and foo bar baz)</code> returns <code>nil</code> if <code>foo</code>, <code>bar</code> or <code>baz</code> evaluates to <code>nil</code>, and <code>t</code> if all of them evaluate to non-<code>nil</code>. This means that anywhere you write <code>(if (and ...) t nil)</code>, you can just write <code>(and ...)</code> with the same effect. The same applies to <code>(if (or ...) t nil)</code> and <code>(or ...)</code>, as well as <code>(if (= ...) t nil)</code> and <code>(= ...)</code>. Your <code>is-equilateral</code> is a particularly egregious violation of this; it can be written as simply </p>\n\n<pre><code>(defun equilateral-p (a b c) (= a b c))\n</code></pre>\n\n<hr>\n\n<p>The most common convention for predicates in Common Lisp is ending the function name with <code>p</code> or <code>-p</code>, rather than prefixing it with <code>is-</code> (personally, I end predicate names with <code>?</code>, in line with Scheme convention, but this is not the standard).</p>\n\n<hr>\n\n<p>Your <code>is-right-triangle</code> function can be simplified <strong>a lot</strong> by removing the stateful operations and using a more functional approach. I would have written it like so:</p>\n\n<pre><code>(defun right-triangle-p (a b c)\n (destructuring-bind (long-side &amp;rest short-sides) (sort (list a b c) #'&gt;)\n (= (expt large-side 2) \n (+ (expt (car short-sides) 2) (expt (cadr short-sides 2))))))\n</code></pre>\n\n<p>As a rule, whenever you use <code>loop</code> to assign values to intermediate variables through <code>setq</code>, double check that you need the loop at all. I've found that it's frequently (though not always) superfluous.</p>\n\n<p>EDIT: If you take my advice about defining your other assignment as a function, you can instead write</p>\n\n<pre><code>...\n(destructuring-bind (long-side &amp;rest short-sides) (my-sort-3 a b c)\n...\n</code></pre>\n\n<hr>\n\n<p>The final <code>let</code> structure can be simplified by using <code>cond</code> instead of nested <code>if</code>s, and slightly re-arranging the clauses.</p>\n\n<pre><code>(let ((a (read-side 1)) (b (read-side 2)) (c (read-side 3)))\n (cond ((not (triangle-p a b c)) (status-message \"is not a triangle.\" a b c))\n ((equilateral-triangle-p a b c) (status-message \"is an equilateral triangle.\" a b c))\n ((isoceles-triangle-p a b c) (status-message \"is an isoceles triangle.\" a b c))\n ((right-triangle-p a b c) (status-message \"is a right triangle.\" a b c))\n (t (status-message \"is a non-isoceles, non-equilateral, non-right triangle.\" a b c))))\n</code></pre>\n\n<hr>\n\n<p>You might want to re-write that final <code>let</code> statement as a function that returns a type of triangle (so like <code>'isoceles</code> instead of printing <code>\"The shape a,b,c is an isoceles triangle.\\n\"</code>) so that you can reuse it more easily. This is basically the same advice I gave you on your sorting function.</p>\n\n<hr>\n\n<p>On a slightly more general note, you might want to be explicit about which Lisp you're using. It's unambiguous in this case, since I'm pretty sure <code>loop</code> is a CL construct, but keep in mind that \"Lisp\" is a fairly large family of languages,</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T15:06:33.653", "Id": "1186", "ParentId": "1182", "Score": "2" } }, { "body": "<p>Much better.</p>\n\n<p>You seem to like assignment a bit more than I do, though. You can rewrite that last let as</p>\n\n<pre><code>(let* ((a (read-side 1)) (b (read-side 2)) (c (read-side 3)) (triangle-type (classify-triangle a b c)))\n (format t \"classify triangle says ~a ~%\" triangle-type)\n (cond ((eq 'right triangle-type) (status-message \"is a right triangle.\" a b c))\n ((eq 'equilateral triangle-type) (status-message \"is an equilateral triangle.\" a b c))\n ((eq 'isoceles triangle-type) (status-message \"is an isoceles triangle.\" a b c))\n ((eq 'triangle triangle-type) (status-message \"is a non-right, non-isoceles, non-equilateral triangle.\" a b c))\n (t (status-message \"is not a triangle.\" a b c))))\n</code></pre>\n\n<p><code>let*</code> is basically <code>let</code>, except that its arguments are guaranteed to be evaluated in the given order (which means that later bindings can refer to previous ones from the same <code>let*</code> statement). It's good style to use <code>let</code> where you can, but <code>let*</code> is better than creating a temporary <code>nil</code> binding and <code>setq</code>ing it later.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T02:27:09.637", "Id": "2115", "Score": "0", "body": "Thank you! let* seems like a very useful function to know about. When you say \"I like assignment,\" do you mean specifically using setq, or do you see another, better way to do this?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T02:44:34.403", "Id": "2116", "Score": "0", "body": "@jaresty - I mean assignment in general (yes, your use of `setq` is what prompted the comment). I remember not minding back in the day, but it seems that you can do the vast majority of things more cleanly and easily without it. It's still useful to have, but IMO, mainly as a tool of last resort." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T16:27:37.237", "Id": "1201", "ParentId": "1182", "Score": "3" } }, { "body": "<p>In response to the 4th edit, I was thinking something along the lines of</p>\n\n<pre><code>(let* ((a (read-side 1)) (b (read-side 2)) (c (read-side 3)) \n (triangle-type (classify-triangle a b c))\n (article (if (member triangle-type '(isoceles equilateral)) \"an\" \"a\"))\n (tri-name (if (eq triangle-type 'triangle) \"non-right, non-isoceles, non-equilateral\" triangle-type)))\n (format t \"The shape (~d, ~d, ~d) is ~:[not a triangle.~;~a ~(~a~) triangle~].\" a b c triangle-type article tri-name))\n</code></pre>\n\n<p>Rather than using global parameters, but that works too (it's not as though you'd use either option in actual code).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-10T00:58:59.017", "Id": "2140", "Score": "0", "body": "1. Why is it sufficient to write \"(if (member triangle-type '(isoceles equilateral) ... )\" rather than (if (member triangle-type '('isoceles 'equilateral) ... )\"?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-10T01:00:08.750", "Id": "2141", "Score": "0", "body": "and 2. What would you use in actual code?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-10T02:07:44.110", "Id": "2147", "Score": "0", "body": "1. `'` is actually just shorthand for `(quote ...)`. `quote` is a function that basically suppresses evaluation of its body (ie, it specifies that the things in it are to be treated as symbols rather than the values they would otherwise be reduced to). You do sometimes need to quote (and unquote) the components of a quoted form, but that's typically done in macros. As part of regular functions, it's mostly enough to have a single level of quoting because that first `'` also suppresses a level of evaluation on the contents of the form its applied to." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-10T02:16:39.547", "Id": "2148", "Score": "0", "body": "2. The code above is a top-level `let*`, and contains a complex format directive with wordy messages. I'd this at the `repl` to test out a function, but it's not the sort of code I would check in. \"Actual code\" (by which I mean \"production code\") would be a named function (like `test-triangle-utility`), have brief comments explaining the tricky parts, wouldn't put `format` through its paces, have a set of defined test arguments instead of `read`ing them from the user, and output a list of `'(input result pass/fail)` (as you can see by the article clause, English output complicates things)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T16:25:46.387", "Id": "1214", "ParentId": "1182", "Score": "2" } }, { "body": "<p>(In response to your 4th edit)</p>\n\n<p>You can simplify right-triangle-p by doing more work in the destructuring:</p>\n\n<pre><code>(defun right-triangle-p (a b c)\n (destructuring-bind (x y z) (sort (list a b c) #'&gt;)\n (= (expt z 2) (+ (expt y 2) (expt x 2)))))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T17:09:44.300", "Id": "2135", "Score": "2", "body": "Psst. Other way round (or sort using `#'<`)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T16:37:00.197", "Id": "1215", "ParentId": "1182", "Score": "1" } }, { "body": "<p>I think if you enter floating point values, your program might not work as expected. You shouldn't do comparison with =, if the numbers are float.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-04T01:05:07.197", "Id": "3277", "ParentId": "1182", "Score": "1" } } ]
{ "AcceptedAnswerId": "1201", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T04:23:33.903", "Id": "1182", "Score": "4", "Tags": [ "lisp", "common-lisp" ], "Title": "Determine type of triangle in LISP" }
1182
<p>I want to create delegates to access properties of different objects without knowing them in advance.</p> <p>I have the following definitions</p> <pre><code>public delegate T MyMethod&lt;K, T&gt;(K data); public static MyMethod&lt;K, T&gt; CreatePropertyGetter&lt;K, T&gt;(PropertyInfo property) { MethodInfo mi = property.DeclaringType.GetMethod("get_" + property.Name); return (MyMethod&lt;K, T&gt;)Delegate.CreateDelegate(typeof(MyMethod&lt;K, T&gt;), mi); } </code></pre> <p>where T can be decimal, string, datetime or int</p> <p>I have some initializing code that will create MyMethod delegates, based on the reflected properties of my object as follows:</p> <pre><code>foreach (PropertyInfo property in entityType.GetProperties()) { switch (property.PropertyType.Name) { case "System.Decimal": return CreatePropertyGetter&lt;T, decimal&gt;(property); case "System.DateTime": return CreatePropertyGetter&lt;T, DateTime&gt;(property); case "System.String": return CreatePropertyGetter&lt;T, DateTime&gt;(property); } } </code></pre> <p>Is there a better way to</p> <ol> <li>create property getters?</li> <li>enumerate through the supported property types hard-coded as strings?</li> </ol> <p>However, performance is an issue, since these delegates will be called frequently (ticking scenario), so any casting will slow it down. While a more elegant solution is desirable, performance is still my main concern</p>
[]
[ { "body": "<p>One suggestion is to create type -> type map of all the types you want to support instead of making a switch statement on strings.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T19:47:25.577", "Id": "2085", "Score": "0", "body": "Except you can't pass the result of a map lookup as a generic parameter." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T19:14:38.163", "Id": "1189", "ParentId": "1188", "Score": "0" } }, { "body": "<p>As <a href=\"https://stackoverflow.com/questions/5221904/best-practice-instantiating-generic-delegates-and-accessing-property-getters/5222042#5222042\">my answer on Stack Overflow states</a>, there is a solution which allows you to create a getter delegate for any type, so the entire switch block can be dropped. Personally, I find that the cleanest solution. The only overhead of this approach is the cast from object to the specific type where necessary. (For a getter this would happen only once on the return value.) I'm guessing if you would benchmark this, the result would be negligible.</p>\n\n<p>When you are certain that the only types required are those specified, or that no new types are expected very often, you could still opt to use your current approach. I would apply a few changes however:</p>\n\n<ol>\n<li>Use <a href=\"http://msdn.microsoft.com/en-us/library/e17dw503.aspx\" rel=\"nofollow noreferrer\">PropertyInfo.GetGetMethod()</a> to retrieve your MethodInfo for the getter.</li>\n<li>Use the type of PropertyType directly to determine which CreatePropertyGetter to call instead of the name of the type.</li>\n<li>Use <a href=\"http://msdn.microsoft.com/en-us/library/bb549151.aspx\" rel=\"nofollow noreferrer\"><code>Func&lt;K, T&gt;</code></a> instead of <code>MyMethod</code>.</li>\n<li>Use a Dictionary holding anonymous functions which create the correct delegate for the specified type of the key. This can replace the switch statement.</li>\n</ol>\n\n<p>The last point is possible as follows:</p>\n\n<pre><code>Dictionary&lt;Type, Func&lt;PropertyInfo, object&gt;&gt; getterCreators =\n new Dictionary&lt;Type, Func&lt;PropertyInfo, object&gt;&gt;\n {\n { typeof(string), p =&gt; CreatePropertyGetter&lt;T, string&gt;(p) },\n { typeof(DateTime), p =&gt; CreatePropertyGetter&lt;T, DateTime&gt;(p) },\n { typeof(decimal), p =&gt; CreatePropertyGetter&lt;T, decimal&gt;(p) }\n };\n</code></pre>\n\n<p>Ofcourse you still have to cast from object to the desired type.</p>\n\n<p>UPDATE:</p>\n\n<p>As Timwi pointed out in the comments, <code>p =&gt; CreatePropertyGetter&lt;T, ...&gt;(p)</code> can be further reduced to: <code>CreatePropertyGetter&lt;T, ...&gt;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T14:20:04.140", "Id": "2105", "Score": "1", "body": "Instead of `p => CreatePropertyGetter<T, string>(p)`, I would recommend to write just `CreatePropertyGetter<T, string>`." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T14:28:02.417", "Id": "2106", "Score": "0", "body": "@Timwi: Cool, didn't know that worked." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T19:59:22.320", "Id": "1190", "ParentId": "1188", "Score": "7" } } ]
{ "AcceptedAnswerId": "1190", "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-07T18:59:10.373", "Id": "1188", "Score": "6", "Tags": [ "c#", ".net" ], "Title": "Best practice instantiating generic delegates and accessing property getters" }
1188
<p><a href="https://stackoverflow.com/questions/5212640/rails-how-to-create-different-views/5212690#5212690">I answered a question in stackoverflow</a> but I gave a solution that looks a little dirty to me, I'd like your opinion because I think there is a much smarter way to do it.</p> <p>A <strong>guest</strong> user should be able to choose between two different view modalities.</p> <p>My approach was to implement an action and store the choice in the session. I paste some relevant code here as well:</p> <pre><code> # application_controller.rb def set_view_type # TODO: here is the part I don't like session[:view_type] = params[:view_type] redirect_to :back end # x_controller.rb def index case session[:view_type].to_sym when :box render 'index_box' else render 'index_list' end end </code></pre> <p>Then I use two <code>link_to</code> (instead of <code>radiobutton</code> as in stackoverflow) to choose the view, and those should be visible anytime in the layout, this is why I use <code>application_controller</code> for that.</p> <p>PS: <em>I don't know if it's correct to ask for a question that it's still open in SO, feel free to answer straight there by me, I just think here I'm posting my solution that I would like to be revised.</em></p>
[]
[ { "body": "<p>For the part you do not like, you can set a before_filter in ApplicationController. Therefore a redirect will not be necessary. Selection form can resubmit to the current page with \"view_type\" parameter.</p>\n\n<pre><code>#application_controller.rb\nbefore_filter :check_view_type, :only =&gt; [:index]\n\ndef check_view_type\n session[:view_type] = params[:view_type] if params[:view_type].present?\nend\n</code></pre>\n\n<p>For this specific example I would prefer layout and partial views. It is well described in <a href=\"http://guides.rubyonrails.org/action_view_overview.html#layouts\" rel=\"nofollow\">Rails guides</a>.</p>\n\n<pre><code>#x/index.html.erb\nrender :partial =&gt; 'item', :layout =&gt; current_layout, :collection =&gt; @items\n\n#application_controller.rb\nhelper_method :current_layout\n\ndef supported_layouts\n [nil]\nend \n\ndef current_layout \n supported_layouts.include? session[:view_type] ? session[:view_type] : supported_layouts.first\nend\n\n#x_controller.rb\ndef supported_layouts \n %w[box list]\nend \n\ndef index\n # only index logic \nend \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-25T16:28:56.530", "Id": "16441", "Score": "0", "body": "very neat! that's why I love rails. - thanks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-25T13:37:31.960", "Id": "10319", "ParentId": "1192", "Score": "2" } } ]
{ "AcceptedAnswerId": "10319", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-07T20:33:02.680", "Id": "1192", "Score": "6", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "How to manage different views" }
1192
<p>I've got three tables I need query to display to a user for a web application I've written. Each table (Url, Note, Quote) has a foreign key relation to the User table. For every User, I need to sort all Bookmarks, Notes and Quotes based on a _date_created_ field, then deliver that to the template as one iterable. This is for a toy/self-learning project so I don't really need to worry about scale.</p> <p>The approach I've taken is this:</p> <pre><code>from operator import attrgetter from app.models import Url, Note, Quote date_dict = {} for url in Url.objects.filter(user=request.user): date_dict[url.date_created] = Url.objects.get(date_created=url.date_created) for note in Note.objects.filter(user=request.user): date_dict[note.date_created] = Note.objects.get(date_created=note.date_created) for quote in Quote.objects.filter(user=request.user): date_dict[quote.date_created] = Quote.objects.get(date_created=quote.date_created) my_query = sorted((date_dict[i] for i in date_dict.iterkeys()), key=attrgetter("date_created"), reverse=True) </code></pre> <p>I have also tried this:</p> <pre><code>from operator import attrgetter from itertools import chain from app.models import Url, Note, Quote items = sorted(chain(Url.objects.filter(user=request.user), Note.objects.filter(user=request.user), Quote.objects.filter(user=request.user)), key=attrgetter("date_created"), reverse=True) </code></pre> <p>I'm concerned how expensive this would get if I had huge data sets (I don't), but from what I've read the second is faster.</p> <p>This code works and does what I expect it to, but is there a better/faster approach?</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T05:32:28.283", "Id": "2095", "Score": "0", "body": "You state that you want a sorted version, but nothing in your code sorts it. You also mention users being involved, but there are no users in your example code." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T05:53:33.890", "Id": "2097", "Score": "0", "body": "@Winston Ewert: I've revised my code to better reflect my question." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T05:59:03.127", "Id": "2098", "Score": "0", "body": "Your current version will produce a bunch of None entries in the list. Also, it'll only count item for any particular date. I assume thats not what you want?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T06:07:22.687", "Id": "2099", "Score": "0", "body": "@Winston Ewert: Hm, well, I've revised it to actually reflect what I've been doing in iPython, and I'm not getting any None-type responses. How would it produce a value of None?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T06:08:25.600", "Id": "2100", "Score": "0", "body": "the current version won't. A previous version looked like it would." } ]
[ { "body": "<p><strong>EDIT</strong> Removed previous version which was pretty much telling you to use the second method shown above. Your first method loads everything from the database twice. (Django may do some caching, but still) I'm not sure why you are putting everything in the dictionary.</p>\n\n<p>The problem with the current implementation is that sorting is done by python rather then in the database. It would be better to have the sorting done in the database. There are two ways I see of doing that.</p>\n\n<ol>\n<li><p>You could have the three different sources sorted by the database. Then you could perform a merge pass to combine them. However, you are probably going to have need a lot of data before that becomes a worthwhile strategy. Sorting will be implemently in C for python which will make it have a speed advantage over a merge which you would have to implement in python. </p></li>\n<li><p>You could redesign your database so Urls, Quotes, and Notes are stored in the same table. That way you could request the database to sort them. </p></li>\n</ol>\n\n<p>Both of these strategies are really only helpful if you end up with a lot of data. If you have that much data you aren't going to want to present it all to the user anyways. The result is that its probably not useful.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T16:39:58.033", "Id": "2107", "Score": "0", "body": "Winston, thanks. #2 is what I'll be going for. I was using an abstract model for all the objects (which in Django is just a code reuse tool), but I'll be migrating over to a model somewhat like you described here." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T05:34:14.350", "Id": "1195", "ParentId": "1194", "Score": "1" } } ]
{ "AcceptedAnswerId": "1195", "CommentCount": "5", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T05:18:13.247", "Id": "1194", "Score": "4", "Tags": [ "python", "django" ], "Title": "Three-table queryset (full outer join?) in Django" }
1194
<p>I had a file that looked like this:</p> <pre><code>Mar 06 22:00:00 [10.251.132.246] logger: 10.64.69.219 - - [06/Mar/2011:22:..... Mar 06 22:00:00 [10.251.132.246] logger: 10.98.137.116 - - [06/Mar/2011:22:0.... </code></pre> <p>that I wanted to split into smaller files using the ip address after "logger"</p> <p>This is what I came up with:</p> <pre><code>file = ARGV.shift split_file = {} pattern = /logger: ([^\s]*)/ File.open(file, 'r') do |f| f.each do |l| match = l[pattern] if match list = split_file[$1] list = [] if list == nil list &lt;&lt; l split_file[$1] = list end end end split_file.each_pair do |k, v| File.open("#{file}.#{k}", "a+") do |f| v.each do |l| f.print l end end end </code></pre> <p>Suggestions, warnings, improvements are very welcome :)</p> <p>One thing I noticed is that the new files are created in the same directory as the original file, not at the current working directory (so ./logsplitter.rb ../log.log creates files in the .. directory).</p> <p>Thank you</p> <p>[edit: typo]</p>
[ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T14:08:25.693", "Id": "2104", "Score": "2", "body": "Do you mind me asking why you'd want to split log files this way? It looks like you want to have a log per IP instead of one giant log. Is this for documentation purposes? Do you just want a way of checking all access for a particular IP?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T23:30:18.643", "Id": "2110", "Score": "0", "body": "I needed to split the log per ip for further analysis and thought ruby would be the easiest way to do it.. for me at least :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T00:16:41.333", "Id": "2113", "Score": "1", "body": "@Dale - Ok, yes I got that, but I meant, \"what kind of analysis?\". If you're just looking to check up on a specific IP, for example, `cat log.log | grep 10.64.69.210` is a better approach than a splitting script (if you want a count of how many times they visited, pipe the output of that through `wc -l`). If you just want a list of unique IPs that visited, then `awk '{print $6}' log.log | sort -u` might be enough for you (again, pipe `wc` to taste). I'm asking to see if a ruby script (which you will now need to maintain) is actually the best solution for you." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T00:54:45.140", "Id": "2114", "Score": "0", "body": "Revised result (heavily cut down) : https://bitbucket.org/dwijnand/logsplitter/src/999b61673f65/logsplitter.rb" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T07:04:28.953", "Id": "2123", "Score": "0", "body": "@Inaimathi sorry didn't see your comment. It was to see try and follow what was going on for specific ips. Yes I could have hand-picked a few and grep them into individual files, but this was simple enough (and a nice excercise) to warrant a ruby script :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-01T02:48:26.570", "Id": "2772", "Score": "0", "body": "Personally, I'd recommend splitting each record into its component fields, then store it all in a database for crunching. There's all sorts of good data-mining to be had from a log file if you know how to look at it. Even if you don't have a good use, knowing how to parse and store the data can pay off. Once the fields are in the database it becomes very easy to group and summarize things." } ]
[ { "body": "<p>First of all it is a pretty wide-spread convention in ruby to use 2 spaces for indendation not 4. Personally I don't care, but there are some ruby developers who will complain when seeing code indented with 4 spaces, so you'll have an easier time just going with the stream.</p>\n\n<hr>\n\n<pre><code>file = ARGV.shift\n</code></pre>\n\n<p>Unless there is a good reason to mutate <code>ARGV</code> (which in this case doesn't seem to be the case), I'd recommend not using mutating operations. <code>file = ARGV[0]</code> will work perfectly fine here.</p>\n\n<hr>\n\n<pre><code>match = l[pattern]\nif match\n list = split_file[$1]\n list = [] if list == nil\n list &lt;&lt; l\n split_file[$1] = list\nend\n</code></pre>\n\n<p>First of all you should avoid using magic variables. Using MatchData objects is more robust than using magic variables. As an example consider this scenario:</p>\n\n<p>Assume that you decide you want to do some processing on the line before storing it in <code>split_file</code>. For this you decide to use gsub. Now your code looks like this:</p>\n\n<pre><code>match = l[pattern]\nif match\n list = split_file[$1]\n list = [] if list == nil\n list &lt;&lt; l.gsub( /some_regex/, \"some replacement\")\n split_file[$1] = list\nend\n</code></pre>\n\n<p>However this code is broken. Since <code>gsub</code> also sets <code>$1</code>, <code>$1</code> now no longer contains what you think it does and <code>split_file[$1]</code> will not work as expected. This kind of bug can't happen if you use <code>[1]</code> on a match data object instead.</p>\n\n<p>Further the whole code can be simplified by using a very useful feature of ruby hashes: default blocks. Hashes in ruby allow you to specify a block which is executed when a key is not found. This way you can create hash of arrays which you can just append to without having to make sure the array exists.</p>\n\n<p>For this you need to change the initialization of <code>split_file</code> from <code>split_file = {}</code> to <code>split_file = Hash.new {|h,k| h[k] = [] }</code>. Then you can replace the above code with:</p>\n\n<pre><code>match = l.match(pattern)\nif match\n split_file[ match[1] ] &lt;&lt; l\nend\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>One thing I noticed is that the new files are created in the same directory as the original file, not at the current working directory (so ./logsplitter.rb ../log.log creates files in the .. directory).</p>\n</blockquote>\n\n<p>If you want to avoid that use <code>File.basename</code> to extract only the name of the file without the directory from the given path and then build the path of the file to be created from that. I.e.:</p>\n\n<pre><code>File.open(\"#{ File.basename(file) }.#{k}\", \"a+\") do |f|\n</code></pre>\n\n<p>Speaking of this line: I don't see why you use \"a+\" instead of just \"a\" as the opening mode - you never read from it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T23:33:55.753", "Id": "2111", "Score": "0", "body": "Thanks sepp2k, great great tips! I thought I remembered something about default blocks in hashes.. there we go :)\n\nThanks again, accepting." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T23:54:33.477", "Id": "2112", "Score": "0", "body": "Oh, one mistake however. Using the square brackets that way does something different.\n\nThe following:\n\n`match = l[pattern]`\n`split_file[match[1]] << l if match`\n\nmust be replaced with:\n\n`match = l[pattern,1]`\n`split_file[match] << l if match`\n\nOr using Regexp.match(str) instead..." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T12:28:47.940", "Id": "2132", "Score": "0", "body": "@Dale: True. I somehow did not notice that you were using `[]` and not `match`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T15:15:41.740", "Id": "1200", "ParentId": "1196", "Score": "4" } } ]
{ "AcceptedAnswerId": "1200", "CommentCount": "6", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T07:18:26.540", "Id": "1196", "Score": "7", "Tags": [ "ruby" ], "Title": "Splitting log file into smaller files" }
1196
<p>I have a <code>std::set&lt;std::string&gt;</code> and I need to know the total number of characters (sum of all strings length):</p> <pre><code>static size_t SumLength(size_t value, const std::string &amp;str) { return str.length() + value; } size_t TotalLength(std::set&lt;std::string&gt; &amp;stringSet) { return std::accumulate(stringSet.begin(), stringSet.end(), 0, SumLength); } </code></pre> <p>What do you think of this approach?</p>
[]
[ { "body": "<p>You should make the parameter to <code>TotalLength</code> const, so you can use it on constant sets. Since <code>TotalLength</code> does not modify its argument, there is no reason not to use a const reference.</p>\n\n<p>Also this is a small thing, but I'd change the name of <code>SumLength</code> to <code>AddLength</code> as <code>Sum</code> to me suggests that it operates on multiple strings.</p>\n\n<p>Other than that your code looks perfectly fine and straight forward.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T17:29:29.687", "Id": "2109", "Score": "0", "body": "Good catch about the const and nice comment about the function name. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T14:31:58.970", "Id": "1199", "ParentId": "1198", "Score": "9" } }, { "body": "<p>If you want to improve the locality of reference of the code you might replace SumLength with a lambda function. This would prevent future maintainers/etc from putting lots of code between SumLength and TotalLength. The drawback would be that you'd lose the ability to call SumLength by another function outside of TotalLength.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T14:11:05.230", "Id": "62279", "Score": "0", "body": "Thanks, but no lambda on the current compiler that I have to use :(." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T23:14:17.013", "Id": "37265", "ParentId": "1198", "Score": "2" } } ]
{ "AcceptedAnswerId": "1199", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-08T14:18:45.670", "Id": "1198", "Score": "6", "Tags": [ "c++" ], "Title": "Counting the total number of characters in an std::set<std::string>" }
1198
<p>I'm working on a network monitoring application, that pings an unknown number of hosts. I've made a class <code>PingHost</code> with a function <code>zping</code> and I called it with the help of a timer once every 2 seconds to let the 2 pings to finish, even if one of them gets <code>TimedOut</code>. But I think a better solution is to generate a new thread for every ping, so that the ping of every host would be independent.</p> <p>Can anyone give me a hint how to do this?</p> <pre><code>namespace pinguin { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void timer1_Tick(object sender, EventArgs e) { PingHost caca = new PingHost(); PingHost caca1 = new PingHost(); this.label1.Text = caca.zping("89.115.14.160"); this.label2.Text = caca1.zping("89.115.14.129"); } } </code></pre> <hr> <pre><code> public class PingHost { public string zping(string dest) { Application.DoEvents(); Ping sender = new Ping(); PingOptions options = new PingOptions(); options.DontFragment = true; string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; byte[] buffer = Encoding.ASCII.GetBytes(data); int timeout = 50; int failed = 0; int pingAmount = 5; string stat = ""; PingReply reply = sender.Send(dest, timeout, buffer, options); if (reply.Status == IPStatus.Success) { stat = "ok"; } else { stat = "not ok!"; } return stat; } } } </code></pre>
[]
[ { "body": "<p>You can use <code>SendAsync</code>:</p>\n\n<pre><code>sender.PingCompleted += new PingCompletedEventHandler (PingCompletedCallback);\nsender.SendAsync(dest, timeout, buffer, options, textLabel);\n</code></pre>\n\n<p>And the callback:</p>\n\n<pre><code>private static void PingCompletedCallback (object label, PingCompletedEventArgs e)\n{\n if (e.Reply.Status == IPStatus.Success)\n {\n label.Text = \"ok\";\n }\n else\n {\n label.Text = \"not ok!\";\n }\n}\n</code></pre>\n\n<p>Disclaimer: I haven't run this code. I believe the delegate will be able to access the label, but I've had issues with it in the past. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T07:23:43.887", "Id": "2124", "Score": "2", "body": "The callback should not update the control directly, it should use Control.Invoke() or Control.BeginInvoke() to have the UI thread do the update. Also, its \"SendAsync\" not \"SendAsynch\" :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T09:42:48.850", "Id": "2128", "Score": "0", "body": "Although it might not hurt to do a InvokeRequired check, I don't believe that would be necessary. The calling thread will be the one receiving the callback. Unless a separate thread has been spawned which is then spawning all these ping requests (unlikely), the update will already be in the UI thread.." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T11:09:28.457", "Id": "2129", "Score": "0", "body": "@Mongus Pong: The documentation for SendAsync states that it uses a thread from the thread pool (http://msdn.microsoft.com/en-us/library/0e6kc029.aspx - under Remarks). Even if it didn't use the thread pool, the only way the event can be raised on the GUI thread is if the Ping object were able to find and somehow attach to a message loop for the creating thread, I imagine this is the sort of thing Microsoft would hi-light in the documentation if they did (they already hi-light the association between a Control and it's creating thread in the documentation)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T11:13:50.963", "Id": "2130", "Score": "0", "body": "@Mongus Pong: I do however agree that InvokeRequired should be checked unless it is known for sure that you are in a different thread." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T12:05:06.473", "Id": "2131", "Score": "0", "body": "@Brian: Yes you are right. I'm not quite sure what is going on - if I check InvokeRequired in the PingCompletedCallback method, I get false. However, if I register a delegate with ThreadPool.RegisterWaitForSingleObject (which is what Ping uses) and check InvokeRequired, I get true. Voodoo..." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-10T08:13:19.087", "Id": "2157", "Score": "0", "body": "@Mongus Pong: I did some testing and it seems I owe you an apology, the Ping object does marshal the call to the UI thread via the message loop. Interestingly, if SendAsync is called from a thread other than the UI thread, it appears to block indefinitely even though the message is sent and the response is processed by the event handler." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-10T08:19:44.827", "Id": "2158", "Score": "0", "body": "@Michael K: I would be happy to suggest an edit, but I think it's a bit moot now :)" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-10T13:41:05.897", "Id": "2165", "Score": "0", "body": "@Brian: That's fine, it's what the site's for!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-08T18:32:47.360", "Id": "1203", "ParentId": "1202", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-08T16:50:51.400", "Id": "1202", "Score": "7", "Tags": [ "c#", "multithreading", "networking" ], "Title": "Multithreaded host pinging application" }
1202
<p>I wondering what people think of this game of life. I don't think it is working properly, but I am interesting in what people think of the general design.</p> <pre><code>module GameOfLife where import Data.List --Our types type Coord = (Int, Int) origin = (0, 0) --Think of an image more like an infinite manifold type DiscreteImage a = (Coord -&gt; a) --Cat is our "out of bounds" data GamePiece = Alive | Dead | Cat deriving(Show, Eq) type GameBoard = DiscreteImage GamePiece type TransitionRule = (GameBoard -&gt; GamePiece) under_population = make_population_transition Alive Dead (&lt;2) overcrowding = make_population_transition Alive Dead (&gt;3) birth = make_population_transition Dead Alive (==3) --Order is not important. Only one transition applies per peice, --the others operate like id transition_rule :: TransitionRule transition_rule image = foldl (\image f -&gt; f image) image [ under_population, overcrowding, birth ] origin --return a new gameboard that applies the transition rule to every --spot on the gameboard step :: TransitionRule -&gt; GameBoard -&gt; GameBoard step trans gb = trans . offset gb --apply the tranisition rule n number of times simulate :: Int -&gt; TransitionRule -&gt; GameBoard -&gt; GameBoard simulate count trans gb = foldl apply_step gb steps where steps = replicate count (step trans) apply_step gb s = s gb --translate the image offset :: DiscreteImage a -&gt; Coord -&gt; Coord -&gt; a offset image (offsetX, offsetY) (x, y) = image (offsetX + x, offsetY + y) --make a square of coords square_coords :: Int -&gt; [Coord] square_coords radius = [(x, y) | x &lt;- diameter_list, y &lt;- diameter_list] where diameter_list = [(negate radius) .. radius] --return a neighborhood with the center missing punctured_neighborhood :: Int -&gt; DiscreteImage a -&gt; [a] punctured_neighborhood size image = map image $ filter (not . (==origin)) $ square_coords size --a little test main = do let (width, height) = get_bounds test_list let board1 = simulate 1 transition_rule test_board putStr $ unlines [ unwords [ ppr_peice $ board1 (x, y) | x &lt;- [0..(width -1)]] | y &lt;- [0..(height - 1)]] test_list = [ [Alive, Dead, Alive, Dead], [Alive, Dead, Dead, Alive], [Dead, Alive, Dead, Alive], [Dead, Alive, Alive, Alive] ] test_board = image_from_lists test_list Cat --helpers population_count = length . filter is_Alive . punctured_neighborhood 1 --does nothing if the origin peice /= from, otherwise test for replacement make_population_transition from to condition image | image origin == from = if (condition . population_count) image then replace image origin to else image make_population_transition from to test image | otherwise = image replace image coord_to_replace value coord = if coord_to_replace == coord then value else image coord bi f g h x = f x `h` g x is_Alive Alive = True is_Alive _ = False from_Bool True = Alive from_Bool False = Dead image_from_lists xs default_value coord@(x, y) = if is_in_bounds1 coord then (xs !! x) !! y else default_value where bounds = get_bounds xs is_in_bounds1 = is_in_bounds bounds get_bounds xs = if null xs then (0, 0) else (length xs, length $ head xs) is_in_bounds (xb, yb) (x, y) = (y &lt; yb &amp;&amp; y &gt; -1) &amp;&amp; (x &lt; xb &amp;&amp; x &gt; -1) ppr_peice Dead = "O" ppr_peice Alive = "X" ppr_peice Cat = "C" </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T07:21:11.207", "Id": "28081", "Score": "0", "body": "Have a look at [Evaluating cellular automata is comonadic](http://blog.sigfpe.com/2006/12/evaluating-cellular-automata-is.html). Using comonads could nicely simplify the game design." } ]
[ { "body": "<p>First, arranging your code from top to bottom level or vice versa would make this a little easier to read. Also, Haskell code formatting custom generally uses casing like <code>someThing</code> rather than <code>some_thing</code>.</p>\n\n<p>There are also a few items that could be more simply defined (or not at all):</p>\n\n<pre><code>isAlive = (==Alive)\nbi = Data.Function.on\ntranisitionRule = foldr (.) [underPopulation, overcrowding, birth]\n</code></pre>\n\n<p>Consider using <a href=\"http://www.haskell.org/hoogle/\">Hoogle</a> to check if something already exists so you don't need to redefine it.</p>\n\n<p>I think keeping the rule as a single function without spreading it too thinly over your code would be a good idea. For the<code>main</code> function, try to keep it as uninvolved with the pure code as possible.</p>\n\n<p>On the idea of an infinite board, you should consider using a zipper of some sort. This is a simple data structure that separates another data structure into pieces to allow movement inside, rather than storing a path to the current element and changing that. For example,</p>\n\n<pre><code>toZipper xs = ([],xs)\ncurrent (_,x:_) = x\nleft (x:ls,rs) = (ls,x:rs)\nright (ls,x:rs) = (x:ls,rs)\nunzipper (ls,rs) = reverse ls ++ rs\n</code></pre>\n\n<p>These functions operate with a zipper that represents the elements at and beyond the current position and the elements behind the current position as a pair. To represent something that is infinite in one direction is trivial (<code>([],repeat 0)</code>, a ray), as would be something that is infinite in two directions (<code>(repeat 0,repeat 0)</code>, a line). Of course, this particular zipper can be made safer with <code>Maybe</code> and other things, but I'm just demonstrating the concept.</p>\n\n<p>Hopefully, you can see that this can now be extended to a two-directional infinite zipper of two-directional infinite zippers, effectively giving you a two-dimensional plane! Here is the line and plane, in terms of a point:</p>\n\n<pre><code>line = (repeat point, repeat point)\nplane = (repeat line, repeat line)\n</code></pre>\n\n<p>This pattern can be extended to any number of dimensions, but in the specific case of the Game of Life, the plane should suffice. For the purposes of printing, you can create a 5-tuple zipper along the lines of <code>(untraversed left elements, traversed left elements, current element, traversed right elements, untraversed right elements)</code>, so you only print the relevant elements. From what I can glean from your code, the zipper pattern is not unlike what you are doing right now, so it shouldn't be too hard to implement. It's also good to abtract the zipper pattern somehow in another module for future use. Even if your plane won't be infinite, try using a zipper.</p>\n\n<p>I'll think I'll stop here for the sake of length. Please ask questions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-29T18:28:36.783", "Id": "2701", "ParentId": "1204", "Score": "10" } }, { "body": "<p>Refactor's answer is excellent and captures most points. One thing in your code which sticks out is the overuse of <code>if</code>. E.g. consider</p>\n\n<pre><code>get_bounds xs = if null xs\n then (0, 0)\n else (length xs, length $ head xs)\n</code></pre>\n\n<p>I think</p>\n\n<pre><code>getBounds [] = (0,0)\ngetBounds xs = (length xs, length $ head xs)\n</code></pre>\n\n<p>is much clearer. Or this, which looks really strange:</p>\n\n<pre><code>make_population_transition from to condition image | image origin == from = \n if (condition . population_count) image \n then replace image origin to \n else image\nmake_population_transition from to test image | otherwise = image\n</code></pre>\n\n<p>You should write</p>\n\n<pre><code>make_population_transition from to condition image \n | image origin == from &amp;&amp; \n (condition . population_count) image = replace image origin to \n | otherwise = image\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-05-30T06:44:57.043", "Id": "2707", "ParentId": "1204", "Score": "11" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T03:42:59.360", "Id": "1204", "Score": "11", "Tags": [ "haskell", "game-of-life" ], "Title": "Game of Life in Haskell" }
1204
<p>In C++, to simplify string conversion between <code>std::string</code> and <code>std::wstring</code>, I created the following utility template functions:</p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;string&gt; #include &lt;cstring&gt; #include &lt;cwchar&gt; #include &lt;cassert&gt; template&lt;typename Td&gt; Td string_cast( const char* pSource, unsigned int codePage = CP_ACP ); template&lt;typename Td&gt; Td string_cast( const wchar_t* pSource, unsigned int codePage = 1200 ); template&lt;typename Td&gt; Td string_cast( const std::string&amp; source, unsigned int codePage = CP_ACP ); template&lt;typename Td&gt; Td string_cast( const std::wstring&amp; source, unsigned int codePage = 1200 ); template&lt;&gt; std::string string_cast( const char* pSource, unsigned int codePage ) { assert( pSource != 0 ); return std::string( pSource ); } template&lt;&gt; std::wstring string_cast( const char* pSource, unsigned int codePage ) { assert( pSource != 0 ); std::size_t sourceLength = std::strlen( pSource ); if( sourceLength == 0 ) { return std::wstring(); } int length = ::MultiByteToWideChar( codePage, 0, pSource, sourceLength, NULL, 0 ); if( length == 0 ) { return std::wstring(); } std::vector&lt;wchar_t&gt; buffer( length ); ::MultiByteToWideChar( codePage, 0, pSource, sourceLength, &amp;buffer[ 0 ], length ); return std::wstring( buffer.begin(), buffer.end() ); } template&lt;&gt; std::string string_cast( const wchar_t* pSource, unsigned int codePage ) { assert( pSource != 0 ); size_t sourceLength = std::wcslen( pSource ); if( sourceLength == 0 ) { return std::string(); } int length = ::WideCharToMultiByte( codePage, 0, pSource, sourceLength, NULL, 0, NULL, NULL ); if( length == 0 ) { return std::string(); } std::vector&lt;char&gt; buffer( length ); ::WideCharToMultiByte( codePage, 0, pSource, sourceLength, &amp;buffer[ 0 ], length, NULL, NULL ); return std::string( buffer.begin(), buffer.end() ); } template&lt;&gt; std::wstring string_cast( const wchar_t* pSource, unsigned int codePage ) { assert( pSource != 0 ); return std::wstring( pSource ); } template&lt;&gt; std::string string_cast( const std::string&amp; source, unsigned int codePage ) { return source; } template&lt;&gt; std::wstring string_cast( const std::string&amp; source, unsigned int codePage ) { if( source.empty() ) { return std::wstring(); } int length = ::MultiByteToWideChar( codePage, 0, source.data(), source.length(), NULL, 0 ); if( length == 0 ) { return std::wstring(); } std::vector&lt;wchar_t&gt; buffer( length ); ::MultiByteToWideChar( codePage, 0, source.data(), source.length(), &amp;buffer[ 0 ], length ); return std::wstring( buffer.begin(), buffer.end() ); } template&lt;&gt; std::string string_cast( const std::wstring&amp; source, unsigned int codePage ) { if( source.empty() ) { return std::string(); } int length = ::WideCharToMultiByte( codePage, 0, source.data(), source.length(), NULL, 0, NULL, NULL ); if( length == 0 ) { return std::string(); } std::vector&lt;char&gt; buffer( length ); ::WideCharToMultiByte( codePage, 0, source.data(), source.length(), &amp;buffer[ 0 ], length, NULL, NULL ); return std::string( buffer.begin(), buffer.end() ); } template&lt;&gt; std::wstring string_cast( const std::wstring&amp; source, unsigned int codePage ) { return source; } </code></pre> <p>Are there any bugs or further optimizations?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-20T02:59:13.797", "Id": "58819", "Score": "0", "body": "Why don't you use an enumeration type to represent the code page with? `int` is hardly discoverable..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-12T02:43:30.813", "Id": "444818", "Score": "0", "body": "This code requires `#include <Windows.h>`. On the other hand, are `<cstring>`, `<cwchar>` and `<cassert>` really necessary?" } ]
[ { "body": "<p>Just a stylistic note, take it for what it's worth. I generally prefer to avoid:</p>\n\n<pre><code>if ( usual_case )\n{\n // lots of code\n}\nelse\n{\n // one line handler\n}\n</code></pre>\n\n<p>and instead prefer to go with less indentation, by handling error cases first:</p>\n\n<pre><code>if ( ! usual_case )\n{\n return one_liner;\n}\n// no need for indentation or braces anymore...\n</code></pre>\n\n<p>Rewriting one of your functions would look like this:</p>\n\n<pre><code>template&lt;&gt;\nstd::string string_cast( const wchar_t* pSource, unsigned int codePage )\n{\n assert( pSource != 0 );\n const size_t sourceLength = std::wcslen( pSource );\n if( sourceLength == 0 )\n {\n return std::string();\n }\n\n int length = ::WideCharToMultiByte( codePage, 0, pSource, sourceLength, NULL, 0, NULL, NULL );\n\n std::vector&lt;char&gt; buffer( length );\n ::WideCharToMultiByte( codePage, 0, pSource, sourceLength, &amp;buffer[ 0 ], length, NULL, NULL );\n\n return std::string( buffer.begin(), buffer.end() );\n}\n</code></pre>\n\n<p>It's slightly cleaner: fewer lines, fewer braces, less indentation. Not much, only slightly, but it adds up with multiple error-case checks, and multiple if-statements.</p>\n\n<p>Also, I made <code>sourceLength</code> <strong>const</strong> because:</p>\n\n<ol>\n<li>The <code>sourceLength</code> isn't going to change. You're going to initialize it, and use it, but you're never going to change it. Using <code>const</code> enforces that you <em>can't</em> change it, and is considered good practice.</li>\n<li>Using <code>if (sourceLength = 0)</code> is a classic programming mistake. Testing for equality, <code>==</code>, and assigning, <code>=</code>, differ only by a single character. That typo has caused numerous bugs.\n\n<ul>\n<li>if <code>sourceLength</code> is constant, <code>sourceLength = 0</code> fails to compile.</li>\n<li>reversing the comparison and using <code>if (0 = sourceLength)</code> also catches the typo at compile time - but it's a little weird to read. Someone nicknamed this \"Yoda conditionals\".</li>\n</ul></li>\n</ol>\n\n<p>So, I made it <code>const</code> to conform to good style, and to catch typo bugs -- especially since I changed the conditional from <code>&gt;</code> to <code>==</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T08:00:02.057", "Id": "2125", "Score": "0", "body": "Thank you for your feedback. I also updated my code as you suggested. BTW, why do I have to add extra `const` keyword to `sourceLength`?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T08:15:58.113", "Id": "2126", "Score": "0", "body": "Updated my answer to explain the `const` usage in more detail. Hope that helps." }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T08:29:19.583", "Id": "2127", "Score": "0", "body": "You're right. That's a good practice. Thank you :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-03-09T07:36:20.300", "Id": "1207", "ParentId": "1205", "Score": "9" } }, { "body": "<p>While your approach is simple and straightforward to implement there are some important drawbacks to realize.</p>\n\n<p>First, it doesn't take advantage of the power templates offer. Since you're specializing for every possible usage of <code>string_cast</code> there's no opportunity for the compiler to generate code for you. A consequence of this is that you have a lot of 'clipboard heritance', copy and pasting the same function and changing parts of it to do what you want. This is a form of code duplication.</p>\n\n<p>The approach does not lend itself to extendibility. What happens if you want to add support for another string type later on? The combination of functions you have to write would explode!</p>\n\n<p>So there're clearly opportunities for some major improvement. Let see how we can refactor this so that it better adheds to DRY. If you take a step back and think about how <code>string_cast</code> is used you'll find there are really just 3 scenarios it has to support:</p>\n\n<ul>\n<li>cast to the same string type.</li>\n<li>cast to a different string type.</li>\n<li>cast from a raw pointer representation into a string type.</li>\n</ul>\n\n<p>Each of these cases can be handle by writing a template for them. Starting with the string_cast function that acts as an interface:</p>\n\n<pre><code>template &lt;typename Td, typename Ts&gt;\n</code></pre>\n\n<p>string_cast now takes 2 template parameters. Keeping your naming convention, I use <code>Ts</code> to indicate the source type. (<code>TO</code> and <code>FROM</code> are probably better names.)</p>\n\n<pre><code>Td string_cast(const Ts &amp;source)\n{\n</code></pre>\n\n<p>We use type deduction to identify what we're casting from.</p>\n\n<pre><code> return string_cast_imp&lt;Td, Ts&gt;::cast(source);\n</code></pre>\n\n<p>Once we know what type <code>Td</code> and <code>Ts</code> is we delegate to <code>string_cast_imp</code> and the appropriate template will be instantiated.</p>\n\n<pre><code>}\n</code></pre>\n\n<hr>\n\n<p>Let's handle the easy case first:</p>\n\n<pre><code>template &lt;typename Td&gt;\nstruct string_cast_imp&lt;Td, Td&gt;\n{\n static const Td&amp; cast(const Td &amp;source)\n {\n return source;\n</code></pre>\n\n<p>For casting to the same string type, we don't need to do anything. Just return back what was given. Since this is nothing more than a pass-through returning by reference is ok. <code>string_cast</code> will make a copy before going out of scope since it's return by value.</p>\n\n<pre><code> }\n};\n</code></pre>\n\n<hr>\n\n<p>Now for the important case, the reason for writing <code>string_cast</code> in the first place! The basic process is the same, only certain aspects are different:</p>\n\n<ul>\n<li>conversion function used. eg. <code>WideCharToMultiByte</code> vs <code>MultiByteToWideChar</code></li>\n<li>buffer type used. eg. <code>vector&lt;char&gt;</code> for string vs <code>vector&lt;wchar_t&gt;</code> for wstring</li>\n<li>string type returned. That's captured by our template parameter <code>Td</code> so we don't have to worry about this as much.</li>\n</ul>\n\n<p>You can extract those differences into a trait-like policy class.</p>\n\n<pre><code>template &lt;typename Td, typename Ts&gt;\nstruct string_cast_imp\n{\n static Td cast(const Ts &amp;source)\n {\n int length = string_traits&lt;Ts&gt;::byte_convert( CP_ACP, source.data(), source.length(), \n NULL, 0 );\n if( length == 0 )\n {\n return Td();\n }\n</code></pre>\n\n<p>Here I removed the <code>string.empty()</code> check since it's not really needed. If the string is empty <code>length</code> will be 0 anyway so this is properly handled.</p>\n\n<pre><code> vector&lt; typename string_traits&lt;Td&gt;::char_trait &gt; buffer( length );\n</code></pre>\n\n<p>Here we use our policy class to tell us the proper character-type to use for our buffer. If <code>Td = string</code> then <code>string_traits&lt;Td&gt;::char_trait</code> will be a <code>char</code>. If it's a wstring then <code>string_traits&lt;Td&gt;::char_trait</code> will evaluate to a <code>wchar_t</code>.</p>\n\n<pre><code> string_traits&lt;Ts&gt;::byte_convert( CP_ACP, source.data(), source.length(), \n &amp;buffer[ 0 ] , length );\n</code></pre>\n\n<p>Similiarly, <code>byte_convert</code> acts as a wrapper to the correct byte function to call. This attrib is captured by our policy class as well.</p>\n\n<pre><code> return Td( buffer.begin(), buffer.end() );\n }\n};\n</code></pre>\n\n<p><br>\n<br>\nWe define our string_traits policies like this:</p>\n\n<pre><code>template &lt;typename T&gt;\nstruct string_traits;\n</code></pre>\n\n<p>Declare the general base-form but don't define it. This way if code tries to cast from an illegit string-type it will give a compile error.</p>\n\n<pre><code>template &lt;&gt;\nstruct string_traits&lt;string&gt;\n{\n typedef char char_trait;\n static int byte_convert(const int codepage, LPCSTR data , int data_length, \n LPWSTR buffer, int buffer_size)\n {\n</code></pre>\n\n<p>You might want to play around with the parameters it accepts but this should give you the general idea.</p>\n\n<pre><code> return ::MultiByteToWideChar( codepage, 0, data, data_length, buffer, buffer_size );\n }\n};\n</code></pre>\n\n<hr>\n\n<p>And now for the last case. For raw pointer types we can just wrap it into an appropriate string type and call one of our above string functions. We have to overload <code>string_cast</code> here because our base form accepts a reference type. Since reference types to arrays <em>do not</em> decay into a pointer type, this second template form will specifically handle that case for us.</p>\n\n<pre><code>template &lt;typename Td, typename Ts&gt;\nTd string_cast(Ts *source)\n{\n return string_cast_imp&lt;Td, typename string_type_of&lt;const Ts *&gt;::wrap &gt;::cast(source);\n</code></pre>\n\n<p>Notice I'm using <code>const Ts *</code> as template parameter for <code>string_type_of</code>. Regardless of whether <code>Ts</code> is const or not we always use template form <code>&lt;const Ts *&gt;</code> to get the information we need.</p>\n\n<pre><code>}\n</code></pre>\n\n<p><br></p>\n\n<p><code>string_type_of</code> is another policy we define as follows:</p>\n\n<pre><code>template &lt;typename T&gt;\nstruct string_type_of;\n</code></pre>\n\n<p>This policy class tells us what string-type to use for a given raw pointer type.</p>\n\n<pre><code>template &lt;&gt;\nstruct string_type_of&lt;const char *&gt;\n{\n typedef string wrap;\n};\n</code></pre>\n\n<p><br>\nWith this refactor, you've reduced the number of written functions from 8 down to just 4 and eliminated code duplication. Perhaps more importantly adding support for another string-type is significantly easier, just specialized another policy for that string-type and you're done.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-29T02:31:05.507", "Id": "2616", "Score": "0", "body": "By the way, I just wanted to use `string_cast<T>( ... )` instead of `string_cast<Td, Ts>( ... )`. Is it still possible?" }, { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-29T10:15:23.867", "Id": "2635", "Score": "1", "body": "@Daniel yes that is possible. Like I said, `Ts` will be deduced based on what parameter you passed into string_cast. eg. `string_cast<wstring>( string(\"foobar\") );` Ts = string in this case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-16T09:46:49.713", "Id": "348074", "Score": "2", "body": "This is one of the most clear, practical, AND useful demonstration of templates and their potential I've ever seen." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-26T00:07:49.613", "Id": "1466", "ParentId": "1205", "Score": "17" } } ]
{ "AcceptedAnswerId": "1466", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-09T06:13:39.323", "Id": "1205", "Score": "14", "Tags": [ "c++", "strings", "template", "stl", "casting" ], "Title": "C++ string_cast<> template function" }
1205
<p>This Common Lisp exercise is to write a program that can calculate the weekday given a string of the format "M-D-Y." It was more challenging than I expected. If you have suggestions about how to simplify this code, I will be very grateful.</p> <pre><code>;; 2.7 Day of Week. A program for converting Gregorian dates in the form month-day-year to day of the ;; week is the following. Let the Gregorian date be represented by M-D-Y where we have the following ;; definitions: ;; M is the month of the year. Let m be the month number derived from M by the rule m is M - 2 if M &gt;= 3 ;; and m is M + 10 otherwise. ;; d is the day of the month. ;; y is the year of the century. ;; c is the number of the previous century. ;; The algorithm is as follows: ;; (a) A is the integer part of (13m - 1)/5. ;; (b) B is the integer parg of y/4. ;; (c) C is the integer part of c/4. ;; (d) D = A + B + C + d + y - 2c. ;; (e) Make R equal to the remainder of D/7. ;; (f ) Interpret R as Sunday if R = 0, Monday if R is 1, etc (defun read-date () (format t "Enter the gregorian date in the format (M-D-Y): ~%") (read)) (defun flatten (the-list) (cond ((null the-list) nil) ((atom the-list) (list the-list)) (t (concatenate 'list (flatten (car the-list)) (flatten (cdr the-list)))))) (defun split (split-char string-to-split) (let ((next-split-char (position split-char string-to-split))) (if next-split-char (flatten (list (safely-read-from-string (subseq string-to-split 0 next-split-char)) (split split-char (subseq string-to-split (+ 1 next-split-char))))) (list (safely-read-from-string string-to-split))))) (defun weekday-code (bigM bigD bigY) (let* ((m (if (&gt;= bigM 3) (- bigM 2) (+ bigM 10))) (y (mod bigY 100)) (littleC (/ (- bigY y) 100)) (A (floor (- (* 13 m) 1) 5)) (B (floor y 4)) (C (floor littleC 4)) (D (- (+ A B C bigD y) (* 2 littleC))) (R (mod D 7))) (format t "m: ~a y: ~a c: ~a A: ~a B: ~a C: ~a D: ~a R: ~a ~%" m y littleC A B C D R) R)) (defun check-date-format (bigM bigD bigY) (cond ((or (&lt; bigM 1) (&gt; bigM 12)) (error "The month (~a) is not in the range 1-12." bigM)) ((&lt; bigY 0) (error "The year (~a) is less than 0." bigY)) ((or (&lt; bigD 1) (&gt; bigD 31)) (error "The day (~a) is not in the range 1-31." bigD)))) (let ((gregorian-date (read-date))) (destructuring-bind (bigM bigD bigY) (split #\- gregorian-date) (check-date-format bigM bigD bigY) (format t "~a was (or will be) a ~[Sunday~;Monday~;Tuesday~;Wednesday~;Thursday~;Friday~;Saturday~]." gregorian-date (weekday-code bigM bigD bigY)))) </code></pre>
[]
[ { "body": "<p>If you're allowed to use library functions, <code>split</code> already exists as part of <a href=\"http://weitz.de/cl-ppcre/\" rel=\"nofollow\">cl-ppcre</a>. </p>\n\n<hr>\n\n<p>There's a pretty rich set of date/time functions in the Lisp core that make this trivial. If it's for learning purposes, by all means, go ahead and do it by hand. But if you're thinking \"What's the best way to get the day-of-week in Lisp?\", that's actually ridiculously simple.</p>\n\n<pre><code>(defun day-of-week (day month year)\n (nth-value 6 (decode-universal-time (encode-universal-time 0 0 0 day month year 0))))\n</code></pre>\n\n<p>Re-arrange order of argumnents to taste. Monday is 0 by default, so you'd need to re-jig your <code>format</code> directive. If you need to be able to handle dates before 1900, there's a more robust version at the <a href=\"http://cl-cookbook.sourceforge.net/dates_and_times.html\" rel=\"nofollow\">Common Lisp Cookbook</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-10T01:34:40.203", "Id": "2146", "Score": "0", "body": "That's good to know. In fact, this is a practice exercise so I had to do it the harder way this time. But, for future reference I will keep that in mind." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-27T02:31:32.913", "Id": "129724", "Score": "1", "body": "0 is Monday. (https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node232.html)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-09T12:31:36.003", "Id": "1210", "ParentId": "1206", "Score": "3" } }, { "body": "<p>Typically, you should almost never need to use a flatten function. For example, the split function:</p>\n\n<pre><code>(defun split (split-char string-to-split) \n (let ((next-split-char (position split-char string-to-split)))\n (if next-split-char (flatten (list (safely-read-from-string (subseq string-to-split 0 next-split-char))\n (split split-char (subseq string-to-split (+ 1 next-split-char)))))\n (list (safely-read-from-string string-to-split)))))\n</code></pre>\n\n<p>is equivalent to:</p>\n\n<pre><code>(defun split (split-char string-to-split) \n (let ((next-split-char (position split-char string-to-split)))\n (if next-split-char \n (cons (safely-read-from-string (subseq string-to-split 0 next-split-char))\n (split split-char (subseq string-to-split (1+ next-split-char))))\n (list (safely-read-from-string string-to-split)))))\n</code></pre>\n\n<p>This assumes safely-read-from-string returns the same as read function. The flatten helper function is not necessary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-10T01:33:44.510", "Id": "2145", "Score": "0", "body": "Thanks! I did not know how to use \"cons\" properly. Now I have a better understanding of how to use it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T12:51:48.450", "Id": "1211", "ParentId": "1206", "Score": "3" } }, { "body": "<h2>Split</h2>\n\n<p>Here is an alternative implementation of <code>split</code> using the loop facility.</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(defun split (split-char string-to-split)\n (loop for start = 0 then (1+ end)\n for end = (position split-char string-to-split :start start)\n collect (parse-integer string-to-split\n :start start\n :end end\n :junk-allowed nil)\n while end))\n</code></pre>\n\n<p>Because we always parse the original <code>string-to-split</code>, with different <code>start</code> and <code>end</code> indices, we don't allocate memory for substrings. In fact, the <code>time</code> macro reports \"<em>0 bytes consed</em>\".</p>\n\n<h2>Check</h2>\n\n<ul>\n<li>I changed <code>check-date-format</code> so that it also checks that the given values are integers.</li>\n<li>I use <code>assert</code> which is more appropriate than <code>error</code> here: an additional benefit is that <code>assert</code> provides a <code>CONTINUE</code> restart which allows to modify the value of some places. </li>\n<li>I exploit the fact that <code>&lt;=</code> is variadic to check range membership.</li>\n<li>The check is a little more precise regarding the number of days in a months and leap years.</li>\n</ul>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(defun check-date-format (month day year)\n (check-type month integer)\n (check-type day integer)\n (check-type year integer)\n (assert (&lt;= 1 month 12) (month) \"The month (~a) is not in the range 1-12.\" month)\n (assert (&lt; 0 year) (year) \"The year (~a) is less than 0.\" year)\n (let ((n-days (aref #(31 29 31 30 31 30 31 31 30 31 30 31) (1- month))))\n (assert (&lt;= 1 day n-days) (day) \"The day (~a) is not in the range 1-~a.\" day n-days))\n (when (and (= month 2) (= day 29))\n (assert (and\n (zerop (mod year 4))\n (or (not (zerop (mod year 100)))\n (zerop (mod year 400))))\n (year) \n \"February 29, ~a is not valid because ~:*~a is not a leap year.\" year)))\n</code></pre>\n\n<h2>Parse and check</h2>\n\n<p>The above utilities can be used to define <code>parse-gregorian-date</code>, which is responsible to check that the string actually is valid.</p>\n\n<ul>\n<li>It returns multiple values instead of a list, which I find more idiomatic.</li>\n<li>It includes the checks done previously by <code>check-date-format</code>: this is a good way to reduce the temporal coupling introduced between parsing and checking user input.</li>\n</ul>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(defun parse-gregorian-date (string)\n (let ((parts (split #\\- string)))\n (apply #'check-date-format parts)\n (values-list parts)))\n</code></pre>\n\n<h2>Computing weekday</h2>\n\n<ul>\n<li>The original intermediate variables (<code>littleC</code>,<code>A</code>,<code>bigD</code>, ...) did not respect the conventional way of writing symbols in Common Lisp (a.k.a. dash-separated lowercase words) and did not convey their purpose very well. I removed them so as to inline the mathematical expression.</li>\n<li><code>(floor 1945 100)</code> returns <code>19</code> and <code>45</code>, which are your <code>c</code> and <code>y</code> variables, respectively.</li>\n<li>The computation of <code>m</code> can be made using the <code>mod</code> operator. That allowed me to simplify some terms, even though the resulting expressions is not necessarly more readable (but the original formula is already cryptic).</li>\n</ul>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(defun weekday-code (month day year)\n (multiple-value-bind (century century-year) (floor year 100)\n (mod (- (+ (floor (+ (* 13 (mod (- month 3) 12)) 12) 5)\n (floor century-year 4)\n (floor century 4)\n day\n century-year) \n (* 2 century))\n 7)))\n</code></pre>\n\n<h2>Main function</h2>\n\n<p>There are minor adaptations due to the fact that above functions were redefined.</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(defun gregorian-weekday ()\n (let ((input-string (read-date)))\n (multiple-value-bind (m d y) (parse-gregorian-date input-string)\n (format t \"~a was (or will be) a ~[Sunday~;Monday~;Tuesday~;Wednesday~;Thursday~;Friday~;Saturday~].\"\n input-string\n (weekday-code m d y)))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-27T10:53:12.603", "Id": "70988", "ParentId": "1206", "Score": "0" } } ]
{ "AcceptedAnswerId": "1211", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-03-09T06:23:30.530", "Id": "1206", "Score": "5", "Tags": [ "datetime", "lisp", "common-lisp" ], "Title": "Calculate the weekday from a date (M-D-Y)" }
1206
<p><a href="http://www.developer.com/design/article.php/3678856/MVC-in-a-JavaSwing-Application.htm">This article has left me a little confused.</a> </p> <p>In explaining a method on how to design MVC into Java Swing apps the author defines the controller class as Singleton and relays a series of calls to the Controller for each operation.</p> <p>In a view object:</p> <pre><code>... Controller.getInstance().setOwner(this); Controller.getInstance().setNameTextField(this.nameTextField); Controller.getInstance().setEmailTextField(this.emailTextField); Controller.getInstance().processForm(); ... </code></pre> <p>And inside the controller class:</p> <pre><code>public void processForm() { result1 = doSomethingWithName(this.nameTextField.getText()); result2 = doSomethingWithEmail(this.emailTextField.getText()); this.owner.setResult(result1, result2); } </code></pre> <p>I don't understand why this has been made so complex! Wouldn't it be simpler, less error prone and more modular to simply:</p> <pre><code>Controller.processForm(this, this.nameTextField.getText(), this.emailTextField.getText()); </code></pre> <p>and</p> <pre><code>public static void processForm(OwnerClass owner, String name, String email) { result1 = doSomethingWithName(name); result2 = doSomethingWithEmail(email); this.owner.setResult(result1, result2); } </code></pre> <p>Is anyone familiar with this design pattern? Is there reason to this method?</p>
[]
[ { "body": "<p>It's been a long time ago since I last used an MVC approach in Swing, but I immediately notice some things I wouldn't do.</p>\n\n<ol>\n<li>Don't use a singleton, <a href=\"http://blogs.msdn.com/b/scottdensmore/archive/2004/05/25/140827.aspx\" rel=\"nofollow\">singletons are evil!</a></li>\n<li>Passing view components to the controller? When I do MVC, I tend to pass the controller to my view elements, preferably just an interface. The view can request actions on the controller. This allows for total decoupling of the view. So you can also switch to something else than Swing. This probably isn't the 'default' approach of MVC with Swing however.</li>\n</ol>\n\n<p>So yeah, it seems I would agree with you. Perhaps try looking for other MVC examples with Swing. This article doesn't look particularly appealing IMHO.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-09T11:01:16.040", "Id": "38478", "Score": "0", "body": "Singletons, I thought, were only evil if they held state. This one doesn't. Is it that bad?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T14:49:04.877", "Id": "1213", "ParentId": "1212", "Score": "3" } }, { "body": "<p>I agree with steven concerning Singletons. I think the most convenient way to call something like this is a builder-pattern-like approach (\"fluent interfaces\") similar to StringBuilder:</p>\n\n<pre><code>Controller.getInstance().setOwner(this)\n .setNameTextField(this.nameTextField);\n .setEmailTextField(this.emailTextField);\n .processForm();\n</code></pre>\n\n<p>This is Java's closest approximation of named and default arguments in other languages (e.g. you don't have to remember the order of parameters, you can make some of them optional, and with a little <a href=\"http://michid.wordpress.com/2008/08/13/type-safe-builder-pattern-in-java/\" rel=\"nofollow\">type trickery</a> you can ensure that processForm can be only called if all mandatory args are set).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-04-07T07:14:50.067", "Id": "1706", "ParentId": "1212", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 2.5", "CreationDate": "2011-03-09T13:49:24.580", "Id": "1212", "Score": "5", "Tags": [ "java", "design-patterns", "mvc" ], "Title": "MVC Controller in Java Swing Apps - Singleton or public static" }
1212