body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have a page with a list of items. Items have several actions assigned to them. (see screenshot).</p> <p>One may choose to directly click on an icon next to each row or check a checkbox on the left hand side and click action above the list.</p> <p>The issue is that after clicking an item OR checking a checkbox of several items and then clicking an action there is a lag (a second or so). Imagine having 100 rows or more.</p> <p><img src="https://i.stack.imgur.com/xXy96.png" alt="enter image description here"> </p> <p>Script:</p> <pre><code> $("a.action:not(.remove)").click(function (e) { // .remove =&gt; do not execute on download tasks page var selected = new Array(); // array to hold selections or clicks var obj = $(this), objData = obj.data(); e.preventDefault(); if (!obj.hasClass('disablelink')) { if (objData.ajaxMachineid) { selected.push(objData.ajaxMachineid); } else { $("input.checkbox:checkbox:checked:not(.checkall)").each(function () { var checkbox = $(this), machineId = checkbox.val(), packageId = objData.ajaxPackageid.removeSpecialChars().toUpperCase(), operation = objData.ajaxType; var $row = $("#" + machineId + packageId.removeSpecialChars().toUpperCase()); if ($row.length) { $row.has("a[data-ajax-type=" + operation + "]:not(.hide)").length ? selected.push(machineId) : $(this).attr('checked', false); } }); } if (selected.length &gt; 0) { // do something more here blah blah blah }; } $("input.checkall").attr("checked", false); }); </code></pre> <p>Sample HTML of one row:</p> <pre><code>&lt;tr id="1960AGISGIGAMEM22220204" class=""&gt; &lt;td class="checkbox"&gt;&lt;input type="checkbox" value="1960" class="checkbox"&gt;&lt;/td&gt; &lt;td class=""&gt;&lt;p&gt;&lt;a href="/Devices/View/1960"&gt;GD009000246&lt;/a&gt;&lt;/p&gt;&lt;/td&gt; &lt;td class="platform"&gt;PCGames&lt;/td&gt; &lt;td class="cat"&gt;Up&lt;/td&gt; &lt;td class="platform"&gt;&lt;div class="pbar"&gt;&lt;span class="progresslabel"&gt;&lt;/span&gt;&lt;/div&gt;&lt;/td&gt; &lt;td class="date"&gt;10.48.1.236&lt;/td&gt; &lt;td class="options clearfix"&gt; &lt;a title="View" class="iconMagnifier tip" href="/Packages/View/AGI-SGI-GAME-M222-2.0.2.0.4"&gt;View&lt;/a&gt; &lt;a title="Install" href="/Packages/PackageActionInstallAsync" data-ajax-type="Install" data-ajax-packageid="AGI-SGI-GAME-M222-2.0.2.0.4" data-ajax-machineid="1960" class="iconDiskPlus action tip "&gt;Install&lt;/a&gt; &lt;a title="" href="/Packages/PackageActionAsyncDeletePackage" data-ajax-type="DeletePackage" data-ajax-packageid="AGI-SGI-GAME-M222-2.0.2.0.4" data-ajax-machineid="1960" class="iconDelete action tip"&gt;Remove&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre>
[]
[ { "body": "<p>So pretty much everything will make a insignificant effect apart from the section where you are looping through each of the checkboxes. See my modifications and notes below.</p>\n\n<pre><code>$(\"a.action:not(.remove)\").click(function (e) { // .remove =&gt; do not execute on download tasks page\n var selected = new Array(); // array to hold selections or clicks\n var obj = $(this),\n objData = obj.data(),\n\n // Moved these up here as they are not specific to the checkboxes\n packageId = objData.ajaxPackageid.removeSpecialChars().toUpperCase(),\n operation = objData.ajaxType;\n\n e.preventDefault();\n if (!obj.hasClass('disablelink')) {\n if (objData.ajaxMachineid) {\n selected.push(objData.ajaxMachineid);\n } else {\n\n // This seems a little convoluted to me, normally you would \n // use [type=checkbox]\n $(\"input[type=checkbox]:checked:not(.checkall)\").each(function () {\n\n var checkbox = $(this),\n machineId = checkbox.val();\n\n // No need to call .removeSpecialChars().toUpperCase() on packageId\n var $row = $(\"#\" + machineId + packageId);\n\n if ($row.length) {\n\n // Not 100% whether you need .length here\n // It could also be beneficial to add a class to the row instead\n // of calling this complex selector\n $row.has(\"a[data-ajax-type=\" + operation + \"]:not(.hide)\").length \n ? selected.push(machineId) \n : $(this).attr('checked', false);\n\n }\n });\n }\n if (selected.length &gt; 0) {\n // do something more here blah blah blah\n };\n }\n $(\"input.checkall\").attr(\"checked\", false);\n });\n</code></pre>\n\n<p>The obvious thing to do on top of my suggestions above is to cache the checkbox list, this means that every time it enters that section, the app will no longer need to go through every element in the DOM looking for all the checkboxes. Doing this will probably have the most meaningful impact on performance.</p>\n\n<pre><code>// in document ready\nvar checkboxes = $('input[type=checkbox]');\n\n// When you need to find the checked check boxes\nvar checked = checkboxes.find(':checked:not(.checkall)');\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T10:34:29.453", "Id": "36296", "Score": "0", "body": "Thanks Tyriar!. the only issue i'm having is having this: var checkboxes = $('input[type=checkbox]'); and then doing this: alert(checkboxes.find(':checked:not(.checkall)').length); always returns 0. however when I have this: alert($('input[type=checkbox]:checked').length); returns the right number of checked checkboxes. ???" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T10:41:34.447", "Id": "36297", "Score": "0", "body": "I figured it out. I used \"filter\" instead and it works: var checked = checkboxes.filter(\":checked:not(.checkall)\");\n checked.each(function () {" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T20:44:12.853", "Id": "36327", "Score": "0", "body": "Yeah that's it. Apologies, working without testing :p" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T08:33:38.370", "Id": "23525", "ParentId": "23524", "Score": "2" } } ]
{ "AcceptedAnswerId": "23525", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T08:01:45.350", "Id": "23524", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "How can I improve performance of my selecting code" }
23524
<p>Exercise:</p> <blockquote> <p>Define three new classes, called <strong>Song</strong>, <strong>Playlist</strong>, and <strong>MusicCollection</strong>. A Song object will contain information about a particular song, such as its title, artist, album, and playing time. A Playlist object will contain the name of the playlist and a collection of songs. A MusicCollection object will contain a collection of playlists, including a special master playlist called library that contains every song in the collection. Define these three classes and write methods to do the following:</p> <ul> <li>Create a Song object and set its information. </li> <li>Create a Playlist object, and add songs to and remove songs from a playlist. A new song should be added to the master playlist if it’s not already there. Make sure that if a song is removed from the master playlist, it's removed from all playlists in the music collection as well. </li> <li>Create a MusicCollection object, and add playlists to and remove playlists from the collection. </li> </ul> <p>Search and display the information about any song, any playlist, or the entire music collection. Make sure all your classes do not leak memory!</p> </blockquote> <p>This is my code:</p> <p><strong>Song.h</strong></p> <pre><code>@interface Song : NSObject @property (nonatomic, copy) NSString *artist, *title, *album, *time; -(void) setSong:(NSString *)theSongName andArtist:(NSString *)theArtist andAlbum:(NSString *)theAlbum andPlayingTime:(NSString *)theTime; @end </code></pre> <p><strong>Song.m</strong></p> <pre><code>#import "Song.h" @implementation Song @synthesize title, album, artist, time; -(void) setSong:(NSString *)theSongName andArtist:(NSString *)theArtist andAlbum:(NSString *)theAlbum andPlayingTime:(NSString *)theTime{ self.title = theSongName; self.artist = theArtist; self.album = theAlbum; self.time = theTime; } @end </code></pre> <p><strong>Playlist.h</strong></p> <pre><code>#import &lt;Foundation/Foundation.h&gt; #import "Song.h" @interface PlayList : NSObject @property (nonatomic, copy) NSString *playListName; @property (nonatomic, strong) NSMutableArray *songsCollection; -(void) addSongToPlayList:(Song *) someSong; -(void) removeSongFromPlayList:(Song *) theSong; -(void) print; -(id) initWithName:(NSString *) listName; -(id) init; @end </code></pre> <p><strong>Playlist.m</strong></p> <pre><code>#import "PlayList.h" #import "Song.h" @implementation PlayList @synthesize songsCollection, playListName; -(void) addSongToPlayList:(Song *) someSong{ [songsCollection addObject:someSong]; } -(id) initWithName:(NSString *)listName{ self = [super init]; if (self) { self.playListName = listName; songsCollection = [[NSMutableArray alloc]init]; } return self; } -(id) init { return [self initWithName:@"No Name"]; } -(void) removeSongFromPlayList:(Song *)theSong{ [songsCollection removeObjectIdenticalTo:theSong]; } -(void) print{ NSLog(@"------------------- %@ -------------------------------------",playListName); for (Song *mySong in songsCollection) { NSLog(@"%-15s %-25s %-18s %-10s",[mySong.artist UTF8String], [mySong.title UTF8String], [mySong.album UTF8String], [mySong.time UTF8String]); } NSLog(@"-----------------------------------------------------------------"); } @end </code></pre> <p><strong>MusicCollection.h</strong></p> <pre><code>#import &lt;Foundation/Foundation.h&gt; #import "PlayList.h" @interface MusicCollection : NSObject @property (nonatomic, copy) NSMutableArray *playlistsCollection; @property (nonatomic, copy) PlayList *library; @property (nonatomic, copy) NSString *name; -(id) initWithName:(NSString *) collectionName; //-(void) addSongToPlaylist:(Song *) aSong toPlaylist:(PlayList *) playlistName; //-(void) removeSongFromPlaylist:(Song *) aSong fromPlaylist:(PlayList *) playlistName; -(void) addPlaylistToCollection:(PlayList *) playListToAdd; -(void) removePlayListFromCollection:(PlayList *) playListToRemove; -(void) searchCollection:(NSString *) someCollection; -(void) list; @end </code></pre> <p><strong>MusicCollection.m</strong></p> <pre><code>#import "MusicCollection.h" @implementation MusicCollection @synthesize playlistsCollection, library, name; -(id) initWithName:(NSString *)collectionName { self = [super init]; if (self) { name = [NSString stringWithString:collectionName]; playlistsCollection = [NSMutableArray array]; library = [[PlayList alloc] initWithName:@"Library"]; } return self; } -(void) addPlaylistToCollection:(PlayList *)playListToAdd{ if ([playlistsCollection containsObject: playListToAdd] == NO) [playlistsCollection addObject: playListToAdd]; for (Song *song in playListToAdd.songsCollection) { if ([library.songsCollection containsObject:song] == NO) [library addSongToPlayList:song]; } } -(void) removePlayListFromCollection:(PlayList *)playListToRemove { if ([playlistsCollection containsObject: playListToRemove] == YES) [playlistsCollection removeObject:playListToRemove]; for (Song *song in playListToRemove.songsCollection) [library removeSongFromPlayList:song]; } -(void) list { for (PlayList *playlist in playlistsCollection) [playlist print]; } -(void) searchCollection:(NSString *)someCollection { NSMutableArray *results = [[NSMutableArray alloc] init]; for (PlayList *lookUp in playlistsCollection) { if ([lookUp.playListName rangeOfString:someCollection options:NSCaseInsensitiveSearch].location != NSNotFound) [results addObject:lookUp]; } for (PlayList *playlists in results) { [playlists print]; } } @end </code></pre> <p><strong>main.m</strong></p> <pre><code>#import &lt;Foundation/Foundation.h&gt; #import "Song.h" #import "Playlist.h" #import "MusicCollection.h" int main(int argc, const char * argv[]) { @autoreleasepool { Song *song1 = [[Song alloc] init]; Song *song2 = [[Song alloc] init]; Song *song3 = [[Song alloc] init]; Song *song4 = [[Song alloc] init]; Song *song5 = [[Song alloc] init]; Song *song6 = [[Song alloc] init]; Song *song7 = [[Song alloc] init]; [song1 setSong:@"Heart Attack" andArtist:@"Demi Lovato" andAlbum:@"Demi's Album" andPlayingTime:@"3:15"]; [song2 setSong:@"When I Was Your Man" andArtist:@"Bruno Mars" andAlbum:@"Bruno Album" andPlayingTime:@"1:31"]; [song3 setSong:@"Harlem Shake" andArtist:@"Baauer" andAlbum:@"Baauer Album" andPlayingTime:@"3:22"]; [song4 setSong:@"I believe I Can Fly" andArtist:@"R-Kelly" andAlbum:@"R-Kelly Album" andPlayingTime:@"2:33"]; [song5 setSong:@"A Milli" andArtist:@"Lil Wayne" andAlbum:@"Lil Wayne Album" andPlayingTime:@"1:34"]; [song6 setSong:@"Diamonds" andArtist:@"Rihana" andAlbum:@"Rihana Album" andPlayingTime:@"2:32"]; [song7 setSong:@"Work Hard Play Hard" andArtist:@"Wiz Khalifa" andAlbum:@"Wiz Khalifa Album" andPlayingTime:@"1:54"]; PlayList *playlist1 = [[PlayList alloc] initWithName:@"My Favorit's"]; PlayList *playlist2 = [[PlayList alloc] initWithName:@"Good Time's"]; PlayList *playlist3 = [[PlayList alloc] initWithName:@"Partying"]; PlayList *playlist4 = [[PlayList alloc] initWithName:@"Hip Hop"]; [playlist1 addSongToPlayList:song1]; [playlist1 addSongToPlayList:song2]; [playlist2 addSongToPlayList:song3]; [playlist2 addSongToPlayList:song4]; [playlist3 addSongToPlayList:song5]; [playlist3 addSongToPlayList:song7]; [playlist4 addSongToPlayList:song7]; [playlist4 addSongToPlayList:song6]; [playlist4 addSongToPlayList:song5]; [playlist4 addSongToPlayList:song4]; [playlist4 addSongToPlayList:song3]; [playlist4 addSongToPlayList:song2]; MusicCollection *myCollection = [[MusicCollection alloc] initWithName:@"music"]; [myCollection addPlaylistToCollection:playlist1]; [myCollection addPlaylistToCollection:playlist2]; [myCollection addPlaylistToCollection:playlist3]; [myCollection addPlaylistToCollection:playlist4]; [myCollection list]; [myCollection searchCollection:@"Hip Hop"]; [playlist1 removeSongFromPlayList: song2]; [myCollection removePlayListFromCollection:playlist2]; [myCollection list]; [myCollection.library print]; } return 0; } </code></pre> <p>Is this code decent?</p>
[]
[ { "body": "<p>As I already wrote on <a href=\"https://codereview.stackexchange.com/questions/21688/creating-shapes-program-with-multiple-classes-different-files-in-objective-c\">another of your questions</a>:</p>\n\n<pre><code>-(void) setSong:(NSString *)theSongName andArtist:(NSString *)theArtist andAlbum:(NSString *)theAlbum andPlayingTime:(NSString *)theTime;\n</code></pre>\n\n<p>This violates the naming conventions. it should be named</p>\n\n<pre><code>-(void) setSong:(NSString *)theSongName artist:(NSString *)theArtist album:(NSString *)theAlbum playingTime:(NSString *)theTime;\n</code></pre>\n\n<p>If you dont believe me, <a href=\"https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/Articles/NamingMethods.html#//apple_ref/doc/uid/20001282-1001751-BCIJHEDH\" rel=\"nofollow noreferrer\">trust apple</a></p>\n\n<blockquote>\n <p>Don’t use “and” to link keywords that are attributes of the receiver.</p>\n\n<pre><code>- (int)runModalForDirectory:(NSString *)path file:(NSString *) name types:(NSArray *)fileTypes;\n</code></pre>\n \n <p>Right.</p>\n\n<pre><code>- (int)runModalForDirectory:(NSString *)path andFile:(NSString *)name andTypes:(NSArray *)fileTypes;\n</code></pre>\n \n <p>Wrong.</p>\n</blockquote>\n\n<p><code>and…</code> indicates a second distinct action</p>\n\n<blockquote>\n <p>If the method describes two separate actions, use “and” to link them.</p>\n\n<pre><code>- (BOOL)openFile:(NSString *)fullPath withApplication:(NSString *)appName andDeactivate:(BOOL)flag;\n</code></pre>\n</blockquote>\n\n<hr>\n\n<pre><code>-(void) list {\n\n for (PlayList *playlist in playlistsCollection)\n [playlist print];\n}\n</code></pre>\n\n<p><code>list</code> is a quite unintuitive name. <code>printPlayListCollection</code> or similar would be better.</p>\n\n<hr>\n\n<p>you should add a <code>init…</code> method to <code>Song</code> that take all important information. The idea behind this is that by using tis as designated initializer you ensure that your song objects will always be in a valid state. Let's assume you also write the sound playing functionality: with <code>[[Song alloc] init]</code> you would create a object that has nothing for playback. before you would play it, each time you must assure it is playable.<br>\nBut if you would raise an exception if the plain <code>init</code> and create <code>initWithArtistName:songName:…filePath:…</code> as designated initializer you can be quite sure, everything is set up correctly once you try to play it.</p>\n\n<hr>\n\n<p><code>@sythesize</code> statements arent necessary anymore. It will be implicit added.</p>\n\n<pre><code>@property (nonatomic, copy) NSString *artist;\n</code></pre>\n\n<p>will result in an implicit synthesize statement equivalent to</p>\n\n<pre><code>@synthesize artist = _artist;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T12:36:36.910", "Id": "36302", "Score": "0", "body": "Thank you buddy. I know this `and` is annoying, it's just that the author in the book use it all the time so i just got use to it, but i will get out of it. i definitely see that its not acceptable, and would make more sense to use it if there if a different action to preform in the method. @vikingosegundo" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T13:19:25.157", "Id": "36304", "Score": "0", "body": "What book is it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T17:42:26.690", "Id": "36322", "Score": "0", "body": "\"Programming in Objective C\" by stephen Kochan @vikingosegundo" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T11:51:55.633", "Id": "23530", "ParentId": "23527", "Score": "5" } } ]
{ "AcceptedAnswerId": "23530", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T09:43:33.737", "Id": "23527", "Score": "2", "Tags": [ "objective-c" ], "Title": "Creating a Playlist program" }
23527
<p>My context is a very simple filter-like program that streams lines from an input file into an output file, filtering out lines the user (well, me) doesn't want. The filter is rather easy, simply requiring a particular value for some 'column' in the input file. Options are easily expressed with <code>argparse</code>:</p> <pre><code>parser.add_argument('-e', '--example', type=int, metavar='EXAMPLE', help='require a value of %(metavar)s for column "example"') </code></pre> <p>There's a few of these, all typed. As the actual filter gets a line at some point, the question whether to include such a line is simple: split the line and check all the required filters:</p> <pre><code>c1, c2, c3, *_ = line.split('\t') c1, c2, c3 = int(c1), int(c2), int(c3) # ← this line bugs me if args.c1 and args.c1 != c1: return False </code></pre> <p>The second line of which bugs me a bit: as the values are initially strings and I need them to be something else, the types need to be changed. Although short, I'm not entirely convinced this is the best solution. Some other options:</p> <ul> <li>create a separate function to hide the thing that bugs me;</li> <li>remove the <code>type=</code> declarations from the options (also removes automatic user input validation);</li> <li>coerce the arguments back to <code>str</code>s and do the comparison with <code>str</code>s (would lead to about the same as what I've got).</li> </ul> <p>Which of the options available would be the 'best', 'most pythonic', 'prettiest'? Or am I just overthinking this...</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T13:59:23.147", "Id": "36310", "Score": "0", "body": "`int()` skips leading and trailing whitespace and leading zeros. So, a string comparison is not quite the same. Which do you need?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T14:34:26.357", "Id": "36313", "Score": "0", "body": "I need the numeric value. My data doesn't contain extraneous whitespace or zeroes, thought that doesn't much matter for the issue at hand." } ]
[ { "body": "<h3>1. Possible bugs</h3>\n\n<p>I can't be certain that these are bugs, but they look dodgy to me:</p>\n\n<ol>\n<li><p>You can't filter on the number 0, because if <code>args.c1</code> is 0, then it will test false and so you'll never compare it to <code>c1</code>. Is this a problem? If it is, you ought to compare <code>args.c1</code> explicitly against <code>None</code>.</p></li>\n<li><p>If the string <code>c1</code> cannot be converted to an integer, then <code>int(c1)</code> will raise <code>ValueError</code>. Is this what you want? Would it be better to treat this case as \"not matching the filter\"?</p></li>\n<li><p>If <code>line</code> has fewer than three fields, the assignment to <code>c1, c2, c3, *_</code> will raise <code>ValueError</code>. Is this what you want? Would it be better to treat this case as \"not matching the filter\"?</p></li>\n</ol>\n\n<h3>2. Suggested improvement</h3>\n\n<p>Fixing the possible bugs listed above:</p>\n\n<pre><code>def filter_field(filter, field):\n \"\"\"\n Return True if the string `field` passes `filter`, which is\n either None (meaning no filter), or an int (meaning that \n `int(field)` must equal `filter`).\n \"\"\"\n try:\n return filter is None or filter == int(field)\n except ValueError:\n return False\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>filters = [args.c1, args.c2, args.c3]\nfields = line.split('\\t')\nif len(fields) &lt; len(filters):\n return False\nif not all(filter_field(a, b) for a, b in zip(filters, fields)):\n return False\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T11:21:07.007", "Id": "36341", "Score": "0", "body": "1: figured that as well, though my current context will never 'require' a falsy value. 2: valid point, crashing isn't good, even though I'd expect only integers. 3: also a valid point, though my lines contain far more than 3 values in reality.\nFurthermore, I like your idea of using `all` and `zip`; does feel prettier to me :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T09:51:20.527", "Id": "23560", "ParentId": "23531", "Score": "1" } } ]
{ "AcceptedAnswerId": "23560", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T12:24:18.877", "Id": "23531", "Score": "3", "Tags": [ "python", "type-safety" ], "Title": "Pythonic type coercion from input" }
23531
<p>I'm learning C and today I wrote a program that displays info about my hardware on ubuntu. </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main() { char ch, file_name[25] = "/proc/scsi/scsi"; FILE *fp; fp = fopen(file_name,"r"); // read mode if( fp == NULL ) { perror("Error while opening the file.\n"); exit(EXIT_FAILURE); } printf("The contents of %s file are :\n", file_name); while( ( ch = fgetc(fp) ) != EOF ) printf("%c",ch); fclose(fp); return 0; } </code></pre> <p>For me it looked like this</p> <pre><code>$ cc driveinfo.c;./a.out The contents of /proc/scsi/scsi file are : Attached devices: Host: scsi0 Channel: 00 Id: 00 Lun: 00 Vendor: ATA Model: WDC WD2500JS-75N Rev: 10.0 Type: Direct-Access ANSI SCSI revision: 05 Host: scsi1 Channel: 00 Id: 00 Lun: 00 Vendor: ATA Model: ST3250824AS Rev: 3.AD Type: Direct-Access ANSI SCSI revision: 05 Host: scsi2 Channel: 00 Id: 00 Lun: 00 Vendor: TSSTcorp Model: DVD+-RW TS-H653A Rev: D300 Type: CD-ROM ANSI SCSI revision: 05 Host: scsi3 Channel: 00 Id: 00 Lun: 00 Vendor: Optiarc Model: DVD-ROM DDU1681S Rev: 102A Type: CD-ROM ANSI SCSI revision: 05 Host: scsi4 Channel: 00 Id: 00 Lun: 00 Vendor: Lexar Model: USB Flash Drive Rev: 1100 Type: Direct-Access ANSI SCSI revision: 00 Host: scsi5 Channel: 00 Id: 00 Lun: 00 Vendor: WD Model: 5000AAKB Externa Rev: l108 Type: Direct-Access ANSI SCSI revision: 00 </code></pre> <p>Can it run on other unices e.g. bsd? How can I make it run on ms-windows? Can I query the hardware directly instead of the file <code>/proc/scsi/scsi</code> ?</p> <h2>Update</h2> <p>Thanks a lot. Here are my updates.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(int argc, char **argv) { int ch; char file_name[25] = "/proc/scsi/scsi"; FILE *fp; fp = fopen(file_name,"r"); // read mode if (fp == NULL) { perror(file_name); exit(EXIT_FAILURE); } printf("The contents of %s file are :\n", file_name); while ((ch = fgetc(fp)) != EOF) putchar(ch); fclose(fp); return 0; } </code></pre> <p>Test run</p> <pre><code>$ cc driveinfo.c;./a.out The contents of /proc/scsi/scsi file are : Attached devices: Host: scsi0 Channel: 00 Id: 00 Lun: 00 Vendor: ATA Model: WDC WD2500JS-75N Rev: 10.0 Type: Direct-Access ANSI SCSI revision: 05 Host: scsi1 Channel: 00 Id: 00 Lun: 00 Vendor: ATA Model: ST3250824AS Rev: 3.AD Type: Direct-Access ANSI SCSI revision: 05 Host: scsi2 Channel: 00 Id: 00 Lun: 00 Vendor: TSSTcorp Model: DVD+-RW TS-H653A Rev: D300 Type: CD-ROM ANSI SCSI revision: 05 Host: scsi3 Channel: 00 Id: 00 Lun: 00 Vendor: Optiarc Model: DVD-ROM DDU1681S Rev: 102A Type: CD-ROM ANSI SCSI revision: 05 Host: scsi4 Channel: 00 Id: 00 Lun: 00 Vendor: Lexar Model: USB Flash Drive Rev: 1100 Type: Direct-Access ANSI SCSI revision: 00 Host: scsi5 Channel: 00 Id: 00 Lun: 00 Vendor: WD Model: 5000AAKB Externa Rev: l108 Type: Direct-Access ANSI SCSI revision: 00 </code></pre> <h2>Latest version</h2> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(int argc, char **argv) { int ch; char file_name[] = "/proc/scsi/scsi"; char cpu_file_name[] = "/proc/cpuinfo"; FILE *fp; FILE *cpu_fp; fp = fopen(file_name,"r"); // read mode cpu_fp = fopen(cpu_file_name,"r"); // read mode if (fp == NULL) { perror(file_name); exit(EXIT_FAILURE); } while ((ch = fgetc(fp)) != EOF) { putchar(ch); } fclose(fp); if (cpu_fp == NULL) { perror(cpu_file_name); exit(EXIT_FAILURE); } while ((ch = fgetc(cpu_fp)) != EOF) { putchar(ch); } fclose(cpu_fp); return 0; } </code></pre> <hr> <p>Test</p> <pre><code>$ cat cpu-disk-info.c;clang -Wconversion cpu-disk-info.c;./a.out #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(int argc, char **argv) { int ch; char file_name[] = "/proc/scsi/scsi"; char cpu_file_name[] = "/proc/cpuinfo"; FILE *fp; FILE *cpu_fp; fp = fopen(file_name,"r"); // read mode cpu_fp = fopen(cpu_file_name,"r"); // read mode if (fp == NULL) { perror(file_name); exit(EXIT_FAILURE); } while ((ch = fgetc(fp)) != EOF) { putchar(ch); } fclose(fp); if (cpu_fp == NULL) { perror(cpu_file_name); exit(EXIT_FAILURE); } while ((ch = fgetc(cpu_fp)) != EOF) { putchar(ch); } fclose(cpu_fp); return 0; } Attached devices: Host: scsi0 Channel: 00 Id: 00 Lun: 00 Vendor: ATA Model: WDC WD2500JS-75N Rev: 10.0 Type: Direct-Access ANSI SCSI revision: 05 Host: scsi1 Channel: 00 Id: 00 Lun: 00 Vendor: ATA Model: ST3250824AS Rev: 3.AD Type: Direct-Access ANSI SCSI revision: 05 Host: scsi2 Channel: 00 Id: 00 Lun: 00 Vendor: TSSTcorp Model: DVD+-RW TS-H653A Rev: D300 Type: CD-ROM ANSI SCSI revision: 05 Host: scsi3 Channel: 00 Id: 00 Lun: 00 Vendor: Optiarc Model: DVD-ROM DDU1681S Rev: 102A Type: CD-ROM ANSI SCSI revision: 05 Host: scsi4 Channel: 00 Id: 00 Lun: 00 Vendor: Lexar Model: USB Flash Drive Rev: 1100 Type: Direct-Access ANSI SCSI revision: 00 Host: scsi5 Channel: 00 Id: 00 Lun: 00 Vendor: WD Model: 5000AAKB Externa Rev: l108 Type: Direct-Access ANSI SCSI revision: 00 processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 15 model name : Intel(R) Core(TM)2 CPU 6400 @ 2.13GHz stepping : 6 microcode : 0xc6 cpu MHz : 2128.073 cache size : 2048 KB physical id : 0 siblings : 2 core id : 0 cpu cores : 2 apicid : 0 initial apicid : 0 fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts nopl aperfmperf pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm lahf_lm dtherm tpr_shadow bogomips : 4256.14 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: processor : 1 vendor_id : GenuineIntel cpu family : 6 model : 15 model name : Intel(R) Core(TM)2 CPU 6400 @ 2.13GHz stepping : 6 microcode : 0xc6 cpu MHz : 2128.073 cache size : 2048 KB physical id : 0 siblings : 2 core id : 1 cpu cores : 2 apicid : 1 initial apicid : 1 fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts nopl aperfmperf pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm lahf_lm dtherm tpr_shadow bogomips : 4256.00 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: dev@dev-OptiPlex-745:~$ </code></pre> <h2>Very latest version with new function</h2> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; void info(char file_name[]) { int ch; FILE *fp; fp = fopen(file_name,"r"); // read mode if (fp == NULL) { perror(file_name); exit(EXIT_FAILURE); } while ((ch = fgetc(fp)) != EOF) { putchar(ch); } fclose(fp); } int main(int argc, char **argv) { info("/proc/scsi/scsi"); info("/proc/cpuinfo"); return 0; } </code></pre> <p>Test </p> <pre><code>$ cat cpu-disk-info.c;clang -Wconversion cpu-disk-info.c;./a.out #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; void info(char file_name[]) { int ch; FILE *fp; fp = fopen(file_name,"r"); // read mode if (fp == NULL) { perror(file_name); exit(EXIT_FAILURE); } while ((ch = fgetc(fp)) != EOF) { putchar(ch); } fclose(fp); } int main(int argc, char **argv) { info("/proc/scsi/scsi"); info("/proc/cpuinfo"); return 0; } Attached devices: Host: scsi0 Channel: 00 Id: 00 Lun: 00 Vendor: ATA Model: WDC WD2500JS-75N Rev: 10.0 Type: Direct-Access ANSI SCSI revision: 05 Host: scsi1 Channel: 00 Id: 00 Lun: 00 Vendor: ATA Model: ST3250824AS Rev: 3.AD Type: Direct-Access ANSI SCSI revision: 05 Host: scsi2 Channel: 00 Id: 00 Lun: 00 Vendor: TSSTcorp Model: DVD+-RW TS-H653A Rev: D300 Type: CD-ROM ANSI SCSI revision: 05 Host: scsi3 Channel: 00 Id: 00 Lun: 00 Vendor: Optiarc Model: DVD-ROM DDU1681S Rev: 102A Type: CD-ROM ANSI SCSI revision: 05 Host: scsi4 Channel: 00 Id: 00 Lun: 00 Vendor: Lexar Model: USB Flash Drive Rev: 1100 Type: Direct-Access ANSI SCSI revision: 00 Host: scsi5 Channel: 00 Id: 00 Lun: 00 Vendor: WD Model: 5000AAKB Externa Rev: l108 Type: Direct-Access ANSI SCSI revision: 00 processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 15 model name : Intel(R) Core(TM)2 CPU 6400 @ 2.13GHz stepping : 6 microcode : 0xc6 cpu MHz : 2128.073 cache size : 2048 KB physical id : 0 siblings : 2 core id : 0 cpu cores : 2 apicid : 0 initial apicid : 0 fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts nopl aperfmperf pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm lahf_lm dtherm tpr_shadow bogomips : 4256.14 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: processor : 1 vendor_id : GenuineIntel cpu family : 6 model : 15 model name : Intel(R) Core(TM)2 CPU 6400 @ 2.13GHz stepping : 6 microcode : 0xc6 cpu MHz : 2128.073 cache size : 2048 KB physical id : 0 siblings : 2 core id : 1 cpu cores : 2 apicid : 1 initial apicid : 1 fpu : yes fpu_exception : yes cpuid level : 10 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts nopl aperfmperf pni dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdcm lahf_lm dtherm tpr_shadow bogomips : 4256.00 clflush size : 64 cache_alignment : 64 address sizes : 36 bits physical, 48 bits virtual power management: </code></pre> <h2>2 strategies implemented</h2> <p>I tried implementing 1024 bytes i/o for 2 strategies. I'm not sure but the chunkinfo function can be better. I didn't find the source to the unix program cat but I try something similar. </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define CHUNK 1024 /* read 1024 bytes at a time */ void info(char file_name[]) { int ch; FILE *fp; fp = fopen(file_name,"r"); // read mode if (fp == NULL) { perror(file_name); exit(EXIT_FAILURE); } while ((ch = fgetc(fp)) != EOF) { putchar(ch); } fclose(fp); } void chunkinfo(char file_name[]) { char buf[CHUNK]; FILE *file; size_t nread; file = fopen(file_name, "r"); if (file) { while ((nread = fread(buf, 1, sizeof buf, file)) &gt; 0) fwrite(buf, 1, nread, stdout); if (ferror(file)) { /* deal with error */ } fclose(file); } } int main(int argc, char **argv) { info("/proc/scsi/scsi"); chunkinfo("/proc/cpuinfo"); return 0; } </code></pre> <p>For the record I also review how a cat.c implementation does it:</p> <pre><code>#include &lt;sys/param.h&gt; #include &lt;sys/stat.h&gt; #include &lt;ctype.h&gt; #include &lt;err.h&gt; #include &lt;errno.h&gt; #include &lt;fcntl.h&gt; #include &lt;locale.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; extern char *__progname; int bflag, eflag, nflag, sflag, tflag, vflag; int rval; char *filename; void cook_args(char *argv[]); void cook_buf(FILE *); void raw_args(char *argv[]); void raw_cat(int); int main(int argc, char *argv[]) { int ch; setlocale(LC_ALL, ""); while ((ch = getopt(argc, argv, "benstuv")) != -1) switch (ch) { case 'b': bflag = nflag = 1; /* -b implies -n */ break; case 'e': eflag = vflag = 1; /* -e implies -v */ break; case 'n': nflag = 1; break; case 's': sflag = 1; break; case 't': tflag = vflag = 1; /* -t implies -v */ break; case 'u': setbuf(stdout, NULL); break; case 'v': vflag = 1; break; default: (void)fprintf(stderr, "usage: %s [-benstuv] [-] [file ...]\n", __progname); exit(1); /* NOTREACHED */ } argv += optind; if (bflag || eflag || nflag || sflag || tflag || vflag) cook_args(argv); else raw_args(argv); if (fclose(stdout)) err(1, "stdout"); exit(rval); /* NOTREACHED */ } void cook_args(char **argv) { FILE *fp; fp = stdin; filename = "stdin"; do { if (*argv) { if (!strcmp(*argv, "-")) fp = stdin; else if ((fp = fopen(*argv, "r")) == NULL) { warn("%s", *argv); rval = 1; ++argv; continue; } filename = *argv++; } cook_buf(fp); if (fp != stdin) (void)fclose(fp); } while (*argv); } void cook_buf(FILE *fp) { int ch, gobble, line, prev; line = gobble = 0; for (prev = '\n'; (ch = getc(fp)) != EOF; prev = ch) { if (prev == '\n') { if (sflag) { if (ch == '\n') { if (gobble) continue; gobble = 1; } else gobble = 0; } if (nflag &amp;&amp; (!bflag || ch != '\n')) { (void)fprintf(stdout, "%6d\t", ++line); if (ferror(stdout)) break; } } if (ch == '\n') { if (eflag &amp;&amp; putchar('$') == EOF) break; } else if (ch == '\t') { if (tflag) { if (putchar('^') == EOF || putchar('I') == EOF) break; continue; } } else if (vflag) { if (!isascii(ch)) { if (putchar('M') == EOF || putchar('-') == EOF) break; ch = toascii(ch); } if (iscntrl(ch)) { if (putchar('^') == EOF || putchar(ch == '\177' ? '?' : ch | 0100) == EOF) break; continue; } } if (putchar(ch) == EOF) break; } if (ferror(fp)) { warn("%s", filename); rval = 1; clearerr(fp); } if (ferror(stdout)) err(1, "stdout"); } void raw_args(char **argv) { int fd; fd = fileno(stdin); filename = "stdin"; do { if (*argv) { if (!strcmp(*argv, "-")) fd = fileno(stdin); else if ((fd = open(*argv, O_RDONLY, 0)) &lt; 0) { warn("%s", *argv); rval = 1; ++argv; continue; } filename = *argv++; } raw_cat(fd); if (fd != fileno(stdin)) (void)close(fd); } while (*argv); } void raw_cat(int rfd) { int wfd; ssize_t nr, nw, off; static size_t bsize; static char *buf = NULL; struct stat sbuf; wfd = fileno(stdout); if (buf == NULL) { if (fstat(wfd, &amp;sbuf)) err(1, "stdout"); bsize = MAX(sbuf.st_blksize, BUFSIZ); if ((buf = malloc(bsize)) == NULL) err(1, "malloc"); } while ((nr = read(rfd, buf, bsize)) != -1 &amp;&amp; nr != 0) for (off = 0; nr; nr -= nw, off += nw) if ((nw = write(wfd, buf + off, (size_t)nr)) == 0 || nw == -1) err(1, "stdout"); if (nr &lt; 0) { warn("%s", filename); rval = 1; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-14T04:59:56.987", "Id": "65624", "Score": "1", "body": "It may be better to ask a new question when you have an updated version of the code, instead of editing it into an existing question. That way it will get a more attention and a more specific review." } ]
[ { "body": "<p>It can run on BSD since you wrote a cross-platform code and /proc/scsi/scsi is present on BSD as well.\nYes, you can list the installed hardware using ioctl calls, see <a href=\"https://stackoverflow.com/questions/2698465/how-to-find-out-if-scsi-device-say-etc-sda-is-a-disk-or-not-via-ioctl-calls-o\">https://stackoverflow.com/questions/2698465/how-to-find-out-if-scsi-device-say-etc-sda-is-a-disk-or-not-via-ioctl-calls-o</a>\nIt seems you can use IOCTL on Windows too. (<a href=\"http://msdn.microsoft.com/en-us/library/aa363219%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa363219%28VS.85%29.aspx</a>).</p>\n\n<p>After a few researches, I found that might correspond to your needs <a href=\"http://www.qtfr.org/viewtopic.php?id=13210\" rel=\"nofollow noreferrer\">http://www.qtfr.org/viewtopic.php?id=13210</a></p>\n\n<p>I just found <a href=\"http://www.tldp.org/HOWTO/archived/SCSI-Programming-HOWTO/\" rel=\"nofollow noreferrer\">this guide</a> on SCSI that deals with programming </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T14:06:04.180", "Id": "23535", "ParentId": "23534", "Score": "2" } }, { "body": "<p>Nick, a few comments on the code:</p>\n\n<ul>\n<li>define only one variable per line</li>\n<li><code>ch</code> should be an int not char</li>\n<li><p>I prefer to see a space after <code>if</code>, <code>while</code> etc and no spaces inside the brackets</p>\n\n<pre><code>if (fp == NULL)\n</code></pre></li>\n<li><p>pass the filename to perror, not your own text (and certainly don't add a\n\\n). Here's what it prints for me:</p>\n\n<pre><code>Error while opening the file.\n: No such file or directory\n</code></pre>\n\n<p>It doesn't tell me which file. Here's what I would expect:</p>\n\n<pre><code>/proc/scsi/scsi: No such file or directory\n</code></pre></li>\n<li><p>add braces in the while, even if strictly unnecessary.</p></li>\n<li><p>use <code>putchar</code> instead of <code>printf</code> for single chars</p></li>\n<li><p>As <code>ch</code> is the wrong type it cannot really hold 'EOF'. It appears to work\nbecause EOF is converted to (char) -1 and then converted to (int) -1 for the\ncomparison. If the file happened to hold a value 255 the loop would exit\nthere. Try it by running this code and redirecting to a file, then reading\nit with your program:</p>\n\n<pre><code>int main(int argc, char **argv)\n{\n printf(\"hello\\n\");\n putchar(255);\n printf(\"world\\n\");\n return 0;\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T17:56:04.760", "Id": "36323", "Score": "0", "body": "Many thanks. I updated, compiled and ran code with `perror(file_name);` posting the complete program the the question so that you can view that the updates you suggest appear to work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T20:45:30.080", "Id": "36328", "Score": "2", "body": "Looks better - you forgot the braces on the `while {}`. BTW, the compiler (clang compiler anyway) would have warned you about the conversion error if you had included -Wconversion to the warnings. BTW2, you can omit the 25 in file_name[]" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T21:03:11.363", "Id": "36329", "Score": "0", "body": "Yes I can confirm that the clang compiler will warn about this but not gcc." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T17:32:01.277", "Id": "23545", "ParentId": "23534", "Score": "3" } }, { "body": "<p>Based on your latest version, have a look at this section of the code:</p>\n\n<pre><code>fp = fopen(file_name,\"r\"); // read mode \ncpu_fp = fopen(cpu_file_name,\"r\"); // read mode \nif (fp == NULL)\n{\n perror(file_name);\n exit(EXIT_FAILURE);\n} \nwhile ((ch = fgetc(fp)) != EOF)\n{\n putchar(ch); \n}\nfclose(fp);\nif (cpu_fp == NULL)\n{\n perror(cpu_file_name);\n exit(EXIT_FAILURE);\n} \nwhile ((ch = fgetc(cpu_fp)) != EOF)\n{\n putchar(ch); \n}\nfclose(cpu_fp);\n</code></pre>\n\n<p>That's essentially two identical sections of code, if you disregard the filename. Try to make a function instead that you can call twice. Something like:</p>\n\n<pre><code>show_hardware_info(\"/proc/scsi/scsi\");\nshow_hardware_info(\"/proc/cpuinfo\");\n</code></pre>\n\n<p>Also you should be able to read more than one char at the time from the file. Reading line by line, or even a fixed size buffer at the time should be more efficient.</p>\n\n<p><strong>Update:</strong></p>\n\n<p>Nice that you tried different approaches with the functions. One thing that I would do differently, though, is to not call the <code>exit()</code> function from within the functions of your program. Even if reading the scsi-info fails, it may make sence to read the cpuinfo. Instead return some value from your function to indicate if it was successful or not. In this way the caller can determine if it's worthwhile to continue, to propagate the error further or simply to terminate the program.</p>\n\n<p>Something like this is a common idiom in C, where the function will reuturn <code>0</code> if successful and some negative value to indicate an error:</p>\n\n<pre><code>int myfunction(const char * arg)\n{\n if (!valid_args(arg))\n return -1;\n\n do_some_work();\n\n return 0;\n}\n</code></pre>\n\n<p>Also, you should pay attention to the indentation. The while loop in <code>chunkinfo()</code> seems off. This makes it difficult to know if you want the <code>if</code>-statement to execute for each iteration or only after the loop is finished. As it is now, the latter is the case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T22:35:17.763", "Id": "36332", "Score": "0", "body": "Thanks. I've also been scanning the net for the source to the unix program cat that displays a text file. I'll make a function like you mention." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T01:47:38.140", "Id": "36335", "Score": "1", "body": "I added 1024 bytes buffering if you like to have another look. I didn't add a function that reads line by line but I might." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T22:31:10.933", "Id": "23555", "ParentId": "23534", "Score": "2" } } ]
{ "AcceptedAnswerId": "23535", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T13:46:10.137", "Id": "23534", "Score": "-1", "Tags": [ "c", "linux" ], "Title": "Possible improvements for this small C program?" }
23534
<p>I'm writing a small Win32 console app that manipulates the contents of binary files. It accepts the filename as a command line parameter and writes to a file named filename.scramble</p> <p>This is the first time I'm dynamically allocating memory for C strings (which I'm using since the <code>fstream</code> functions use <code>const char*</code>).</p> <p>I've added the comments to help you understand what I'm trying to do. Please tell me whether I'm doing anything unsafe with pointers or whether I'm allocating memory wrong or any unsafe practice you see regarding dynamically allocating and concatenating C strings in C++. My question is specifically about the strings and the memory management.</p> <pre><code>#include&lt;iostream&gt; #include&lt;fstream&gt; using namespace std; int main(int argc, char *argv[]) { //Program needs at least one extra argument //If less, print 'usage' if (argc &lt; 2) cout&lt;&lt;"usage: "&lt;&lt; argv[0] &lt;&lt;" &lt;filename&gt;\n"; else { //Assuming argv[1] is a file name fstream fin (argv[1],ios::binary|ios::in); if (!fin.is_open()) cout&lt;&lt;"Could not open file\n"; else { //Calculate size of file fin.seekg(0,ios::end); unsigned long long size = fin.tellg(); //Find out how many left over characters //if using blocks of 16 characters int lastset=size%16; //Change size to number of blocks size /= 16; //File name must be &lt;original filename&gt;.scramble //Allocate space char* name = new char[sizeof(argv[1])+8]; //Concatenate &lt;original filename&gt; strcat_s(name,sizeof(argv[1]),argv[1]); //Concatenate ".scramble" strcat_s(name,sizeof(argv[1])+8,".scramble"); fstream fout (name,ios::binary|ios::out); //Buffer char memblock[16]; fin.seekg(0,ios::beg); //Read from fin and write to fout in blocks of 16 characters for(unsigned long long i=0;i&lt;size;++i) { fin.read(memblock,16); /* * * Manipulation on memblock to be done here * */ fout.write(memblock,16); } //No manipulation for last n bytes, n&lt;16 fin.read(memblock,lastset); fout.write(memblock,lastset); fin.close(); fout.close(); delete[] name; } } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T02:52:05.823", "Id": "36449", "Score": "0", "body": "I'd suggest creating the output file name using something like `std::string name(argv[1] + std::string(\".scramble\"));`" } ]
[ { "body": "<p>There is no need for manual dynamic memory allocation.</p>\n\n<p>Don't use this:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>It causes lots of problems in anything but a small application. So get into the habbit of not using it. If you muse be lazy specifically import the things you need. Notice in the code below I always use the prefix <code>std::</code> five letters is not a big overhead for being exact.</p>\n\n<pre><code>using std::cout;\nusing std::ifstream;\n</code></pre>\n\n<p>For a good discussion see <a href=\"https://stackoverflow.com/q/1452721/14065\">https://stackoverflow.com/q/1452721/14065</a> my favorite answer to this question is <a href=\"https://stackoverflow.com/a/1453605/14065\">https://stackoverflow.com/a/1453605/14065</a></p>\n\n<p>Don't write comments where you explain what the code is doing. The code is already verbose enough to explain what. If you are going to comment explain \"WHY\" you are doing this. Over commenting is a real problem and you should use comments judiciously and explain why. <a href=\"https://softwareengineering.stackexchange.com/a/13/12917\">https://softwareengineering.stackexchange.com/a/13/12917</a></p>\n\n<pre><code> //Program needs at least one extra argument\n //If less, print 'usage'\n</code></pre>\n\n<p>If your condition exits the program. Return an error code immediately. This makes the alignment and reading of the rest of your code easier:</p>\n\n<pre><code> if (argc &lt; 2) \n cout&lt;&lt;\"usage: \"&lt;&lt; argv[0] &lt;&lt;\" &lt;filename&gt;\\n\";\n\n else \n {\n</code></pre>\n\n<p>Easier to write as:</p>\n\n<pre><code> if (argc &lt; 2) \n {\n cout&lt;&lt;\"usage: \"&lt;&lt; argv[0] &lt;&lt;\" &lt;filename&gt;\\n\";\n return 1;\n }\n &lt;rest of code&gt;\n</code></pre>\n\n<p>Same comment as above.</p>\n\n<pre><code> if (!fin.is_open())\n cout&lt;&lt;\"Could not open file\\n\";\n</code></pre>\n\n<p>The best way to comment this. Is to put this code in a function with an appropriate name. Then don't write the comments (the code is self explanatory). You may write a comment about <strong>\"why\"</strong> you are using 16 as this will help a maintainer to modify dependant code.</p>\n\n<pre><code> //Calculate size of file\n fin.seekg(0,ios::end);\n unsigned long long size = fin.tellg();\n //Find out how many left over characters\n //if using blocks of 16 characters\n int lastset=size%16;\n //Change size to number of blocks\n size /= 16;\n</code></pre>\n\n<p>Easier to read as:</p>\n\n<pre><code> int size = getNumberOf16ByteBlocksFromStream(fin);\n</code></pre>\n\n<p>It is very rare that you need to use new/delete. It is even rarer that you would use delete as any object created with new should be put in an object that manages its lifespan correctly. If you don't do this writing exception safe code is exceedingly hard.</p>\n\n<p>In this case you can achieve the same affect by using a std::vector</p>\n\n<pre><code> //File name must be &lt;original filename&gt;.scramble\n //Allocate space\n char* name = new char[sizeof(argv[1])+8];\n</code></pre>\n\n<p>Use std::vector for simple buffers. Its exception safe.</p>\n\n<pre><code> std::vector&lt;char&gt; name(strlen(argv[1]) + 8);\n\n // To get the address of the first byte use &amp;name[0];\n</code></pre>\n\n<p>Note that <code>sizeof()</code> gives you the number of bytes in the variable. This does not give you the length of the string. the size of the variable in this case is the size of the pointer that is pointing at the string (so 4 or 8 depending on the system). Use <code>strlen()</code> to get the size of a string.</p>\n\n<p>Also the <code>+8</code> is wrong. As <code>.scramble</code> is 9 characters and you need to add a byte for the terminating <code>\\0</code> character. So in reality you should use std::string to build the filename. Again the comments are worse the useless (not because you wrote bad comments, but because the comments can go out of sync with the code. Then a maintainer will wonder why the code does not match the comments. Also this code is so trivial that you should be able to see what it is trying to do).</p>\n\n<pre><code> //Concatenate &lt;original filename&gt;\n strcat_s(name,sizeof(argv[1]),argv[1]);\n //Concatenate \".scramble\"\n strcat_s(name,sizeof(argv[1])+8,\".scramble\");\n\n // PS you got the usage all long.\n // I am very surprised if this actually runs correctly.\n // Normal operation.\n // 1) string-copy the first part\n // 2) string-cat all subsequent parts.\n // 3) The size (Second field) in &lt;X&gt;_s() functions is the\n // TOTAL SIZE OF THE BUFFER\n // not how much you want to copy. This should ALWAYS\n // match the value you used in allocation.\n</code></pre>\n\n<p>Easier to write as:</p>\n\n<pre><code> std::string filename = argv[1];\n filename += \".scramble\"\n</code></pre>\n\n<p>That's is a very small buffer:</p>\n\n<pre><code> char memblock[16];\n</code></pre>\n\n<p>You should probably have re-set the stream up where you were messing around with it finding the size.</p>\n\n<pre><code> fin.seekg(0,ios::beg);\n</code></pre>\n\n<p>No need to manually close files. The destructor will do that. <a href=\"https://codereview.stackexchange.com/a/544/507\">https://codereview.stackexchange.com/a/544/507</a></p>\n\n<pre><code> fin.close();\n fout.close();\n</code></pre>\n\n<p>This delete is not exception safe.<br>\nNot a problem in this code. But in general you should try and make them exception safe so you don't leak. This means using RAII.</p>\n\n<pre><code> delete[] name;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T16:21:49.130", "Id": "23543", "ParentId": "23536", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T14:09:52.563", "Id": "23536", "Score": "3", "Tags": [ "c++", "strings", "memory-management", "console" ], "Title": "Dynamically allocated C strings in C++, concatenation, pointers, etc" }
23536
<p>How can I optimize this?</p> <pre><code>&lt;cfftp connection = "myConnection" username = "#username#" password = "#password#" server = "#server#" action = "open" timeout = "500" stopOnError = "Yes"&gt; &lt;cfloop index="i" from="1" to="#ArrayLen(ImagesArray)#"&gt; &lt;cfset slocal = "temp\" &amp; ImagesArray[i] &gt; &lt;cfset sremoteFile = "Images\" &amp; ImagesArray[i]&gt; &lt;cftry&gt; &lt;cfftp connection = "myConnection" action = "getFile" name = "uploadFile" transferMode = "binary" failIfExists = "false" localFile = "#slocal#" remoteFile = "#sremoteFile#" /&gt; &lt;cfcatch&gt; &lt;cfabort&gt; &lt;/cfcatch&gt; &lt;/cftry&gt; &lt;cfset files = files &amp; "|" &amp; slocalFile&gt; &lt;cfset fileliste = fileliste &amp; arFiles[i] &amp; "|"&gt; &lt;/cfloop&gt; &lt;cfftp connection = "myConnection" action = "close" stopOnError = "Yes"&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T15:02:25.410", "Id": "36315", "Score": "1", "body": "Could you give us more details on what you're trying to optimize? How many images are being FTP'd? What operating system are you using?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T15:18:48.783", "Id": "36317", "Score": "0", "body": "The number of images can vary from 1 to 100 and usning Windows Server." } ]
[ { "body": "<p>In my experience, FTP can use up a lot of network packets and CPU time just negotiating the starting and finishing of a single file. If there exists the option of having an archive uncompressed at the destination, I would suggest zipping the images into a single file for transport.</p>\n\n<p>To get even more performance for the end user making the CF request you could perform the FTP transfer in an asynchronous thread via cfthread. Launch the thread that zips and sends the file and let the user know that the data is on its way.</p>\n\n<p>Hope this helps, or at least inspires some new ideas.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T03:14:29.333", "Id": "36882", "ParentId": "23539", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T14:53:19.740", "Id": "23539", "Score": "2", "Tags": [ "performance", "coldfusion", "cfml" ], "Title": "Image transfer script" }
23539
<p>Most of my slow queries on my server are due to a single "find" query. I have a collection that represents website pages. I want to be able to look up a page in the collection by URL. The caveat is that a website might have URLs that redirect to it.</p> <p>I've modeled my schema (with Node.js/Mongoose) like this:</p> <pre><code>{ 'url': { type: String, index: {unique: true, dropDups: true} }, 'redirects': { type: Array, index: true }, // ... other stuff } </code></pre> <p>In other words, one entry might have the URL <code>http://codereview.stackexchange.com/</code> but also have an array of 5 other URLs (such as bit.ly URLs) that redirect to it.</p> <p>Later, I want to query the collection to see if we have an entry which matches an arbitrary set of URLs. I don't know if the URLs are redirected URLs or what -- I just want to find all matches in my collection that represent these URLs.</p> <p>So I do this:</p> <pre><code>// urls is an array of URL strings we want to find... model.find({$or: [{'url': {$in: urls}}, {'redirects': {$in: urls}}]}).lean().exec( ... ); </code></pre> <p>Unfortunately, I might be looking for around 200 URLs at once, so this query sometimes takes > 1 second.</p> <p>Is there further optimization I can do, or would it be better to split the query into multiple queries, capping the search-size each time?</p>
[]
[ { "body": "<p>I haven't used MongoDB, but I have a few suggestions based on experiences with optimization and other databases.</p>\n\n<ol>\n<li><p>Index hashes of the URLs and search for those instead. Using a simple MD5 hash would probably speed up searching with the cost of dealing with false positives (unlikely but possible).</p></li>\n<li><p>Store every URL as a top-level object and add a <code>redirectsTo</code> attribute. This alleviates the need to index or search the <code>redirects</code> collections. While now you need to perform two queries--one for the original URLs and another for the redirected URLs--this could end up being faster if only a small percentage of URLs are redirects.</p>\n\n<p>Here's some psuedocode to clarify what I mean:</p>\n\n<pre><code>all = []\nfound = model.find({'url': {$in: urls}})...\nredirects = []\nfor each item in found\n if item.redirectsTo\n redirects += item.redirectsTo\n else\n all += item\nredirected += model.find({'url': {$in: redirects}})...\nfor each item in redirected\n all += item\n</code></pre></li>\n<li><p>Update your question with the higher-level problem you're trying to solve. I often find that when I'm trying to optimize slow task <code>T</code> to solve problem <code>P</code>, the better approach is to rethink <code>P</code>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T16:24:30.363", "Id": "23544", "ParentId": "23542", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T15:49:42.807", "Id": "23542", "Score": "3", "Tags": [ "javascript", "node.js", "mongodb" ], "Title": "Query for finding collection entries matching an arbitrary set of URLs" }
23542
<p>Would you be kind to make me a code review? It would be nice to have some comments, whether you would have done something differently and so on. I am not sure about the way I handle the exception. Is there a better way?</p> <pre><code>@Transactional public classServiceImpl implements Service { private static final Logger LOG = Logger.getLogger(HermesServiceImpl.class); @Autowired(required = true) private Client client; @Autowired private SubmissionDAO submissionDAO; @Autowired private SubmissionSender hrsQueueSender; @Transactional @Override public void registerDocument(String submissionId) { final long start = System.currentTimeMillis(); final List&lt;HermesItem&gt; items = submissionDAO.getSubmissionItems(submissionId); RegistrationSummary regSummary = null; if (!items.isEmpty()) { final HrsDocumentBuilder builder = new HrsDocumentBuilder(); final Date docDate = new Date(); builder.setTitle(submissionId); builder.setDocumentDate(docDate); builder.setSentDate(docDate); builder.setMailType(HermesMailType.INTERNAL); /* Document is constructed, try to invoke Hermes - upload annexes and register document. */ try { regSummary = client.registerDocument(builder.buildDocument()); } catch (final ClientException e) { LOG.error("Unable to register document with Submission Id= [" + submissionId + "], " + e.getMessage()); } if (regSummary != null) { final String hermesDocId = regSummary.getHermesDocumentId(); /* Update the DB with the documentID received from Hermes. */ final int update = submissionDAO.updateSubmission(submissionId, hermesDocId, SubmissionStatus.HRS_REGISTERED.name()); if (update &lt; 1) { LOG.error("update error"); } } else { submissionDAO.updateSubmission(submissionId, null, SubmissionStatus.HRS_FAILED.name()); hrsQueueSender.sendMesage(submissionId); } } else { LOG.error("Not found"); submissionDAO.updateSubmission(submissionId, null, SubmissionStatus.ANNEXES_NOT_FOUND.name()); } } } </code></pre>
[]
[ { "body": "<p>Few points:</p>\n\n<ul>\n<li>Try to avoid long or nested if/else </li>\n<li>Sub-divide tasks in smaller functions(clean and more readable code + easier unit testing)</li>\n<li>Minimize variable scope(try to declare variables in the scope where you really need them)</li>\n<li>Think about Exception in context of your business domain, may be using builder pattern (like HrsDocumentBuilder) can be useful to have consistent logging message for same type of exception(<strong>override toString() method</strong>).</li>\n</ul>\n\n<p>We can refactor the method <strong>registerDocument()</strong> like this:</p>\n\n<p>You may replace </p>\n\n<pre><code>final long start = System.currentTimeMillis();\n</code></pre>\n\n<p>with <a href=\"http://static.springsource.org/spring/docs/1.1.5/api/org/springframework/util/StopWatch.html\" rel=\"nofollow\">StopWatch</a></p>\n\n<pre><code>@Transactional\n@Override\npublic void registerDocument(String submissionId) {\nfinal long start = System.currentTimeMillis(); \nfinal List&lt;HermesItem&gt; items = submissionDAO.getSubmissionItems(submissionId);\n\nif (!hasItems(items)) //extract else to method\n return;\n\nfinal HrsDocumentBuilder builder = ...builder.setMailType(HermesMailType.INTERNAL);//stays the same\ntry {\n // minimized the scope of local variable, you need regSummary in try block so declare it here.\n RegistrationSummary regSummary = client.registerDocument(builder.buildDocument()); // will rename buildDocument() -&gt; build() \n update(regSummary);\n\n} catch (final ClientException e) { \n\n //To standarized log message we can refactor it like :\n ClientExceptionBuilder b = new ClientExceptionBuilder(e).submissionId(submissionId).build();// override toString()\n LOG.error(b.getMessage());\n}\n}//function registerDocument() end here\n</code></pre>\n\n<p>Since all other method can be easily extracted from else blocks, i am posting only the <strong>update(regSummary)</strong> because this function can be further subdivide into two smaller functions like this:</p>\n\n<pre><code>void update(regSummary) {\n\n if(!hasSummary()) //extract else to method \n return \n\n final String hermesDocId = regSummary.getHermesDocumentId();\n /* Update the DB with the documentID received from Hermes. */\n final int update = submissionDAO.updateSubmission(submissionId, hermesDocId, SubmissionStatus.HRS_REGISTERED.name());\n\n if (update &lt; 1) \n LOG.error(\"update error\");\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T15:08:37.773", "Id": "23658", "ParentId": "23546", "Score": "1" } } ]
{ "AcceptedAnswerId": "23658", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T17:47:37.383", "Id": "23546", "Score": "2", "Tags": [ "java" ], "Title": "Review of document registrar" }
23546
<p>The following code works, but I'd like to re-write, so that a single index is returned, rather than a sequence of indexes visited.</p> <p>Here are the defs and function.</p> <pre><code>(def usage-vec-len 13) (def read-levels [9999 3000 2000 1000 100 90 80 70 60 50 40 30 10]) (defn sel-adj-idx "Finds the correct position at which to bin part of the reading." [reading] (for [idx (reverse (range 0 usage-vec-len)) :let [out-idx idx] :when (and (&lt;= reading (nth read-levels idx)) (&gt;= idx 0))] out-idx)) </code></pre> <p>If I run this with a reading of 5, I get what I expect</p> <pre><code>wtr-usage1.core=&gt; (sel-adj-idx 5) (12 11 10 9 8 7 6 5 4 3 2 1 0) wtr-usage1.core=&gt; (first (reverse (sel-adj-idx 5))) 0 wtr-usage1.core=&gt; </code></pre> <p>I keep going until the first index. The value of 5 would be binned there. I would like just to return the index, but still need to traverse read-levels to compare the reading against each of the levels.</p> <p>Is there a better form to use for this purpose? I could probably write this recursively, but am trying to see if I can do it with Clojure's rich set of sequence functions.</p>
[]
[ { "body": "<ul>\n<li><p>Why not use just what you posted? Like this:</p>\n\n<pre><code>;use better names\n(defn sel-adj-idx-fixed [reading] (first (reverse (sel-adj-idx reading))))\n</code></pre></li>\n<li><p><code>for</code> is used to generate sequences. Try <a href=\"http://clojuredocs.org/clojure_core/clojure.core/loop\" rel=\"nofollow\"><code>loop</code></a> for more general looping needs.</p></li>\n<li><p>You should not hard code the length of a data structure. Each time you update <code>read-levels</code> you will need to update <code>usage-vec-len</code>. Use <code>count</code> instead. It is supposed to be fast for vectors.</p></li>\n<li><p>A suggestion follows, Not a clojure programmer, so ignore the style:</p>\n\n<pre><code>(defn bin-idx [reading]\n \"......\"\n (second (first (drop-while #(&gt; reading (first %)) \n (map vector \n (reverse read-levels) \n (range))))))\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T11:51:39.020", "Id": "23562", "ParentId": "23547", "Score": "2" } }, { "body": "<p>How about:</p>\n\n<pre><code>(def ^:const read-levels [10 30 40 50 60 70 80 90 100 1000 2000 3000 9999]\n\n(defn bin-index [level]\n \"Finds the correct position at which to bin part of the reading.\" \n (letfn [(find-idx [idx read-level] \n (when (&gt; read-level level) idx))]\n (or (first (keep-indexed find-idx read-levels))) (count read-levels)))\n</code></pre>\n\n<p>Steps:</p>\n\n<ol>\n<li>Find the first index where the read level is greater than our level.</li>\n<li>Give the last index (simply the number of levels we have) if our\nlevel is greater than all read levels.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-04T21:38:51.790", "Id": "24733", "ParentId": "23547", "Score": "1" } } ]
{ "AcceptedAnswerId": "23562", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T17:51:14.777", "Id": "23547", "Score": "4", "Tags": [ "clojure" ], "Title": "Is there a better way to extract a single value instead of a sequence?" }
23547
<p>This code takes 8 divs and races them across the screen depending on which time value the div was assigned. How can I have coded this better so my code doesn't look so amateurish?</p> <p>I know I should have used something other than a hard coded 8 in my <code>for</code>-loop, but <code>timeArray.length</code> is unavailable since I am removing items from the array with splice.</p> <pre><code>$(document).ready(function() { var timeArray = new Array(3,4,5,6,7,8,9,10); var shortestTime = timeArray[7]; var fastestPony = {}; var index; var pony = { name: "pony", raceTime: -1, selected: "" }; //change the color of the pony when the user clicks on it $('.pony').bind('click', function() { $('.pony').removeClass('selectedPony'); $(this).addClass('selectedPony'); //get the pony that the user selected pony.selected = $(this); }); $('#startButton').click(function() { if (pony.selected == "") { alert("Please click the pony you think will win the race."); } else { for (i = 1; i &lt;= 8; i++) { //get a random number from the timeArray index = Math.floor(Math.random() * timeArray.length); pony.raceTime = timeArray[index]; //pull the random race time number out of the array //so it can't be assigned to another horse timeArray.splice(index, 1); //get the fastest pony if (pony.raceTime &lt; shortestTime) { shortestTime = pony.raceTime; fastestPony = $('#pony' + i); } //award the winner after the ponies have reached the finish line if (i == 8) { fastestPony.addClass('winner').append(' - Winner!'); } //send the horses on their way to race! $('#pony' + i).animate({left: '320px'}, pony.raceTime * 1000); } } }); //reset the ponies back to the starting line by reloading the page $('#resetButton').click(function() { document.location.reload(true); }); }); </code></pre>
[]
[ { "body": "<p><em>Note: As I type \"pony\" and \"ponies\" in my code, I can't help but wonder what the hell I'm doing with my time. Never thought I'd be writing words like that in javascript...</em></p>\n\n<p>Anyway! My first suggestion would be to make everything more flexible bynot relying on element IDs, and a set number of DIV elements. If you add or remove one, you'll have to make sure its ID is numbered correctly, and update your code to match. Much easier to just use jQuery to find and animate the DIVs, regardless of how many there are.</p>\n\n<p>In fact, the elements plus jQuery can tell you everything you need to know, so there's no need to store anything along the way.</p>\n\n<p>Also, the reset functionality is trivial. No need reload the entire page just for that.</p>\n\n<p>Lastly, and perhaps most importantly, you code announces the winner immediately - before the poni-- ahem, <em>the DIVs</em> have even raced. Yes, the winner is picked right away, and it's kinda' obvious which one will reach the goal first, but still. Better to announce the winner when it crosses the finish line.</p>\n\n<p>Of course, overall it'd be more fun to have something more random, where the DIVs move in fits and starts, so you can't tell who's going to win until the very end. But I'll stick to refactoring your current code.</p>\n\n<p><a href=\"http://jsfiddle.net/93Sv8/2/\" rel=\"nofollow\">Here's a demo of my version</a> and here's the code:</p>\n\n<pre><code>$(function() { // just pass in a function; it's the same as using $(document).ready()\n var ponies = $(\".pony\"), // Again: I never thought I'd write \"ponies\" in code\n raceButton = $(\"#raceButton\"); // use a single button for race and reset\n\n ponies.click(function (event) {\n ponies.removeClass('selected');\n $(this).addClass('selected');\n // no need to store the selection; we can always find it, now that it's got a \"selected\" class\n });\n\n // use one button for both start and reset\n raceButton.click(function() {\n // If we have a winner, the race is pretty much over\n // If we have no winner, and no elements currently animating, we're ready to race\n // Otherwise we're racing; don't do anything\n\n if( ponies.filter(\".winner\").length !== 0 ) {\n reset();\n } else if( ponies.filter(\".winner, :animated\").length === 0 ) {\n race();\n }\n });\n\n function race() {\n // check for selection\n if( ponies.filter(\".selected\").length === 0 ) {\n alert(\"Please click the pony you think will win the race.\");\n return; // return here instead of having a big else-block\n }\n\n var times = [], i, l;\n\n // disable the race button\n raceButton.prop(\"disabled\", true);\n\n // build time array; don't hardcode it\n for( i = 0, l = ponies.length ; i &lt; l ; i++ ) {\n times.push(i);\n }\n\n // Use .each() instead of relying on all the divs having numbered IDs.\n ponies.each(function () {\n var index = Math.floor(Math.random() * times.length),\n time = times[index],\n pony = $(this);\n\n times.splice(index, 1);\n\n // Use the onComplete callback to identify the winner\n pony.animate({left: '320px'}, {\n duration: (time + 3) * 1000, // only here do we set the minimum time by adding 3\n complete: function () {\n // If this was the fastest one\n if( time === 0 ) {\n pony\n .addClass(\"winner\")\n .append(\"&lt;span&gt;Winner!&lt;/span&gt;\"); // use a span or something, so it's easier to remove later\n\n // alert the gambler and enable the reset button\n if( pony.hasClass(\"selected\") ) {\n alert(\"You win tons of money or something\");\n } else {\n alert(\"You lost. Boo-hoo\");\n }\n raceButton.prop(\"disabled\", false).val(\"Reset\");\n }\n }\n });\n });\n }\n\n // just reset everything yourself; no need to reload\n function reset() {\n ponies\n .stop() // stop any running animations\n .removeClass(\"selected\") // clear selection\n .removeClass(\"winner\") // clear winner\n .css({ left: '0px' }) // move 'em back\n .children(\"span\").remove(); // remove the label\n raceButton.val(\"Race!\");\n }\n});\n</code></pre>\n\n<hr>\n\n<p>Addendum: As Sridhar points out in the comments, you there are some issues with the code above. Both are related to the state of the race, so one way to deal with it is to extract a few functions that check the state:</p>\n\n<pre><code>function raceInProgress() {\n return ponies.filter(\":animated\").length &gt; 0;\n}\n\nfunction raceDecided() {\n return ponies.filter(\".winner\").length &gt; 0\n}\n\nfunction raceNotStarted() {\n return !raceInProgress() &amp;&amp; !raceDecided();\n}\n</code></pre>\n\n<p>Now we can make sure that the gambler can't change the selection mid-race, by simply checking <code>raceInProgress()</code>. Plus, it's much easier to read and use than the raw jQuery selector magic.</p>\n\n<p>I've made the changes <a href=\"http://jsfiddle.net/b8Lan/1/\" rel=\"nofollow\">in this demo</a> rather than bothering to rewrite my original answer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T18:42:51.597", "Id": "36355", "Score": "0", "body": "+1 but just one point to mention, do we really need that \"else-if\" part to start the race, just a \"else\" should be sufficient right ? Since the \"Race\" button will be disabled (once the race is started) so I don't see the need to check whether the race is already going on as there is no way the user can start another race." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T19:23:17.100", "Id": "36357", "Score": "0", "body": "Also I think all the ponies(?) should not be select-able once the race is started else now am able to re-select a pony (possibly the winner pony) when the race is going on :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T19:40:16.530", "Id": "36360", "Score": "0", "body": "@Sridhar Both good points! I'll edit my answer a bit." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T22:20:52.407", "Id": "23554", "ParentId": "23548", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T18:39:50.307", "Id": "23548", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "Reading 8 divs across the screen depending on assignment time" }
23548
<p>I have recently just started learning Perl, so I decided to program the classic 'Guess my Number' game. I was wondering if anyone can spot any areas for improvement. As it's my first program, I expect there to be some unoptimized areas.</p> <pre><code>#!\usr\bin\perl print"Welcome to guess my number!\n"; $compNumber=int rand 100; while($n&lt;6){ print"Guess a number between 1 and 100: "; chomp($userNumber=&lt;STDIN&gt;); if($compNumber&gt;$userNumber){ print"Your guess was too low, try again.\n"; } if($compNumber&lt;$userNumber){ print"Your guess was too high, try again.\n"; } $n++ } if($compNumber==$userNumber){ print"Well done, $compNumber was my number! You got it correct in $n guesses!"; } if($compNumber!=$userNumber){ print"Unfortunately, you couldn't guess my number in 6 guesses, it was actually ${compNumber}."; } </code></pre>
[]
[ { "body": "<p>You could ask the user for a range between the random number should be choosen.\nAlso, you check is the user is right after he has tried 6 times, but what if he has right in less than 6 tries ? You better should write something like</p>\n\n<pre><code>boolean won = false\nint tries = 0\n\nwhile (tries &lt; MAX_TRIES || won == false)\n{\n /* ask for a number and compare it, if it is the right number, set win to true */\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T21:40:15.273", "Id": "23553", "ParentId": "23550", "Score": "5" } }, { "body": "<p>First, always <code>use strict; use warnings;</code> at the top of your code. The <code>strict</code> pragma restricts you to a sensible subset of Perl, which removes many sources for errors. Also, it forces you to declare all your variables with <code>my</code>. The <code>warnings</code> are very helpful, but non-fatal errors.</p>\n\n<p>If you are on a fairly modern perl (10 or later), you can use the <code>say</code> function. This works exactly like <code>print</code>, but appends a newline at the end. Enable this feature with <code>use feature 'say'</code> or <code>use 5.010</code>.</p>\n\n<p>If you have a set of mutually exclusive conditions in an <code>if</code>-cascade, you might want to look into the <code>if/elsif/else</code> structure.</p>\n\n<p>Your <code>while</code>-loop is meant to execute up to six times. Instead of <code>while</code>, you might want to use a range, and a <code>foreach</code> loop:</p>\n\n<pre><code>for (1 .. 6) {\n # this stuff executes six times\n}\n</code></pre>\n\n<p>Inside your loop, you only test if the user didn't hit the number. If his guessed number is equal to the secret num, then you continue with a new iteration. Don't.</p>\n\n<p>Also, I would pack the whole algorithm into a subroutine. This is a good habit, and allows us to do an early exit:</p>\n\n<pre><code>sub guess_my_number {\n my %args = @_; # cast the subroutine arguments to a hash\n my $maxnum = $args{maxnum} || 100; # unpack named arguments,\n my $tries = $args{tries} || 6; # or give default value\n\n my $secret = int rand $maxnum;\n\n GUESS: # a labeled loop\n for my $try (1 .. $tries) {\n say \"Guess a number between 0 and $maxnum:\";\n\n chomp( my $guess = &lt;STDIN&gt; );\n\n if ($guess == $secret) {\n say \"Yay, that was right! $secret was my number.\";\n say \"You managed in $try tries.\";\n return 1; # exit the subroutine\n } elsif ($guess &lt; $secret) {\n say \"Your guess was too low.\";\n } elsif ($guess &gt; $secret) {\n say \"Your guess was too big.\"\n }\n # This is executed for both too low or too large numbers:\n say \"You have \", $tries - $try, \" tries left.\";\n }\n\n # we land here if we didn't manage the guess\n say \"You failed to guess the correct number $secret in $tries guesses.\";\n return 0;\n}\n</code></pre>\n\n<p>And then in the main code:</p>\n\n<pre><code>guess_my_number(maxnum =&gt; 50, tries =&gt; 5);\n</code></pre>\n\n<p>All arguments are optional.</p>\n\n<p>The above might produce a session like</p>\n\n\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>Guess a number between 0 and 50:\n25\nYour guess was too low.\nYou have 4 tries left.\nGuess a number between 0 and 50:\n37\nYour guess was too low.\nYou have 3 tries left.\nGuess a number between 0 and 50:\n44\nYour guess was too big.\nYou have 2 tries left.\nGuess a number between 0 and 50:\n40\nYour guess was too low.\nYou have 1 tries left.\nGuess a number between 0 and 50:\n42\nYay, that was right! 42 was my number.\nYou managed in 5 tries.\n</code></pre>\n</blockquote>\n\n<p>What you could (or should) implement is input validation. Without strict and warnings, Perl will transform any string into a number, which will be zero for non-numeric strings. To assert that the input only contains ASCII digits, run a regex over it:</p>\n\n\n\n<pre class=\"lang-perl prettyprint-override\"><code>if (not $guess =~ /^[0-9]+$/) {\n say qq(Your guess \"$guess\" was not a number.); # special qq() quotes\n redo GUESS; # redo this iteration, without incrementing the counter\n}\n</code></pre>\n\n<hr>\n\n<h3>About your updated code:</h3>\n\n<ol>\n<li>Use whitespace. Whitespace is good and improves readability.</li>\n<li><code>use warnings</code>. <code>use 5.016</code> should already be activating <code>strict</code> for you. More warnings = more bugs found early.</li>\n<li>We don't call subs like <code>&amp;foo</code> <em>except</em> when you know what you are doing. This style has a number of side effects that don't matter for your example, but can introduce bugs in complex applications. Always prefer <code>foo()</code>. </li>\n<li>Why on earth are you using <code>our</code>? The <code>our</code> is just like <code>my</code>, except that it declares globals. Don't use globals. Use lexicals with <code>my</code>. In either case, declare your variable once and use it throughout the remaining scope. I.e. declare the variable outside the loop.</li>\n<li>If you look at all your execution paths, you test for duplicate conditions: <code>$compNumber == $userNumber</code> is tested two times. Look at my code again, which manages with one test. The real reason I used a <code>sub</code> is that I could <code>return</code> early, as soon as the correct number was guessed. This made my loop control easier.</li>\n<li><p>You currently have this sequence of conditions inside the loop:</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>if $compNumber == $userNumber\nelsif $compNumber &gt; $userNumber\n if $_ == 5\n last\n else\nelsif $compNumber &lt; $userNumber\n if $_ == 5\n last\n else\n</code></pre>\n\n<p>As soon as <code>$compNumber != $userNumber</code>, we can test for the last iteration. This structure is logically equivalent, but shorter:</p>\n\n<pre class=\"lang-perl prettyprint-override\"><code>if $compNumber == $userNumber\nelsif $_ == 5\n last\nelsif $compNumber &gt; $userNumber\nelsif $compNumber &lt; $userNumber\n</code></pre>\n\n<p>In my code, I simply drop of the last iteration of the loop, after telling the user if his guess was too small or too large, as usual.</p></li>\n<li><p>You use the <em>topic variable</em> <code>$_</code>. This makes for short code, but also makes it hard to understand. Consider using a better name, like <code>$try</code> or <code>$guess</code>. The topic variable is the topic of the current code (you can often pronounce it <em>this</em> or <em>it</em>). Your topic is the guess the user made, not the number of the iteration.</p></li>\n<li>The <code>$n</code> is always zero. You don't increment it. This is good, as it should be the same as your loop variable. As I print the congratulatory message <em>inside</em> the loop, I can use the loop variable, which will yield the correct value.</li>\n<li>My subroutine argument unpacking code may seem a bit arcane if you are new to Perl, but using hardcoded constants is an anti-pattern in any language. (Also, named arguments make for really nice interfaces.)</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T08:11:25.093", "Id": "36394", "Score": "1", "body": "@Lewis I added a section discussing your updated code. Some aspects are partially personal preferences (using whitespace, no `&foo` invocation, no globals, no duplication), but these have good reasons." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T22:44:11.290", "Id": "23556", "ParentId": "23550", "Score": "11" } } ]
{ "AcceptedAnswerId": "23556", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T20:41:02.857", "Id": "23550", "Score": "5", "Tags": [ "game", "perl", "number-guessing-game" ], "Title": "\"Guess my Number\" game" }
23550
<p>These functions are selected by the same index. I understand the index logic of what to do but I don't know how to do it well enough.</p> <pre><code>// those are buttons that will trigger different functions according by an index button_up = jQuery('#videos_tabs-up-0' ); button_down = jQuery('#videos_tabs-down-0' ); button_up_1 = jQuery('#videos_tabs-up-1' ); button_down_1 = jQuery('#videos_tabs-down-1' ); button_up_2 = jQuery('#videos_tabs-up-2' ); button_down_2 = jQuery('#videos_tabs-down-2' ); // this one stores a custom number videos_visible = 3; // there are 3 .ov_front_video div, see I select each one by its index videos_list = jQuery('#ov_front_videos .ov_front_video:eq(0) .item-list ul'); videos_list_item = videos_list.find('li'); videos_list_item_length = videos_list_item.length; videos_visible_limit = videos_list_item_length - videos_visible; videos_list_1 = jQuery('#ov_front_videos .ov_front_video:eq(1) .item-list ul'); videos_list_item_1 = videos_list_1.find('li'); videos_list_item_length_1 = videos_list_item_1.length; videos_visible_limit_1 = videos_list_item_length_1 - videos_visible; videos_list_2 = jQuery('#ov_front_videos .ov_front_video:eq(2) .item-list ul'); videos_list_item_2 = videos_list_2.find('li'); videos_list_item_length_2 = videos_list_item_2.length; videos_visible_limit_2 = videos_list_item_length_2 - videos_visible; // each .ov_front_video (videos_list, videos_list_1, videos_list_2) animates pressing any of the previous buttons, // I'm setting a variable for each .ov_front_video.index k =1; k_1 =1; k_2 =1; // The next functions animates videos_list when button_up is pressed, // videos_list_1 when button_up_1 is pressed, etc ... /* -------------------- click tab 0 ------------------------ */ button_up.click(function() { current_position = videos_list.position().top; current_position = current_position + 70 videos_list.not(':animated').stop().animate({'top':current_position}, function() {k -= 1;}); console.log(k); if (k == 2 ) { jQuery('#videos_tabs-up-0').hide(); } jQuery('#videos_tabs-down-0').show(); }); button_down.click(function() { current_position = videos_list.position().top; current_position = current_position - 70 videos_list.not(':animated').stop().animate({'top':current_position}, function() {k += 1;}); console.log(k); if (k == videos_visible_limit ) { jQuery('#videos_tabs-down-0').hide(); } jQuery('#videos_tabs-up-0').show(); }); /* -------------------- click tab 1 ------------------------ */ button_up_1.click(function() { current_position = videos_list_1.position().top; current_position = current_position + 70 videos_list_1.not(':animated').stop().animate({'top':current_position}, function() {k_1 -= 1;}); console.log(k_1); if (k_1 == 2 ) { jQuery('#videos_tabs-up-1').hide(); } jQuery('#videos_tabs-down-1').show(); }); button_down_1.click(function() { current_position = videos_list_1.position().top; current_position = current_position - 70 videos_list_1.not(':animated').stop().animate({'top':current_position}, function() {k_1 += 1;}); console.log(k_1); if (k_1 == videos_visible_limit_1 ) { jQuery('#videos_tabs-down-1').hide(); } jQuery('#videos_tabs-up-1').show(); }); /* -------------------- click tab 2 ------------------------ */ button_up_2.click(function() { current_position = videos_list_2.position().top; current_position = current_position + 70 videos_list_2.not(':animated').stop().animate({'top':current_position}, function() {k_2 -= 1;}); console.log(k_2); if (k_2 == 2 ) { jQuery('#videos_tabs-up-2').hide(); } jQuery('#videos_tabs-down-2').show(); }); button_down_2.click(function() { current_position = videos_list_2.position().top; current_position = current_position - 70 videos_list_2.not(':animated').stop().animate({'top':current_position}, function() {k_2 += 1;}); console.log(k_2); if (k_2 == videos_visible_limit_2 ) { jQuery('#videos_tabs-down-2').hide(); } jQuery('#videos_tabs-up-2').show(); }); </code></pre>
[]
[ { "body": "<p>You can compact this code a lot by generalising the click listener.</p>\n\n<p>In the html assign a class to each video_tab, but keep the ids as they are. For instance I assigned each video tab a video_button class.</p>\n\n<pre><code>&lt;div id=\"videos_tabs-up-0\" class=\"video_button\"&gt;\n Button: #videos_tabs-up-0\n&lt;/div&gt;\n&lt;div id=\"videos_tabs-down-0\" class=\"video_button\"&gt;\n Button: #videos_tabs-down-0\n&lt;/div&gt;\n&lt;div id=\"videos_tabs-up-1\" class=\"video_button\"&gt;\n Button: #videos_tabs-up-1\n&lt;/div&gt;\n&lt;div id=\"videos_tabs-down-1\" class=\"video_button\"&gt;\n Button: #videos_tabs-down-1\n&lt;/div&gt;\n&lt;div id=\"videos_tabs-up-2\" class=\"video_button\"&gt;\n Button: #videos_tabs-up-2\n&lt;/div&gt;\n&lt;div id=\"videos_tabs-down-2\" class=\"video_button\"&gt;\n Button: #videos_tabs-down-2\n&lt;/div&gt;\n</code></pre>\n\n<p>So now in the jQuery, we can assign just one click listener, listening for clicks on <code>.video_button</code>.</p>\n\n<p>This method handles all possible 'video_tabs-xxx' clicks: up, down, for each of the indexes 0, 1, 2.</p>\n\n<p>Now, clicks can come from any of the 'video_tabs-xxx' ids, so the first thing we need to do is assign some variables based on the origin of the click.</p>\n\n<p>event.target.id contains the id string of the originating element. This is very handy.</p>\n\n<p>Your naming convention contained 'up' and 'down' in the id, so using string searching we can get whether this is an UP or DOWN click and store that in <code>direction</code>.</p>\n\n<p>The index is supplied in the last character of the id name. Let's parse that as an int into the variable <code>idx</code>.</p>\n\n<p>Your k variables seemed to be tracking whether an animation ir running or not*. A simpler way is an array of booleans, where <code>idx</code> will give us a key into the array.</p>\n\n<p>And the <code>offset</code> variable is assigned + or - 70 depending on whether this is an UP or DOWN click.</p>\n\n<p>So that leaves this single listener:</p>\n\n<pre><code>var UP = 0,\n DOWN = 1,\n animating = [false, false, false];\n\n$(document).ready(function () {\n $('.video_button').click(function (event) {\n var idx = parseInt(event.target.id[event.target.id.length-1], 10),\n direction = event.target.id.indexOf('up') &gt; -1 ? UP : DOWN,\n offset = direction === UP ? 70 : -70,\n isAnimating = direction === UP ? true : false,\n videos_list,\n current_position;\n\n console.log('video_button clicked: ' + event.target.id + ' idx: ' +\n idx + ' direction: ' + direction + ' offset: ' + offset +\n ' isAnimating: ' + isAnimating);\n\n videos_list = $('#ov_front_videos .ov_front_video:eq(' +\n idx + ') .item-list ul');\n\n current_position = videos_list.position().top;\n current_position = current_position + offset;\n videos_list.not(':animated').stop().animate({'top':current_position},\n function() {animating[idx] = isAnimating});\n\n if (direction === UP) {\n jQuery('#videos_tabs-down-' + idx).show();\n if (animating[idx]) {\n jQuery('#videos_tabs-up-' + idx).hide();\n }\n }\n else {\n jQuery('#videos_tabs-up-' + idx).show();\n if (animating[idx]) {\n jQuery('#videos_tabs-down-' + idx).hide();\n }\n }\n });\n});\n</code></pre>\n\n<p>*: not entirely clear what your k variables were measuring, but hopefully it's straightforward to fit that logic in the single listener.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T10:59:37.603", "Id": "23561", "ParentId": "23558", "Score": "1" } } ]
{ "AcceptedAnswerId": "23561", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T05:24:35.367", "Id": "23558", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Multiple and similar numbered functions" }
23558
<p>I want to know whether this thing I wrote in C# is a correct implementation of the state monad.</p> <p>I've used it in code and it does what I expect it to do, but I'm still not quite sure if I'm doing this right, or if I just pulled something out of my ear and called it a state monad.</p> <p>I would have made an <code>IMonad&lt;T&gt;</code> interface and used that to help test this, but that's <a href="https://stackoverflow.com/questions/1709897/why-there-is-no-something-like-imonadt-in-upcoming-net-4-0">not possible</a>.</p> <p>Anyway, here's the code:</p> <pre><code>// State a class State&lt;TResult&gt; { // State a t public struct StateData&lt;TState&gt; { public TResult result; public TState state; } // return :: t -&gt; m t public static StateData&lt;TState&gt; Return&lt;TState&gt;(TState state) { StateData&lt;TState&gt; monadicValue = new StateData&lt;TState&gt;(); monadicValue.result = default(TResult); monadicValue.state = state; return monadicValue; } // (&gt;&gt;=) :: m t -&gt; (t -&gt; m u) -&gt; m u public static StateData&lt;TNewState&gt; Bind&lt;TState, TNewState&gt;(StateData&lt;TState&gt; monadicValue, Func&lt;TState, StateData&lt;TNewState&gt;&gt; func) { StateData&lt;TNewState&gt; newMonadicValue = func(monadicValue.state); return newMonadicValue; } // liftM :: (t -&gt; u) -&gt; m t -&gt; m u // liftM :: m t -&gt; (t -&gt; u) -&gt; m u -- looks more similar to bind this way public static StateData&lt;TNewState&gt; Lift&lt;TState, TNewState&gt;(StateData&lt;TState&gt; monadicValue, Func&lt;TState, TNewState&gt; func) { StateData&lt;TNewState&gt; newMonadicValue = new StateData&lt;TNewState&gt;(); newMonadicValue.result = monadicValue.result; newMonadicValue.state = func(monadicValue.state); return newMonadicValue; } } </code></pre> <p>EDIT: You're not supposed to use mutable structs. Here in particular it's helpful to adhere to that, because the state object in the state monad isn't supposed to be mutable either. Ironically, I had to change StateData from a struct to a class to get the compiler to quit complaining about the constructor. Nonetheless, it is now immutable.</p> <p>Also, I changed the Lift function so that it no longer passes through stale TResults.</p> <p>Based on the type signatures and how quaint the code has become, I'm pretty sure this thing is indeed a state monad.</p> <pre><code>// State a class State&lt;TResult&gt; { // State a t public class StateData&lt;TState&gt; { public TResult Result { get; private set; } public TState State { get; private set; } public StateData(TResult result, TState state) { this.Result = result; this.State = state; } } // return :: a -&gt; m a public static StateData&lt;TState&gt; Return&lt;TState&gt;(TState state) { return new StateData&lt;TState&gt;(default(TResult), state); } // (&gt;&gt;=) :: m t -&gt; (t -&gt; m u) -&gt; m u public static StateData&lt;TNewState&gt; Bind&lt;TState, TNewState&gt;(StateData&lt;TState&gt; monadicValue, Func&lt;TState, StateData&lt;TNewState&gt;&gt; func) { return func(monadicValue.State); } // liftM :: (t -&gt; u) -&gt; m t -&gt; m u // liftM :: m t -&gt; (t -&gt; u) -&gt; m u -- looks more similar to bind this way public static StateData&lt;TNewState&gt; Lift&lt;TState, TNewState&gt;(StateData&lt;TState&gt; monadicValue, Func&lt;TState, TNewState&gt; func) { return Return(func(monadicValue.State)); } } </code></pre> <p>I tested this thing by making tic tac toe. The type of TResult is <code>enum Player { Nobody, X, O }</code> and the type of TState is <code>GameState</code>, which knows the board state and the next player. Here's the Main function for your enjoyment:</p> <pre><code>static void Main(string[] args) { Console.WriteLine("Use the number pad to select a location."); State&lt;Player&gt;.StateData&lt;GameState&gt; game = State&lt;Player&gt;.Return&lt;GameState&gt;(new GameState()); while (game.Result == Player.Nobody) { game = State&lt;Player&gt;.Lift&lt;GameState, GameState&gt;(game, nextPlayerMove); game = State&lt;Player&gt;.Lift&lt;GameState, GameState&gt;(game, drawBoard); game = State&lt;Player&gt;.Bind&lt;GameState, GameState&gt;(game, findWinner); } Console.WriteLine(game.Result.ToString() + " won."); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T18:28:15.943", "Id": "36354", "Score": "0", "body": "Could you add an example of how would you use it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-28T06:49:26.557", "Id": "37735", "Score": "1", "body": "I find putting bind in a static extension or directly on the type in C# gives the fluency that feels more like the bind's infix operator, think about State 42 >>= return vs new State(0, 42).Bind(Return)" } ]
[ { "body": "<p>Mutable <code>struct</code>s in C#/.NET are evil for many reasons you can Google. Rewrite as such:</p>\n\n<pre><code>// State a\ninternal class State&lt;TResult&gt;\n{\n // State a t\n public struct StateData&lt;TState&gt;\n {\n private readonly TResult result;\n\n private readonly TState state;\n\n public StateData(TResult result, TState state)\n {\n this.result = result;\n this.state = state;\n }\n\n public TResult Result\n {\n get\n {\n return this.result;\n }\n }\n\n public TState State\n {\n get\n {\n return this.state;\n }\n }\n }\n\n // return :: t -&gt; m t\n public static StateData&lt;TState&gt; Return&lt;TState&gt;(TState state)\n {\n return new StateData&lt;TState&gt;(default(TResult), state);\n }\n\n // (&gt;&gt;=) :: m t -&gt; (t -&gt; m u) -&gt; m u\n public static StateData&lt;TNewState&gt; Bind&lt;TState, TNewState&gt;(\n StateData&lt;TState&gt; monadicValue,\n Func&lt;TState, StateData&lt;TNewState&gt;&gt; func)\n {\n return func(monadicValue.State);\n }\n\n // liftM :: (t -&gt; u) -&gt; m t -&gt; m u\n // liftM :: m t -&gt; (t -&gt; u) -&gt; m u -- looks more similar to bind this way\n public static StateData&lt;TNewState&gt; Lift&lt;TState, TNewState&gt;(\n StateData&lt;TState&gt; monadicValue,\n Func&lt;TState, TNewState&gt; func)\n {\n return new StateData&lt;TNewState&gt;(monadicValue.Result, func(monadicValue.State));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T01:08:57.470", "Id": "36383", "Score": "0", "body": "That's convenient." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T13:48:42.253", "Id": "23564", "ParentId": "23559", "Score": "1" } }, { "body": "<ul>\n<li><p>You cannot have something named \"X\" theoretically does not mean you cannot have anything anyone at sometime thought to be \"X\". \nSee <a href=\"https://codereview.stackexchange.com/questions/20845\">my answer</a> to another question for a feeling of what you can expect to get in the way of a monad <em>pattern</em> in an object oriented language.</p></li>\n<li><p>What really concerns me is this:</p>\n\n<pre><code>// liftM :: m t -&gt; (t -&gt; u) -&gt; m u -- looks more similar to bind this way\n</code></pre>\n\n<p>Why is it called <code>lift</code>? Because it takes a function in and gives a function out, but in another domain. <code>(t -&gt; u) -&gt; m t -&gt; m u</code> should be read as <code>(t -&gt; u) -&gt; (m t -&gt; m u)</code>, which translates to something like <code>Func&lt;Func&lt;T, U&gt;, Func&lt;M&lt;T&gt;, M&lt;U&gt;&gt;&gt;</code> in C#.</p></li>\n<li><p>You should not overwrite local variables, let alone repetitively, let alone in functional-style aspirant code:</p>\n\n<pre><code>game = State&lt;Player&gt;.Lift&lt;GameState, GameState&gt;(game, nextPlayerMove);\ngame = State&lt;Player&gt;.Lift&lt;GameState, GameState&gt;(game, drawBoard);\ngame = State&lt;Player&gt;.Bind&lt;GameState, GameState&gt;(game, findWinner);\n</code></pre></li>\n<li><p>You don't do <code>Monad</code> and <code>while</code> loop. You should use a <code>foldM</code>.</p></li>\n<li><p>Also noticed <code>nextPlayerMove</code> may do IO. In Haskell you would not have a function interleaved with a monad, unless it is a deterministic mathematical function. For example if it used Random numbers or IO you would need a monadic transformer, see <code>StateT</code> <a href=\"http://www.haskell.org/haskellwiki/Simple_StateT_use\" rel=\"nofollow noreferrer\">here</a>.</p></li>\n</ul>\n\n<p>In adopting functional paradigms, you should start with the low hanging fruits. Avoiding mutable state and preferring expressions over statements, etc. And look for opportunities for reification.\nAim for making implicit patterns explicit (for example using applicative alternatives from IEnumerable/IQueryable instead of loops) , composability and as much compile time guarantees as possible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T09:46:09.513", "Id": "23611", "ParentId": "23559", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T05:38:53.807", "Id": "23559", "Score": "5", "Tags": [ "c#", "haskell", "monads" ], "Title": "C# state monad implementation" }
23559
<p>I'm using the boost::units library (<a href="http://www.boost.org/doc/libs/1_53_0/doc/html/boost_units.html" rel="nofollow" title="boost::units">boost::units</a>) and trying to make use of auto and decltype to deal with all the complicated types it produces.</p> <p>I have a templated function to integrate a mathematical function (which might accept x values with units such as <code>1*metre</code>) between two points:</p> <pre><code>template &lt;class Out, class In &gt; auto integrate( std::function&lt;Out(In)&gt; const &amp; f, In xmin, In xmax, int nSteps) -&gt; decltype( f(xmin) * xmin ) </code></pre> <p>Now I want to use this with some functions that have big ugly return types. I have written this:</p> <pre><code>//Standard quantities quantity&lt;temperature&gt; stdBlackBodyTemp = 2857.0*kelvin; auto luminousEfficiency = quantity&lt;luminous_flux&gt;(682.0*lumen) / quantity&lt;power&gt;(1.0 * watt); //Integration range quantity&lt;length&gt; minWavelength(150.0 * nano * metre); quantity&lt;length&gt; maxWavelength(600.0 * nano * metre); //Get type for spectral_differential_current quantity&lt;length&gt; fakeLength(300.0 * nano * metre); typedef decltype(pmt_radiant_sensitivity(fakeLength) * plancklaw(fakeLength, stdBlackBodyTemp)) sdctype; //Define spectral_different_current function std::function&lt; sdctype(quantity&lt;length&gt;)&gt; spectral_differential_current = [&amp;stdBlackBodyTemp](quantity&lt;length&gt; l) { return pmt_radiant_sensitivity(l) * plancklaw(l, stdBlackBodyTemp ); }; //Integrate over spectral_differential_current auto differential_current = integrate( spectral_differential_current, minWavelength, maxWavelength, 100); </code></pre> <p>To define my <code>std::function spectral_differential_current</code> which I'm going to give to <code>integrate</code> I need to know the return type. The only way I have found to get this is by using the function on some random value (<code>fakeLength</code>) and then using decltype. It seems odd that I have to introduce a variable which isn't actually used just to get a type. Is there a better way of approaching this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T12:51:36.173", "Id": "36342", "Score": "0", "body": "You could re-use `minWavelength` instead of introducing `fakeLength`. Since there could be multiple `pmt_radiant_sensitivity` and `plancklaw` with different return types, I'm not sure what you'd expect without giving the input type – and `decltype` has been constructed to take a standard expression, not some new syntax that only gets types and functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T20:11:22.450", "Id": "36364", "Score": "0", "body": "Thanks. I see your point that the return type can't be deduced without the arguments. Is there a better approach I could have taken? I've seen comments in other places suggesting that std::function is really only meant for very specific circumstances. Is this one of them or could my integrate function accept something else?" } ]
[ { "body": "<p>I'm not sure why you need the typedef in the first place. Is there anything wrong with <code>auto spectral_differential_current = ...</code>?</p>\n\n<p>On a similar note, why do you want to require that <code>f</code> is an <code>std::function</code>, disallowing reasonable calls like <code>integrate(sin, 0, 2, 10)</code>? Most code of this type can happily accept anything that can be called:</p>\n\n<pre><code>template &lt;typename F, typename In&gt;\nauto integrate(F f, In xmin, In xmax, int nSteps)\n-&gt; decltype(f(xmin) * xmin)\n</code></pre>\n\n<p>The compiler will tell you whether a given <code>f</code> is OK. Usually by not finding a suitable <code>integrate</code> function – SFINAE.</p>\n\n<p>Also note the use of <code>typename</code> – that's just a stylistic thing of course, but e.g., <code>double</code> is not a class, so I prefer not to say <code>class</code> for template parameters that would accept a <code>double</code> or a plain function pointer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T11:30:54.260", "Id": "36405", "Score": "0", "body": "Thanks, that works! I didn't realise you could directly assign a lambda to a variable without wrapping it in a std::function. I've taken your typename advice as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T09:49:55.893", "Id": "23612", "ParentId": "23563", "Score": "1" } } ]
{ "AcceptedAnswerId": "23612", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T12:39:20.747", "Id": "23563", "Score": "2", "Tags": [ "c++", "c++11", "functional-programming" ], "Title": "Determining function return types for std::function" }
23563
<p>Racket is a general purpose, multi-paradigm programming language in the Lisp/Scheme family. One of its design goals is to serve as a platform for language creation, design, and implementation. The language is used in a variety of contexts such as scripting, general-purpose programming, computer science education, and research.</p> <p>Home page: <a href="http://www.racket-lang.org" rel="nofollow">http://www.racket-lang.org</a></p> <p>Documentation: <a href="http://docs.racket-lang.org/" rel="nofollow">http://docs.racket-lang.org/</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T14:26:25.130", "Id": "23566", "Score": "0", "Tags": null, "Title": null }
23566
Racket is an extensible general programming language in the Lisp family.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T14:26:25.130", "Id": "23567", "Score": "0", "Tags": null, "Title": null }
23567
<p>I am trying to track relationships among people. I came up with my own solution, but I'm wondering if there might be another way or better way of doing this. To keep it simplified, I'll post just the bare bones.</p> <p>Let's say I have created the tables: <code>person</code>, <code>person_relation</code>, and <code>people_relation</code> for a MYSQL database using the following code:</p> <pre><code>DROP TABLE IF EXISTS person; DROP TABLE IF EXISTS person_relation; DROP TABLE IF EXISTS people_relation; CREATE TABLE `person` ( `id` int(10) NOT NULL auto_increment primary key, `name` varchar(32) NOT NULL, ) ENGINE=MyISAM DEFAULT CHARSET=utf8; CREATE TABLE `people_relation` ( `id` int(2) NOT NULL auto_increment primary key, `relation` varchar(32) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; CREATE TABLE `person_relation` ( `id` int(10) NOT NULL auto_increment primary key, `parent_id` int(10) NOT NULL, `child_id` int(10) NOT NULL, `relation_id` int(10) NOT NULL, FOREIGN KEY (`parent_id`) REFERENCES person(`id`), FOREIGN KEY (`child_id`) REFERENCES person(`id`), FOREIGN KEY (`relation_id`) REFERENCES people_relations(`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; INSERT INTO `person` (`id`, `name`) VALUES (1, 'John Jr'), (2, 'Jane'), (3, 'Mark'), (4, 'John'), (5, 'Betty'); INSERT INTO `people_relation` (`id`, `relation`) VALUES (1, 'HUSBAND'), (2, 'WIFE'), (3, 'FATHER'), (4, 'MOTHER'), (5, 'SON'), (6, 'DAUGHTER'), (7, 'GRANDFATHER'), (8, 'GRANDMOTHER'), (9, 'GRANDSON'), (10, 'GRANDDAUGHTER'), (11, 'GREAT GRANDFATHER'), (12, 'GREAT GRANDMOTHER'), (13, 'GREAT GRANDSON'), (14, 'GREAT GRANDDAUGHTER'), (15, 'GODFATHER'), (16, 'GODMOTHER'), (17, 'GODSON'), (18, 'GODDAUGHTER'), (19, 'BROTHER'), (20, 'SISTER'), (21, 'MOTHER-IN-LAW'), (22, 'FATHER-IN-LAW'), (23, 'DAUGHTER-IN-LAW'), (24, 'SON-IN-LAW'); INSERT INTO `person_relation` (`id`, `parent_id`, `child_id`, `relation_id`) VALUES (1, 1, 2, 1), (2, 1, 3, 3), (3, 1, 4, 5), (4, 1, 5, 5), (5, 2, 1, 2), (6, 2, 3, 4), (7, 2, 4, 23), (8, 2, 5, 23), (9, 3, 1, 5), (10, 3, 2, 5), (11, 3, 4, 9), (12, 3, 5, 9), (13, 4, 1, 3), (14, 4, 2, 22), (15, 4, 3, 7), (16, 4, 5, 1), (17, 5, 1, 4), (18, 5, 2, 21), (19, 5, 3, 8), (20, 5, 4, 2); </code></pre> <p>So, in my example, I am capturing 5 people, all family related, where I make connections to each of them with a unique relation: spoken plainly, a John Jr. has listed: a wife, a son, a mother, and a father; and Jane has a husband, a son, a father-in-law, and a mother-in-law, etc.</p> <p>The records with 5 people end up being 20 records in the <code>person_relation</code> table. If I add, let's say a new daughter for John Jr. and Jane. The table will then have presumably 30 records to account all the relations.</p> <p>Does this sound about right? This problem seems like it could explode to be a very large table. Do you know maybe a better way to do this? Or do you think I am on the right track?</p>
[]
[ { "body": "<p>It seems fine for me for generic cases. Later you might need some denormalization or caching if it's too slow but it really depends on the usage. (If you have any special requirement you should share it, edit the question, please.)</p>\n\n<p>Four things to consider:</p>\n\n<ol>\n<li><p><code>varchar(32)</code> for <code>name</code> could be too small.</p></li>\n<li><p>Consider unique indexes for the <code>person_relation(parent_id, child_id, relation_id)</code> triplet and the <code>people_relation.relation</code> attribute. For example:</p>\n\n<p>Currently, you can insert the same relation twice:</p>\n\n<pre><code>mysql&gt; select * FROM person_relation;\nEmpty set (0.00 sec)\n\nmysql&gt; INSERT INTO `person_relation` (`parent_id`, `child_id`, `relation_id`) \n VALUES (1, 2, 1);\nQuery OK, 1 row affected (0.00 sec)\n\nmysql&gt; INSERT INTO `person_relation` (`parent_id`, `child_id`, `relation_id`) \n VALUES (1, 2, 1);\nQuery OK, 1 row affected (0.00 sec)\n\nmysql&gt; select * FROM person_relation;\n+----+-----------+----------+-------------+\n| id | parent_id | child_id | relation_id |\n+----+-----------+----------+-------------+\n| 23 | 1 | 2 | 1 |\n| 24 | 1 | 2 | 1 |\n+----+-----------+----------+-------------+\n2 rows in set (0.00 sec)\n</code></pre>\n\n<p>An unique index could prevent that: </p>\n\n<pre><code>CREATE UNIQUE INDEX person_relation_uniq_idx \n ON person_relation \n (parent_id, child_id, relation_id);\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>mysql&gt; DELETE FROM person_relation;\nQuery OK, 2 rows affected (0.00 sec)\n\nmysql&gt; CREATE UNIQUE INDEX person_relation_uniq_idx \n -&gt; ON person_relation \n -&gt; (parent_id, child_id, relation_id);\nQuery OK, 0 rows affected (0.31 sec)\nRecords: 0 Duplicates: 0 Warnings: 0\n\nmysql&gt; INSERT INTO `person_relation` (`parent_id`, `child_id`, `relation_id`) \n VALUES (1, 2, 1);\nQuery OK, 1 row affected (0.00 sec)\n\nmysql&gt; INSERT INTO `person_relation` (`parent_id`, `child_id`, `relation_id`) \n VALUES (1, 2, 1);\nERROR 1062 (23000): Duplicate entry '1-2-1' for key 'person_relation_uniq_idx'\n\nmysql&gt; SELECT * FROM person_relation;\n+----+-----------+----------+-------------+\n| id | parent_id | child_id | relation_id |\n+----+-----------+----------+-------------+\n| 25 | 1 | 2 | 1 |\n+----+-----------+----------+-------------+\n1 row in set (0.00 sec)\n</code></pre></li>\n<li><p><code>people_relation.relation</code> might not be <code>NULL</code>.</p></li>\n<li><p><code>people_relation</code> and <code>person_relation</code> are easy to mix up, these names are too similar to each other. I'd rename <code>people_relation</code> to <code>relation_type</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T16:28:23.327", "Id": "36347", "Score": "0", "body": "thanks, im a newb, so i am not very confident with my work thus far. but good points and catches with number 1, 3, and 4. regarding number 2, could you go into a little more detail there? i am not understanding. how would this help to have a unique index for the triplet. and wouldn't by nature they already be unique?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T16:57:18.470", "Id": "36349", "Score": "0", "body": "@ArmYourselves: I've updated the answer, check it, please. I hope it's a little bit clearer. Feel free to ask if you have any further questions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T16:59:01.993", "Id": "36350", "Score": "0", "body": "@ArmYourselves: Thank you for accepting the answer but I think you should not do that so fast :) Waiting a few days with it you are likely to get more feedback from others. (You can unaccept it by clicking on the green tick icon.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T17:08:43.713", "Id": "36351", "Score": "1", "body": "oh - yes.. :) thanks for the tips and extra explanation, your feedback has been great, its very tempting to accept your answer! i suppose yes.. i should wait. :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T16:17:06.867", "Id": "23569", "ParentId": "23568", "Score": "2" } }, { "body": "<p>Let's say Mary and John are married and have two children, Jane and Matt...</p>\n\n<p>What about this table structure:</p>\n\n<pre><code>side1 | side1type | side2type | side2\n----------------------------------------------------\nMary | wife | husband | John\nJane | child | mother | Mary\nJane | child | father | John\nMatt | child | mother | Mary\nMatt | child | father | John \nJane | sister | brother | Matt\n</code></pre>\n\n<p>When we are interested to find one person relatives we could run 2 queries looking for that person in column side1 and then in column side2...</p>\n\n<p>Or maybe one query looking for that person in one or another column, than we use logic in our application and:</p>\n\n<pre><code>If that person has been found in side1 column \n we print side1, side1type, \"of \", side2 \n</code></pre>\n\n<blockquote>\n <p>Mary is wife of John </p>\n</blockquote>\n\n<pre><code>If that person has been found in side2 column \n we print side2, side2type, \"of \", side1 \n</code></pre>\n\n<blockquote>\n <p>Mary is mother of Jane<br>\n Mary is mother of Matt</p>\n</blockquote>\n\n<p>Or maybe more elegant...</p>\n\n<pre><code>If that person has been found in side1 column \n we print side2 (side2type) \n</code></pre>\n\n<blockquote>\n <p>John (husband) </p>\n</blockquote>\n\n<pre><code>If that person has been found in side2 column \n we print side1 (side1type) \n</code></pre>\n\n<blockquote>\n <p>Jane (child)<br>\n Matt (child) </p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-06-10T07:12:28.837", "Id": "131599", "ParentId": "23568", "Score": "2" } } ]
{ "AcceptedAnswerId": "23569", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T15:42:51.590", "Id": "23568", "Score": "2", "Tags": [ "sql", "mysql" ], "Title": "Keeping track of people's relationships using a people relation table" }
23568
<p>I need to run over a log file with plenty of entries (25+GB) in Python to extract some log times. </p> <p>The snippet below works. On my test file, I'm ending up with roughly <code>9:30min</code> (Python) and <code>4:30min</code> (PyPy) on 28 million records (small log).</p> <pre><code>import datetime import time import json import re format_path= re.compile( r"^\S+\s-\s" r"(?P&lt;user&gt;\S*)\s" r"\[(?P&lt;time&gt;.*?)\]" ) threshold = time.strptime('00:01:00,000'.split(',')[0],'%H:%M:%S') tick = datetime.timedelta(hours=threshold.tm_hour,minutes=threshold.tm_min,seconds=threshold.tm_sec).total_seconds() zero_time = datetime.timedelta(hours=0,minutes=0,seconds=0) zero_tick = zero_time.total_seconds() format_date = '%d/%b/%Y:%H:%M:%S' obj = {} test = open('very/big/log','r') for line in test: try: chunk = line.split('+', 1)[0].split('-', 1)[1].split(' ') user = chunk[1] if (user[0] == "C"): this_time = datetime.datetime.strptime(chunk[2].split('[')[1], format_date) try: machine = obj[user] except KeyError, e: machine = obj.setdefault(user,{"init":this_time,"last":this_time,"downtime":0}) last = machine["last"] diff = (this_time-last).total_seconds() if (diff &gt; tick): machine["downtime"] += diff-tick machine["last"] = this_time except Exception: pass </code></pre> <p>While I'm ok with the time the script runs, I'm wondering if there are any obvious pitfalls regarding performance, which I'm stepping in (still in my first weeks of Python).</p> <p>Can I do anything to make this run faster?</p> <p><strong>EDIT:</strong></p> <p>Sample log entry:</p> <pre><code>['2001:470:1f14:169:15f3:824f:8a61:7b59 - SOFTINST [14/Nov/2012:09:32:31 +0100] "POST /setComputerPartition HTTP/1.1" 200 4 "-" "-" 102356'] </code></pre> <p><strong>EDIT 2:</strong></p> <p>One thing I just did, was to check if log entries have the same log time and if so, I'm using the <code>this_time</code> from the previous iteration vs calling this:</p> <pre><code>this_time = datetime.datetime.strptime(chunk[2].split('[')[1], format_date) </code></pre> <p>I checked some of logs, there are plenty of entries with the exact same time, so on the last run on <code>pypy</code> I'm down to <code>2.43min</code>.</p>
[]
[ { "body": "<pre><code>import datetime\nimport time\nimport json\nimport re\n\nformat_path= re.compile( \n r\"^\\S+\\s-\\s\" \n r\"(?P&lt;user&gt;\\S*)\\s\"\n r\"\\[(?P&lt;time&gt;.*?)\\]\" \n)\n</code></pre>\n\n<p>Python convention is ALL_CAPS for global constants. But as far as I can tell, you don't actually use this.</p>\n\n<pre><code>threshold = time.strptime('00:01:00,000'.split(',')[0],'%H:%M:%S')\n</code></pre>\n\n<p>Why are you putting in a string literal just to throw half of it away? Why are you converting from a string rather then creating the value directly? \n tick = datetime.timedelta(hours=threshold.tm_hour,minutes=threshold.tm_min,seconds=threshold.tm_sec).total_seconds()</p>\n\n<p>That's a way over complicated way to accomplish this. Just say <code>tick = 60</code> and skip all the rigamorle.</p>\n\n<pre><code>zero_time = datetime.timedelta(hours=0,minutes=0,seconds=0)\nzero_tick = zero_time.total_seconds()\n</code></pre>\n\n<p>You don't seem to use this...</p>\n\n<pre><code>format_date = '%d/%b/%Y:%H:%M:%S'\n\n\n\nobj = {}\ntest = open('very/big/log','r')\n</code></pre>\n\n<p>Really bad names. They don't tell me anything. Also, it's recommended to deal with files using a with statement.</p>\n\n<pre><code>for line in test:\n try:\n chunk = line.split('+', 1)[0].split('-', 1)[1].split(' ')\n</code></pre>\n\n<p>That seems way complicated. There is probably a better way to extract the data but without knowing what this log looks like I can't really suggest one.</p>\n\n<pre><code> user = chunk[1]\n if (user[0] == \"C\"):\n</code></pre>\n\n<p>You don't need the ( and )</p>\n\n<pre><code> this_time = datetime.datetime.strptime(chunk[2].split('[')[1], format_date)\n try:\n machine = obj[user]\n except KeyError, e:\n machine = obj.setdefault(user,{\"init\":this_time,\"last\":this_time,\"downtime\":0})\n</code></pre>\n\n<p>Don't use dictionaries random attribute storage. Create an a class and put stuff in there.</p>\n\n<pre><code> last = machine[\"last\"]\n diff = (this_time-last).total_seconds()\n if (diff &gt; tick):\n</code></pre>\n\n<p>You don't need the parens, and I'd combine the last two lines</p>\n\n<pre><code> machine[\"downtime\"] += diff-tick\n machine[\"last\"] = this_time\n\n except Exception:\n pass\n</code></pre>\n\n<p>Don't ever do this. DON'T EVER DO THIS. You should never never catch and then ignore all possible exceptions. Invariably, you'll end up with a bug that you'll miss because you are ignoring the exceptions. </p>\n\n<p>As for making it run faster, we'd really need to know more about the log file's contents.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T17:31:05.033", "Id": "36352", "Score": "0", "body": "wow. Lot of input. Let me digest. I also add a sample record above plus one thing I just did" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T17:00:47.967", "Id": "23572", "ParentId": "23570", "Score": "2" } }, { "body": "<ol>\n<li><p>You can use <a href=\"https://en.wikipedia.org/wiki/Regular_expression\" rel=\"nofollow\">regular expressions</a> with <a href=\"http://docs.python.org/2.7/library/re.html\" rel=\"nofollow\">re</a> module to speed up parsing dramatically. For example the following code extracts user and time information by using regular expression (note that <code>user[0] == \"C\"</code> condition also checked by the regexp):</p>\n\n<pre><code>import re\nimport datetime\n\nmatch_record = re.compile(r\"^[^ ]+ - (C[^ ]*) \\[([^ ]+)\").match\nstrptime = datetime.datetime.strptime\n\nf = open(\"very/big/log\", \"rb\")\n\nfor line in f:\n match = match_record(line)\n if match is not None:\n user, str_time = match.groups()\n time = strptime(str_time, \"%d/%b/%Y:%H:%M:%S\")\n print user, repr(time)\n</code></pre>\n\n<p>I think you can make it even faster by reading bigger chunks of data and using <a href=\"http://docs.python.org/2.7/library/re.html#re.RegexObject.finditer\" rel=\"nofollow\">re.finditer</a> method.</p></li>\n<li><p>Don't use dictionaries to store information in the <code>obj</code> dictionary. <a href=\"http://docs.python.org/2.7/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange\" rel=\"nofollow\">Tuples</a> is the way to go here and if you really need to use names for fields you can use <a href=\"http://docs.python.org/2.7/library/collections.html#collections.namedtuple\" rel=\"nofollow\">collections.namedtuple</a>. In any case tuples will be faster than dictionaries (and lists) and will take less memory.</p></li>\n<li><p>Probably <code>if user in obj</code> will be little bit faster than <code>try/except KeyError</code> here. You can check execution times for small code blocks with <a href=\"http://docs.python.org/2.7/library/timeit.html\" rel=\"nofollow\">timeit</a> module.</p></li>\n<li><p>Check the <a href=\"http://wiki.python.org/moin/PythonSpeed/PerformanceTips\" rel=\"nofollow\">Python performance tips</a>. For example <a href=\"http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots...\" rel=\"nofollow\">Avoiding dots...</a> chapter can be relevant for your code.</p></li>\n</ol>\n\n<h2>UPDATE</h2>\n\n<p>The following version of the code read bigger chunks of data and using <a href=\"http://docs.python.org/2.7/library/re.html#re.RegexObject.finditer\" rel=\"nofollow\">re.finditer</a> (Not sure if it faster or not. Also note the changes in the regexp):</p>\n\n<pre><code>import re\nimport datetime\n\niter_records = re.compile(r\"^[^ ]+ - (C[^ ]*) \\[([^ ]+) .*$\", re.M).finditer\nstrptime = datetime.datetime.strptime\n\nf = open(\"very/big/log\", \"rb\")\n\nchunk = \"\"\nwhile True:\n # Probably buffer size can be even bigger\n new = f.read(1048576)\n chunk += new\n end = 0\n for match in iter_records(chunk):\n user, str_time = match.groups()\n time = strptime(str_time, \"%d/%b/%Y:%H:%M:%S\")\n print user, repr(time)\n end = match.end()\n if end &gt; 0:\n chunk = chunk[end:]\n elif not new:\n break\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T20:56:59.167", "Id": "36367", "Score": "0", "body": "nice. Thank you very much. Will try tomorrow" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T09:22:50.563", "Id": "36397", "Score": "0", "body": "ok. using `regular expression` with pypy and 28m rows cuts `2.43mins` to `1.47mins`, `users in obj` is 5seconds slower on the test set and namedtuples... I'm trying now" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T09:55:16.683", "Id": "36398", "Score": "0", "body": "regarding `namedtuples` - the values in my tuple will be changed on every iteration plus I need to add 3 more values once the loop is done. From what I understand namedtuples are not changeable \"out-of-the-box\". So should I use dict, namedtuple or a list?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T10:06:40.143", "Id": "36399", "Score": "1", "body": "@frequent You would have to construct a new tuple with updated values and assign that to `obj[user]`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T10:09:18.063", "Id": "36400", "Score": "0", "body": "@JanneKarila: so I'm thinking. But creating a new tuple & removing the old one is probably more resource-eating than list or dict (or set)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T10:34:06.027", "Id": "36402", "Score": "0", "body": "Ok. Using a `list` vs a `dict` cuts processing to `1.30mins`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T11:42:01.777", "Id": "36406", "Score": "0", "body": "@frequent You're right, probably `list` will be better than `tuple` in this case. And you still can try read bigger chunks of data and using `re.finditer`. It can be a little bit tricky so you can first test how fast is the code without I/O operations by replacing the file object with a test iterator." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T20:44:39.960", "Id": "23589", "ParentId": "23570", "Score": "4" } }, { "body": "<pre><code>if (user[0] == \"C\"):\n</code></pre>\n\n<p>If the above statement skips a large majority of lines, you can speed things up by doing a preliminary check up front:</p>\n\n<pre><code>if ' - C' in line:\n</code></pre>\n\n<p>This may give false positives, so follow up with a better check. The regex proposed by hdima looks like the way to go.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T20:56:04.877", "Id": "23591", "ParentId": "23570", "Score": "0" } } ]
{ "AcceptedAnswerId": "23589", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T16:33:24.563", "Id": "23570", "Score": "5", "Tags": [ "python", "performance", "logging" ], "Title": "Running over a log file to extract log times" }
23570
<pre><code>class ControllerFactory { public function createController($controller) { if (file_exists($path = __DIR__ . 'app/controllers/' . $controller . '.php')) { require_once $path; return true; } } } </code></pre> <p>It seems a bit overkill to have a class to do this. To intiate a class to build another one, am I correct? Anyother way I can do these/ or to improve this one. I guess make it static would be an alternative?</p>
[]
[ { "body": "<p>I indeed suggest to make it static, so you can call <code>ControllerFactory::createController</code>. I think factories are the only things that are allowed to use static methods.</p>\n\n<p>But I think this is not something you do in a factory. It looks like it is some autoloading function. Factories create classes, they don't autoload them. You should use an autoloader (which you register with the <a href=\"http://php.net/spl_autoload_register\" rel=\"nofollow\"><code>spl_autoload_register</code></a> function) to load classes. A autoloader looks something like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>class Autoloader\n{\n public function loadClass($class)\n {\n // ... do something magic to load a class based on the classname + namespace\n }\n\n public static function register()\n {\n spl_autoload_register(array($this, 'loadClass'));\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T17:16:49.393", "Id": "23574", "ParentId": "23573", "Score": "2" } }, { "body": "<h2>Factory basics</h2>\n\n<p>If we talking about MVC then we have an object oriented system which contains a lot of objects. Factory methods and classes mainly exists to help instantiate other orbjects. Look at your code; is your factory do what it have to? No. Your factory only loading a file in a strict way, you need a class loader as Wouter J suggested.</p>\n\n<h2>Learn how PHP namespaces work</h2>\n\n<h2>ControllerFactory</h2>\n\n<p>If you have a class loader then you can build a real ControllerFactory. What should it do? Get the controller name (namespace + controller name, not file becouse the actual controller is a class!) from the input parameters (route data) handling all namespace and naming issues (for example not only in your controllers \"folder\" (namespace) can contain controllers).</p>\n\n<p>If we have the controller (full name and the class exists) then we have to instantiate it. A ControllerFactory can handle some kind of dependency injection container to allow controller classes to have parametered constructors. If there is no DI container available, then the instantiation can be really simple: new $namespacedName()</p>\n\n<p>The ControllerFactory it self should not be static becouse it will be hard to test, the implementation could not be replaced if it would required and we could not pass anything to it's constructor (it wouldn't have a ctor). Ofcourse it can have static methods to set the default ControllerFactory, like:</p>\n\n<pre><code>class ControllerFactory {\n\n private static $_factory;\n\n public static function SetCurrent(ControllerFactory $factory) {\n self::$_factory = $factory;\n }\n\n public static function Current() {\n if (self::$_factory == null) {\n self::$_factory = new ControllerFactory();\n }\n\n return self::$_factory;\n }\n\n /* ... */\n}\n</code></pre>\n\n<p>(If i were you i would put this into a seperated class to keep everything clean.)\nWhat are we gain this way? Testability, flexibitily (can be changed the default factory in each application if needed).</p>\n\n<h2>Controller factory with dependency injection</h2>\n\n<pre><code>interface IDependencyResolver {\n function GetService($classNameOrAnyOtherIdentifierForExampleACustomTypeClass);\n}\n\n//this stuff can be called as null object pattern\nclass DefaultResolver implements IDependencyResolver {\n public function GetService($className) {\n //this will fail if no parameterless constructor is defined in the class\n return new $className();\n }\n}\n\nfinal class DependencyResolver {\n\n private static $_resolver;\n\n public static function SetResolver(IDependencyResolver $resolver) {\n if ($resolver == NULL) {\n throw new Exception(\"Resolver can not be null\");\n }\n\n self::$_resolver = $resolver;\n }\n\n public static function Current() {\n if (self::$_resolver == null) {\n self::$_resolver = new DefaultResolver();\n }\n return self::$_resolver;\n }\n\n}\n\nclass AdvancedControllerFactory extends ControllerFactory {\n\n private $_resolver;\n\n public function __constructor(IDependencyResolver $resolver = NULL) {\n $this-&gt;_resolver = $resolver;\n }\n\n public function CreateController($allDataWhatIsRequiredInACustomObjectInstance) {\n /* ... name resolving etc */\n\n $resolver = $this-&gt;_resolver ?: DependencyResolver::Current();\n\n return $resolver-&gt;GetService($fullyQualifiedClassNameOfTheCurrentController);\n }\n\n}\n</code></pre>\n\n<p>You can found a lot information about what is dependency injection and with the example above you can use any existing DI framework (or create your own) you only have to do is create an adapter (Adapter pattern) which is implementing the IDependencyResolver interface and working whith the current DI framework implementation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T21:24:30.573", "Id": "36436", "Score": "0", "body": "Could you tell me more about this phase: ControllerFactory can handle some kind of dependency injection container" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T08:25:22.973", "Id": "36457", "Score": "0", "body": "I've made an edit to my answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T19:56:33.427", "Id": "23584", "ParentId": "23573", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T17:07:35.233", "Id": "23573", "Score": "1", "Tags": [ "php" ], "Title": "Small factory class" }
23573
<p>I'm running into page performace issues and I believe this block is causing the biggest slowdown:</p> <pre><code> // Section menu on mouseover, hide menu on mouseout // Can be more concise using .toggleClass? $('section').live('mouseenter', function() { if ($(window).width() &gt; 1278) { $(this).find('menu').removeClass('hidden') $(this).find('div.section-wrapper').addClass('active') } }).live('mouseleave', function() { if ($(window).width() &gt; 1278) { $(this).find('menu').addClass('hidden') $(this).find('div.section-wrapper').removeClass('active') } }) </code></pre> <p>For the record, I'm aware <code>.live()</code> is deprecated and will eventually switch to <code>.on()</code>. I'm under the impression this only runs when mouseenter and mouseleave occur, but with it, the page performance is poor - especially for mobile.</p> <p>I'm trying to convert this to a css media query so it runs faster but the following block of SASS isn't cutting it:</p> <pre><code>@media(min-width: 1279px) { section:hover { menu.hidden { display:block; } section .section-wrapper { border: 1px #ddd solid; padding: 14px; } } } </code></pre> <p><code>.active</code> just adds a border and changes the padding to accommodate. <code>section:hover</code> appears to do nothing. I added <code>section {background-color: #E1C2E2;}</code> within the media query for troubleshooting and it's working fine. Ideas? Could it be nested SASS with media queries causing the slowdown?</p>
[]
[ { "body": "<p>Just a simple case of css hierarchy and not covering my bases with undoing twitter bootstrap's <code>.hidden</code> class. This does the trick:</p>\n\n<pre><code>@media(min-width: 1279px) {\n section:hover {\n menu.hidden {\n display: block;\n visibility: visible;\n }\n .section-wrapper {\n border: 1px #ddd solid;\n padding: 14px;\n }\n }\n}\n</code></pre>\n\n<p>As for performance, it was this block that was causing a much bigger slow down:</p>\n\n<pre><code> $(window).bind('load resize orientationchange', function(){\n $('#main_menu').trigger('testfit')\n if ($(window).width() &lt; 1278) {\n $('section').find('menu').removeClass('hidden')\n $('section').find('div.section-wrapper').addClass('active')\n } else {\n $('section').find('menu').addClass('hidden')\n $('section').find('div.section-wrapper').removeClass('active')\n }\n })\n</code></pre>\n\n<p>Using a timeout will speed things up since it doesn't need to run everytime the browser size changes by 1 pixel: <a href=\"https://stackoverflow.com/questions/599288/cross-browser-window-resize-event-javascript-jquery\">https://stackoverflow.com/questions/599288/cross-browser-window-resize-event-javascript-jquery</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T17:03:10.197", "Id": "36427", "Score": "1", "body": "If you want to test out your performance JSPerf (http://jsperf.com/) is great for that. You can create isolated test cases with entire sections of code, or even compare one method with another." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T16:18:39.117", "Id": "36475", "Score": "1", "body": "you can still improve your code with variable caching and adding the timeout will improve performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T14:10:35.553", "Id": "36592", "Score": "0", "body": "In this case, variable caching wouldn't help. I need the updated page width. And ultimately, media queries are faster. If you have to use the document width in JS, use [document.body.clientWidth](http://jsperf.com/get-width)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T18:21:46.920", "Id": "23579", "ParentId": "23575", "Score": "1" } } ]
{ "AcceptedAnswerId": "23579", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T17:17:16.940", "Id": "23575", "Score": "2", "Tags": [ "javascript", "jquery", "css" ], "Title": "Convert JavaScript to CSS media query" }
23575
<p>I've managed to position the link boxes as I wanted and to apply a background to them, but I'm not sure I've done it in the most elegant or efficient way. </p> <p>Is there a better way to position the elements without mixing positioning and floats? And is there a way to remove the background between the link boxes without having to turn it off in the section and turn it on again for the boxes? Or any other suggestions?</p> <p>I've only been coding for a few months, but I aspire to write nice shiny code.</p> <p><a href="http://jsfiddle.net/ex_jedi/SSANp/2/" rel="nofollow">jsfiddle link</a></p> <pre class="lang-html prettyprint-override"><code>&lt;section class="three"&gt; &lt;a href="#"class="left-link link-box"&gt; &lt;h2&gt;Title&lt;/h2&gt; &lt;p&gt;Lorem ipsum dolor sit amet.&lt;/p&gt; &lt;/a&gt; &lt;a href="#"class="middle-link link-box"&gt; &lt;h2&gt;Title&lt;/h2&gt; &lt;p&gt;Lorem ipsum dolor sit amet.&lt;/p&gt; &lt;/a&gt; &lt;a href="#"class="right-link link-box"&gt; &lt;h2&gt;Title&lt;/h2&gt; &lt;p&gt;Lorem ipsum dolor sit amet.&lt;/p&gt; &lt;/a&gt; &lt;/section&gt; </code></pre> <pre><code>section { width: 1000px; margin: 1em auto; background: #C3C3C3 url(images/background.png); overflow: hidden; border-radius: 5px; } .three, .five { background: none; } .link-box { position: relative; display: block; float: left; text-decoration: none; color: #333; border-radius: 5px; width: 300px; background: #C3C3C3 url(images/background.png); } .left-link { float: left; } .right-link { float: right; } .middle-link { left: 5%; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T16:39:22.993", "Id": "36423", "Score": "0", "body": "Your background images in your fiddle don't load because you have to update the links to a public URL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T17:18:33.057", "Id": "36428", "Score": "0", "body": "I anticipated that which is why I added the colour. I was more interested in the best way to apply a background to the link boxes and not to the parent section element." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T17:22:52.130", "Id": "36430", "Score": "0", "body": "I think the way you applied the background to the link boxes is correct. You can see this if you remove the background declaration from .section, the link boxes will have their respective background." } ]
[ { "body": "<p>I edited your fiddle <a href=\"http://jsfiddle.net/SSANp/3/\" rel=\"nofollow\">jsFIddle</a>. Basically what I have done is removed <code>position:relative</code> and added <code>float:left</code> and then added some margin to the elements. Then with the last-child selector I removed margin from the last item.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T18:03:25.150", "Id": "23578", "ParentId": "23577", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T17:54:18.083", "Id": "23577", "Score": "3", "Tags": [ "html", "css" ], "Title": "Positioning link boxes & managing backgrounds" }
23577
<p>Given a sorted array, remove the duplicates in place such that each element appear at most twice and return the new length.</p> <p>Do not allocate extra space for another array, you must do this in place with constant memory.</p> <p>For example, Given sorted array A = [1,1,1,2,2,3],</p> <p>Your function should return length = 5, and A is now [1,1,2,2,3].</p> <p>The following is my code:</p> <pre><code>int rightMost_of_curElem(int A[], int curElem, int ind, int n) { while(ind&lt;n) { if(A[ind]!=curElem) break; ++ind; } return --ind; } int remove_duplicates(int A[], int n) { int i=0; int unique_num = 0; while(i&lt;n) { int cur_elem = A[i]; int pos = rightMost_of_curElem(A, cur_elem, i, n); if(A[pos]==A[pos-1]) { A[unique_num++] = A[pos]; } A[unique_num++] = A[pos]; i = pos+1; } return unique_num; } </code></pre>
[]
[ { "body": "<h3>Opps one bug:</h3>\n<pre><code> if(A[pos]==A[pos-1])\n</code></pre>\n<p>If <code>pos == 0</code> (if there is only one first element) it will fail (undefined behavior).</p>\n<h3>Two Recommendation:</h3>\n<p>This:</p>\n<pre><code> int i=0;\n while(i&lt;n)\n {\n // Stuff\n i = pos+1;\n }\n</code></pre>\n<p>Seems like a classic for(;;) loop.</p>\n<pre><code> for(int i = 0; i &lt; n; i = pos +1)\n {\n }\n</code></pre>\n<p>Don't use single letter variable names.<br />\nIf your function is only slightly larger then looking through the code and finding all the uses of <code>i</code> can be hard. Give it a longer more unique name.</p>\n<hr />\n<p>So the rest is just some personal preferences. Nothing I could complain about in a code review.</p>\n<h3>int rightMost_of_curElem(int A[], int curElem, int ind, int n)</h3>\n<p>This returns the righmost element. Which means the user has basically has the index to beginning an end of a range. Most C/C++ like functions use a concept of beginning to one past the end. So I would have made this return the index of the first element that did not match (and re-named slightly).</p>\n<p>Slight improvement is that you pass the index of the current index which you already know equals the value. You should pass current index + 1 (avoids one compare).</p>\n<h3>int remove_duplicates(int A[], int n)</h3>\n<p>You hard code the number of elements to retain. In an interview (and in real life) I would have parametrized this.</p>\n<p>Using <code>if(A[pos]==A[pos-1])</code> as a test seems a bit hard to read when testing one or two elements. I would just use the distance between <code>pos</code> and <code>i</code> to find the number.</p>\n<h3>I would have written like this:</h3>\n<pre><code>int getNextElement(int* data, int size, int index, int curElem)\n{\n for( ; ((index &lt; size) &amp;&amp; (data[index] == curElem)) ; ++index)\n { /* No Body */ }\n\n return index;\n}\n\nint removeDuplicates(int* data, int size, int maxElements)\n{\n int count = 0;\n int pos = 0;\n for(int loop = 0; loop &lt; size; loop = pos)\n {\n int pos = getNextElement(data, size, loop + 1, data[loop]);\n\n int lastElement = min(loop + maxElement, pos);\n memcpy(data + count, data + loop, (lastElement - loop) * sizeof(int));\n count += (lastElement - loop)\n /*\n for(int copy = loop; copy &lt; lastElements; ++copy, ++count)\n {\n data[count] = data[copy];\n }\n */\n }\n\n return count;\n}\n\nint removeDuplicates2(int* data, int size) {return removeDuplicates(data, size, 2);}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T00:39:44.817", "Id": "36382", "Score": "0", "body": "There are a few compile errors in there. Also, why roll your own `memcpy`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T04:10:23.393", "Id": "36391", "Score": "0", "body": "@WilliamMorris: Fixed errors. Two reasons 1) Its not what I would do in an interview (maybe I should). 2) I did not think about it. But yes `memcpy()` is probably the best choice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T16:59:05.537", "Id": "36425", "Score": "0", "body": "is it a typo `data+copy` ==> `data+loop`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T17:39:20.963", "Id": "36431", "Score": "0", "body": "`count += (lastElement - loop)`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T22:28:20.210", "Id": "23594", "ParentId": "23582", "Score": "5" } }, { "body": "<h2>General comments</h2>\n\n<ul>\n<li><p>mixed naming style - youve got camelCase and separate_words combined!</p></li>\n<li><p>upper case naming (<code>A[]</code>)is for #define constants</p></li>\n<li><p>I prefer to see a space after <code>while</code> and <code>if</code> etc and spaces around\noperators (<code>!=</code> etc)</p></li>\n</ul>\n\n<hr>\n\n<h2>In <code>rightMost_of_curElem</code></h2>\n\n<ul>\n<li><p>verbose name</p></li>\n<li><p>function takes 4 parameters which seems excessive; <code>strspn</code> does\nthe same for strings and takes just 2.</p></li>\n<li><p><code>A[]</code> should be const</p></li>\n<li><p>returns -1 if <code>ind</code> and <code>n</code> are both 0. Ok that is not going to happen but\na function that has input conditions under which it fails is undesirable.</p></li>\n<li><p>should be static</p></li>\n<li><p>pedantic: missing braces on the if statement</p></li>\n</ul>\n\n<hr>\n\n<h1>In <code>remove_dupicates</code></h1>\n\n<p><code>unique_num</code> is an odd name</p>\n\n<ul>\n<li><p><code>cur_elem</code> is unnecessary - and why is it <code>cur_elem</code> here and <code>curElem</code> in\n<code>rightMost_of_curElem</code> (name and parameter)</p></li>\n<li><p><code>pos</code>, <code>i</code> and <code>unique_num</code> here and <code>ind</code> in <code>rightMost_of_curElem</code> are the\nsame quatity. One wouldn't guess this from the names. You can't always\nuse the same name everywhere, but one might at least expect <code>ind</code> and <code>pos</code>\nto be the same.</p></li>\n<li><p>as @LokiAstari says, there is a bug in your <code>if(A[pos]==A[pos-1])</code>. You\nmust always be careful when using negative offsets in array indices.</p></li>\n</ul>\n\n<hr>\n\n<p>Here's another approach, for what it is worth:</p>\n\n<pre><code>static inline int intspan(const int *in, const int *end)\n{\n int span = 1;\n for (; in + span &lt; end; ++span) {\n if (in[0] != in[span]) {\n break;\n }\n }\n return span;\n}\n\nstatic size_t remove_duplicates(int *const in, int n)\n{\n const int *data = in;\n const int *end = data + n;\n int *out = in;\n\n while (data &lt; end) {\n int span = intspan(data, end);\n *out++ = *data;\n if (span &gt; 1) {\n *out++ = *data;\n }\n data += span;\n }\n return (size_t) (out - in);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T00:33:05.450", "Id": "23599", "ParentId": "23582", "Score": "2" } } ]
{ "AcceptedAnswerId": "23594", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T19:46:16.943", "Id": "23582", "Score": "3", "Tags": [ "c", "algorithm", "interview-questions" ], "Title": "remove duplicates in a sorted array if duplicates are allowed at most twice" }
23582
<p>Does the following code look okay? Want to see if anyone can spot any mistakes I may have made. This will be pulling from a pre-formatted Excel document - I have already specified all needed Cell locations.</p> <p>Things I want clarified:</p> <ul> <li><p>How many times can you invoke SetInfo and did I use it more than needed? I was under the impression that a SetInfo would be needed before a SetPassword can be used, but I could be very wrong.</p></li> <li><p>Does this line look okay? Was I correct to separate multiple cells using a comma in order to put all the info together? I know it worked with an Echo command:</p> <pre><code>Set objUser = objOU.Create _ ("User", "cn=" &amp; objExcel.Cells(intRow, 3).Value, objExcel.Cells(intRow, 2).Value, objExcel.Cells(intRow, 19).Value) </code></pre></li> <li><p>Is this the correct code for setting a password to never expire?</p> <pre><code>objUser.Put "userAccountControl", intUAC XOR _ ADS_UF_DONT_EXPIRE_PASSWD </code></pre></li> <li><p>Full code below, I'd appreciate any feedback on anything else that is found.</p> <pre><code>Set objExcel = CreateObject("Excel.Application") Set objWorkbook = objExcel.Workbooks.Open _ ("C:\Book1.xls") intRow = 2 Do Until objExcel.Cells(intRow,1).Value = "" Set objOU = GetObject _ ("ou=" &amp; objExcel.Cells(intRow, 13).Value &amp; _ ", dc=satdc, dc=com") Set objUser = objOU.Create _ ("User", "cn=" &amp; objExcel.Cells(intRow, 3).Value, objExcel.Cells(intRow, 2).Value, objExcel.Cells(intRow, 19).Value) objUser.sAMAccountName = objExcel.Cells(intRow, 19).Value &amp; ".sat" objUser.GivenName = objExcel.Cells(intRow, 3).Value objUser.SN = objExcel.Cells(intRow, 2).Value objUser.SetInfo objUser.AccountDisabled = False objUser.AccountExpirationDate = Date + 365 objUser.SetPassword objExcel.Cells(intRow, 9).Value objUser.SetInfo objUser.Put "userAccountControl", intUAC XOR _ ADS_UF_DONT_EXPIRE_PASSWD objUser.HomeDirectory = "\\satdc" &amp; "\" &amp; "Users" &amp; "\" &amp; _ objUser.Get("sAMAccountName") objUser.homeDrive = "U:" objUser.SetInfo intRow = intRow + 1 Loop objExcel.Quit </code></pre></li> </ul>
[]
[ { "body": "<h1>Naming: <em>Hungarian Notation</em> is the DEVIL.</h1>\n<h3>It makes the reader want to see your code burn in eternal flames.</h3>\n<blockquote>\n<p><img src=\"https://simpsonswiki.com/w/images/7/7c/Devil_Flanders.png\" alt=\"enter image description here\" /></p>\n<p><a href=\"https://simpsonswiki.com/wiki/Flanders_the_Devil\" rel=\"nofollow noreferrer\">https://simpsonswiki.com/wiki/Flanders_the_Devil</a></p>\n</blockquote>\n<ul>\n<li><code>objExcel</code> would be better off as <code>xlApp</code> or <code>excelApp</code></li>\n<li><code>objUser</code> is dying to call itself something like <code>adUser</code></li>\n<li><code>intRow</code> wants to be called <code>xlRow</code> or just <code>row</code></li>\n<li><code>intUAC</code> is silently begging for a more descriptive name</li>\n<li><code>objOU</code> wants to shoot whoever named it that</li>\n</ul>\n<p>Now, whether your code is correct or not is off-topic for this site; since this question hasn't been closed as off-topic yet, I'm going to assume you've got working code.</p>\n<pre><code>Do Until objExcel.Cells(intRow,1).Value = &quot;&quot;\n</code></pre>\n<p>I'd use <code>vbNullString</code> here instead of <code>&quot;&quot;</code>. It makes the intent clearer, and the non-string takes up 0 bytes. <code>&quot;&quot;</code> eats 6 bytes for no reason - <code>StrPtr(vbNullString)</code> is 0; <code>StrPtr(&quot;&quot;)</code> is a non-zero memory address.</p>\n<p>The repeated assignments on <code>objUser</code> are a missed opportunity of using a <code>With</code> block:</p>\n<pre><code>With objOU.Create(&quot;User&quot;, &quot;cn=&quot; &amp; objExcel.Cells(intRow, 3).Value, _\n objExcel.Cells(intRow, 2).Value, _\n objExcel.Cells(intRow, 19).Value)\n\n .SAMAccountName = objExcel.Cells(intRow, 19).Value &amp; &quot;.sat&quot;\n .GivenName = objExcel.Cells(intRow, 3).Value\n .SN = objExcel.Cells(intRow, 2).Value\n .AccountDisabled = False\n .AccountExpirationDate = Date + 365\n '...\n\nEnd With\n</code></pre>\n<p>Your usage of line continuation characters is... well, you use it in weird places. Actually, everywhere you've used it, I wouldn't have. Notice in the above snippet, how I used it to line up the parameters.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-12T02:04:57.013", "Id": "37191", "ParentId": "23583", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T19:49:58.280", "Id": "23583", "Score": "4", "Tags": [ "vbscript" ], "Title": "VBScript for AD account creation" }
23583
<p>I wrote an infinite scrolling scrolling plugin for an app I'm developing. When requesting the second 'page' from the server, I loop through each image, and give it a very basic <code>onload</code> function.</p> <pre><code>// I will have the result in a variable called data // Fetch each image from result $images = $( data.content ).find('img'); // Cache length for use in for loop imagesLength = $images.length; for ( var i = 0; i &lt; imagesLength; i++ ) { // Create new Image object img = new Image(); // Match src of image in the result img.src = ( $images[i].src ); // Add onload listener img.onload = function () { // Increment iterator, and check if we've loaded all the images if( ++imageLoadingIterator == images.length) _continue(); // Run _continue() if this is the case } } </code></pre> <p>I feel like this isn't the best way to do this. Is there a way I can improve this function to run faster? For example: I'm thinking maybe creating a new <code>Image</code> object for each <code>img</code> tag is too much overhead.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T00:26:32.150", "Id": "36380", "Score": "0", "body": "Why do you think it can be sped up? Because as far as I can tell, the js can't be made much faster. If it seems slow, it's probably the actual image fetching that's taking time" } ]
[ { "body": "<p>Not really about performance, but this is more about clarity of the code.</p>\n\n<ul>\n<li><p>Attach <code>onload</code> handlers first, for readability. Appending the <code>src</code> starts the loading process. If you saw code that loaded something, expect to do something, but haven't found the handler to do it makes it a bit confusing.</p></li>\n<li><p>Declare one handler function in a persistent scope and have the <code>onload</code> refer to it, rather than create one handler for each onload, or creating the function everytime the whole routine executes.</p></li>\n<li><p>Instead of <code>find()</code>, use jQuery function's second parameter, context. With this, jQuery finds the elements with the given selector under the jQuery object that is on the second parameter.</p></li>\n<li><p>If the images are children of <code>data.content</code>, use <code>children()</code> instead of <code>find()</code> to avoid deep DOM traversal. Also, the lower you are in the DOM, the less deep <code>find()</code> has to dive and find your elements. </p></li>\n<li><p>Use strict comparison as much as possible.</p></li>\n<li><p>Don't forget to declare the variables and use <code>var</code>. You'd be declaring globals if you didn't.</p></li>\n</ul>\n\n<p>And so:</p>\n\n<pre><code>var $images = $('img', data.content),\n imagesLength = $images.length,\n imageLoadingIterator = 0,\n img, i;\n\nfunction onImageLoad() {\n if (++imageLoadingIterator === images.length) _continue();\n}\n\nfor (i = 0; i &lt; imagesLength; i++) {\n img = new Image();\n img.onload = onImageLoad;\n img.src = $images[i].src;\n}\n</code></pre>\n\n<p>However, these advices might have a very negligible gain in performance, and might be unnecessary since the compiler might be optimizing them in some way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T17:21:39.870", "Id": "36429", "Score": "0", "body": "Thanks for the tips! I defined the variables as you recommended already, but I forgot to paste it into the question. It was behind some other (irrelevant) code so I missed it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-04T21:41:35.877", "Id": "215118", "Score": "0", "body": "Also, wrap your code in a `(function($){ ... })(jQuery);` to avoid problems with `jQuery.noConflict();` *and* to keep those `var`s as local variables, instead of global. That should massivelly reduce any risk of outside manipulation and should increase the performance a bit more (since it doesn't have to access the over-crowded `window` object for your variables)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T12:19:43.010", "Id": "23618", "ParentId": "23587", "Score": "4" } } ]
{ "AcceptedAnswerId": "23618", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T20:34:45.400", "Id": "23587", "Score": "3", "Tags": [ "javascript", "performance", "jquery", "image", "ajax" ], "Title": "JavaScript Image Preloading Script" }
23587
<p>I have an sql table with multiple fields and 4 of them are enums. I wrote a script that runs thought the table and retrieve the enums and put them in a 2 dimension array.</p> <p>Unfortunately this script is extreamly slow and I can't fix it. </p> <pre><code>&lt;?php require_once('mySQL_Connect.php'); $con = ConnectToDataBase(); if ($con == false) { //data returned will be null exit; } $db = 'courses_db'; $table = 'courses'; $fields = array( 'training_field', 'speciality_field', 'type', 'language'); $enums = array(); foreach ($fields as $colomn) { $sq1 = "SELECT column_type FROM information_schema.columns WHERE table_schema = '$db' AND table_name = '$table' AND column_name = '$colomn'"; $query = mysqli_query($con,$sq1); $stack = array(); $i = 0; $stack[$i]=$colomn; if ($fetch = mysqli_fetch_assoc($query) ) { $enum = $fetch['column_type']; $off = strpos($enum,"("); $enum = substr($enum, $off+1, strlen($enum)-$off-2); $values = explode(",",$enum); // For each value in the array, remove the leading and trailing // single quotes, convert two single quotes to one. Put the result // back in the array in the same form as CodeCharge needs. for( $n = 0; $n &lt; Count($values); $n++) { $val = substr( $values[$n], 1,strlen($values[$n])-2); $val = str_replace("''","'",$val); $stack[$i+1]=$val; $i++; } } // return the values array to the caller //echo json_encode( $stack); array_push($enums,$stack); reset($stack); } echo json_encode($enums); ?&gt; </code></pre>
[]
[ { "body": "<p>You can use describe queries in mysql to find column types</p>\n\n<p>for example <code>DESCRIBE courses</code> returns the table information including column type</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T09:50:05.197", "Id": "23648", "ParentId": "23592", "Score": "3" } }, { "body": "<p>I finally found a solution and here it is:</p>\n\n<pre><code>function get_enum_values($connection, $table, $field )\n{\n\n $query = \" SHOW COLUMNS FROM `$table` LIKE '$field' \";\n $result = mysqli_query($connection, $query );\n $row = mysqli_fetch_array($result , MYSQL_NUM );\n #extract the values\n #the values are enclosed in single quotes\n #and separated by commas\n $regex = \"/'(.*?)'/\";\n preg_match_all( $regex , $row[1], $enum_array );\n $enum_fields = $enum_array[1];\n\n return( $enum_fields );\n}\n</code></pre>\n\n<p>So basically there's no need to go through information_schema!</p>\n\n<p>Credit goes to this blog:</p>\n\n<p><a href=\"http://akinas.com/pages/en/blog/mysql_enum/\" rel=\"nofollow\">http://akinas.com/pages/en/blog/mysql_enum/</a></p>\n\n<p>Hope this helps out some people.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T22:18:57.540", "Id": "24021", "ParentId": "23592", "Score": "3" } } ]
{ "AcceptedAnswerId": "24021", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T21:34:25.810", "Id": "23592", "Score": "0", "Tags": [ "php", "performance", "mysql", "sql" ], "Title": "php script to retrieve enum values from sql table" }
23592
<p>I've just started programming with JavaScript and I am currently working on this hobby website project of mine. The site is supposed to display pages filled with product images than can be "panned" to either the left or right. Each "page" containing about 24 medium sized pictures, one page almost completely fills out an entire screen. When the user chooses to look at the next page he needs to click'n'drag to the left (for example) to let a new page (dynamically loaded through an AJAX script) slides into the view.</p> <p>This requires for my JavaScript to "slide" two of these mentioned pages synchronously by the width of a screen. This results in a really low framerate. Firefox and Opera lag a bit, Chrome has it especially bad: 1 frame of animation takes approx. 100 milliseconds, thus making the animation look very "laggy".</p> <p>I do not use jQuery, nor do I want to use it or any other library to "do the work for me". At least not until I know for sure that what I am trying to do can not be done with a couple of lines of self-written code.</p> <p>So far I have figured out that the specific way I manipulate the DOM is causing the performance-drop. The routine looks like this:</p> <pre><code>function slide(){ this.t=new Date().getTime()-this.msBase; if(this.t&gt;this.msDura) { this.callB.call(this.ref,this.nFrames); return false; } //calculating the displacement of both elements // this.pxProg=this.tRatio*this.t; this.eA.style.left=(this.pxBaseA+this.pxProg)+'px'; this.eB.style.left=(this.pxBaseB+this.pxProg)+'px'; if(bRequestAnimationStatus)requestAnimationFrame(slide.bind(this)); else window.setTimeout(slide.bind(this),16); this.nFrames++; }; ... //starting an animation // slide.call({ 'eA':theMiddlePage, 'eB':neighboorPage, 'callB':theCallback, 'msBase':new Date().getTime(), 'msDura':400, 'tRatio':((0-pxScreenWidth)/400), 'nFrames':0, 'ref':myObject, 'pxBaseA':theMiddlePage.offsetLeft, 'pxBaseB':neighboorPage.offsetLeft }); </code></pre> <p>I've noticed that when I let the AJAX script load less images into each page, the animation becomes much faster. The separate images seem to create more overhead than I have expected. Is there another way to do this?</p> <p>(Reposted from Stack Overflow <a href="https://stackoverflow.com/questions/15283511/animating-multiple-div-elements-with-js-and-the-dom-results-in-a-low-framerate">here</a>)</p>
[]
[ { "body": "<p>Well I can only guess without seeing the code where the DOM is actually accessed but one thing that looks big to me is that you appear to be manipulating each individual element in seperate frames. If you did the calcs in one function for all elements that would be (I believe) one set of reflow calcs set off in the browser rather than per elements-moved.</p>\n\n<p>Basically any time there is a change to the DOM a series of reflow calculations is set off in the browser. I think when say three DOM changes are made in one function call, the browser is aware of all three before it starts doing anything. Whereas with seperate funcs it does that same work multiple times.</p>\n\n<p>How much reflow calculation gets set off for an action on the DOM in any given browser isn't something I'm a real wizard on but IIRC tends to be a fairly crude operation that doesn't necessarily take \"out of flow\" elements like absolutely positioned containers into consideration. That said, I still tend to find the DOM seems to have an easier time of it when you try to optimize by taking movable elements out of flow first.</p>\n\n<p>If you don't need to support older browsers, look into CSS3 animation approaches. These can drastically improve animation performance since browsers can optimize for actions before they happen.</p>\n\n<p>Barring that, avoid touching the DOM as much as possible in loops. If you must access properties on a DOM element multiple times, don't keep reacquiring it. Assign it to a var, effectively caching that operation (note: might not matter in newer browsers). But actually making changes to the DOM is where you need to optimize the most. Sidestep with pre-set CSS3 animations or follow some of the older-school stuff I've outlined here and we can examine in more depth if needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T23:46:24.497", "Id": "36378", "Score": "0", "body": "yes, Jude Osborn pointed out CSS3 animations to me as well. Currently checking out the \"transition\" attribute. This looks like it might be the solution to my problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T23:49:24.170", "Id": "36379", "Score": "0", "body": "Yep, just track minimum IE support for whatever css3 properties you use. I don't think they even touched CSS3 support until IE9. The ideal way to handle it is old-school and new-school depending on what's available." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T23:31:38.060", "Id": "23596", "ParentId": "23595", "Score": "1" } } ]
{ "AcceptedAnswerId": "23596", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-07T23:14:47.900", "Id": "23595", "Score": "1", "Tags": [ "javascript", "image", "animation", "dom", "google-chrome" ], "Title": "Website with images that pan to different sides" }
23595
<p>This question is about improving my C++ coding skills. I was asked to implement a simple static integer stack in C++ as an assignment. I've come up with the following code:</p> <pre><code>class myStaticIntStack { int stackSize; int storedElements; int *elements; public: myStaticIntStack(); myStaticIntStack( int aNumber ); ~myStaticIntStack(); int peek(); int pop(); void push( int element ); }; myStaticIntStack::myStaticIntStack() { this-&gt;stackSize = 1; this-&gt;elements = new int(0); this-&gt;storedElements = 0; } myStaticIntStack::myStaticIntStack( int stackSize ) { this-&gt;stackSize = stackSize; this-&gt;elements = new int[ stackSize ]; this-&gt;storedElements = 0; } myStaticIntStack::~myStaticIntStack() { if( this-&gt;elements != NULL ) { if( stackSize &gt; 1 ) delete[] this-&gt;elements; else delete this-&gt;elements; } } void myStaticIntStack::push( int newElement ) { if( this-&gt;storedElements == this-&gt;stackSize ) cout &lt;&lt; "Stack is full, you must POP an element before PUSHing a new one!" &lt;&lt; endl; else { this-&gt;elements[ (this-&gt;stackSize - 1) - this-&gt;storedElements ] = newElement; this-&gt;storedElements++; } } int myStaticIntStack::pop() { if( this-&gt;storedElements == 0 ) { cout &lt;&lt; "Stack is empty, you must PUSH an element before POPping one!" &lt;&lt; endl; return -1; } else { storedElements--; return this-&gt;elements[ (this-&gt;stackSize - 1) - this-&gt;storedElements ]; } } int myStaticIntStack::peek() { if( this-&gt;storedElements == 0 ) { cout &lt;&lt; "Stack is empty, you must PUSH an element before PEEKing one!" &lt;&lt; endl; return -1; } else { return this-&gt;elements[ this-&gt;stackSize - this-&gt;storedElements ]; } } int main() { myStaticIntStack aStack(3); cout &lt;&lt; "Popped Element: " &lt;&lt; aStack.pop() &lt;&lt; endl; aStack.push(1); cout &lt;&lt; "Stack Top is: " &lt;&lt; aStack.peek() &lt;&lt; endl; aStack.push(2); cout &lt;&lt; "Stack Top is: " &lt;&lt; aStack.peek() &lt;&lt; endl; aStack.push(3); cout &lt;&lt; "Stack Top is: " &lt;&lt; aStack.peek() &lt;&lt; endl; aStack.push(4); cout &lt;&lt; "Stack Top is: " &lt;&lt; aStack.peek() &lt;&lt; endl; cout &lt;&lt; "Popped Element: " &lt;&lt; aStack.pop() &lt;&lt; endl; cout &lt;&lt; "Stack Top is: " &lt;&lt; aStack.peek() &lt;&lt; endl; cout &lt;&lt; "Popped Element: " &lt;&lt; aStack.pop() &lt;&lt; endl; cout &lt;&lt; "Stack Top is: " &lt;&lt; aStack.peek() &lt;&lt; endl; cout &lt;&lt; "Popped Element: " &lt;&lt; aStack.pop() &lt;&lt; endl; cout &lt;&lt; "Stack Top is: " &lt;&lt; aStack.peek() &lt;&lt; endl; return 0; } </code></pre> <p>The code is compiling and running correctly, this is standard output:</p> <pre><code>Stack is empty, you must PUSH an element before POPping one! Popped Element: -1 Stack Top is: 1 Stack Top is: 2 Stack Top is: 3 Stack is full, you must POP an element before PUSHing a new one! Stack Top is: 3 Popped Element: 3 Stack Top is: 2 Popped Element: 2 Stack Top is: 1 Popped Element: 1 Stack is empty, you must PUSH an element before PEEKing one! Stack Top is: -1 </code></pre> <p>However I was given a B due to the following reasons:</p> <ol> <li>There was a better way of implementing it. </li> <li>I didn't manage well the case in which I'm trying to POP an element from an empty stack, since it's confusing that <code>pop()</code> returns a value even if Stack is empty.</li> </ol> <p>Can you please help me understand how I could improve my code?</p>
[]
[ { "body": "<p><code>this</code> is not always needed in member functions, you can remove all the </p>\n\n<pre><code>this-&gt;\n</code></pre>\n\n<p>The compiler knows this from the context.</p>\n\n<p>And move brackets, e.g.:</p>\n\n<pre><code>int myStaticIntStack::peek() {\n if( 0 == storedElements ){\n cout &lt;&lt; \"Stack is empty, you must PUSH an element before PEEKing one!\" &lt;&lt; endl;\n return -1;\n }\n else{\n return elements[stackSize - storedElements ];\n }\n}\n</code></pre>\n\n<p>In comparisons, the <code>const</code> is safer on the left. This avoids a possible <code>=</code>, which is a common error.</p>\n\n<p>You could improve it by making a vector class. You may have to do this from scratch if it is homework. It would be better than old C arrays.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T00:30:48.043", "Id": "36381", "Score": "0", "body": "thks for pointing out, but I hope this is not the only thing I could have done better in the code... ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T00:29:21.553", "Id": "23598", "ParentId": "23597", "Score": "4" } }, { "body": "<p>First of all, your code has a bug: You did not follow the <a href=\"http://en.wikipedia.org/wiki/Rule_of_three_%28C++_programming%29\" rel=\"nofollow noreferrer\">rule of three</a>.\nCode such as <code>myStack1 = myStack2;</code> will cause the pointer to be deleted twice - which is undefined behavior.</p>\n\n<hr>\n\n<pre><code>int storedElements;\n</code></pre>\n\n<p>This seems kind of misleading. This variable doesn't hold the <em>stored elements</em>. It holds the <em>number of stored elements</em>. Perhaps <code>storedElementsCount</code> or something like that would be better?</p>\n\n<hr>\n\n<pre><code>myStaticIntStack( int aNumber );\n</code></pre>\n\n<p>Why did you call the variable <code>aNumber</code> here? <code>aNumber</code> is a <em>terrible</em> name. It tells me essentially <em>nothing</em>. Later you used <code>stackSize</code> which is a <strong>FAR</strong> better name. Why didn't you use it here too?</p>\n\n<p>And, by the way, consider using <code>size_t</code> to store sizes and capacities instead of ints. This would apply to <code>stackSize</code> and <code>storedElements</code>.</p>\n\n<hr>\n\n<pre><code>myStaticIntStack::myStaticIntStack()\n{\n this-&gt;stackSize = 1;\n this-&gt;elements = new int(0);\n this-&gt;storedElements = 0;\n}\n</code></pre>\n\n<p>Seriously? The default behavior for the stack is to create a stack with maximum size 1? That is kind of... worthless. It's OK to allow this in the myStaticIntStack(int) constructor, but as a <em>default</em> it just seems odd.</p>\n\n<p>Consider not even allowing a default constructor.</p>\n\n<hr>\n\n<pre><code>myStaticIntStack::myStaticIntStack( int stackSize )\n{\n this-&gt;stackSize = stackSize;\n this-&gt;elements = new int[ stackSize ];\n this-&gt;storedElements = 0;\n}\n</code></pre>\n\n<p>Can the stackSize be zero? Can it be negative? Consider adding an assertion.\nBy the way, if you make stackSize be a size_t, the negative case becomes impossible, since size_t is unsigned. But you'll still need to handle the \"stackSize == 0\" case.</p>\n\n<p>A size of 0 might be acceptable. If that is the case, add a comment stating that and why it is so.</p>\n\n<p>Consider declaring this constructor <code>explicit</code>.</p>\n\n<hr>\n\n<pre><code>myStaticIntStack::~myStaticIntStack()\n{\n if( this-&gt;elements != NULL )\n {\n if( stackSize &gt; 1 )\n delete[] this-&gt;elements;\n else\n delete this-&gt;elements;\n }\n\n}\n</code></pre>\n\n<p>Why do you need a NULL check? Are you expecting the destructor to be called with <code>elements == NULL</code>? If this merely defensive programming and this case is never supposed to happen, then leave it as an assertion.</p>\n\n<p>Also, that whole <code>delete</code> vs <code>delete[]</code> is weird. What if I use the constructor <code>myStaticIntStack(1)</code>? Then you'll be <code>delete</code>ing something created with <code>new[]</code>.</p>\n\n<p>I'd change the code (from the constructors) so that <code>new[]</code> - not <code>new</code> - is always used and, therefore, <code>delete[]</code> is always the right thing to do in the destructor.</p>\n\n<hr>\n\n<pre><code>void myStaticIntStack::push( int newElement )\n{\n if( this-&gt;storedElements == this-&gt;stackSize )\n cout &lt;&lt; \"Stack is full, you must POP an element before PUSHing a new one!\" &lt;&lt; endl;\n else\n {\n this-&gt;elements[ (this-&gt;stackSize - 1) - this-&gt;storedElements ] = newElement;\n this-&gt;storedElements++;\n }\n}\n</code></pre>\n\n<p>This is improper error handling that violates the single responsibility principle.\nYour function should either throw an exception, merely assert the condition or return an error code. Printing to the command line should be done elsewhere - probably <em>outside</em> this class.</p>\n\n<hr>\n\n<pre><code>this-&gt;elements[ (this-&gt;stackSize - 1) - this-&gt;storedElements ] = newElement;\n</code></pre>\n\n<p>I'm pretty sure you could simplify this. For a stackSize=16, the first position is at index 15. Why 15? Why not 0? That'd simplify the code to just <code>elements[storedElements] = newElement;</code>. Just remember to also fix the pop/peek code.</p>\n\n<p>Just because the stack is Last-in-first-out doesn't mean you have to fill the last indexes in the internal array first. That's an implementation detail.</p>\n\n<hr>\n\n<blockquote>\n <p>it's confusing that pop() returns a value even if Stack is empty.</p>\n</blockquote>\n\n<p>Then <em>don't</em> return a value if the Stack is empty. Throw an exception or abort with an assertion. Problem solved. Next.\nAs I stated before, your <code>cout</code>s are in the wrong place. If you fix that the \"Pop return\" problem might just naturally go away.</p>\n\n<p>If you decide to keep it like that (return -1), then consider making <code>-1</code> a named constant since <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">magic numbers</a> are bad.</p>\n\n<pre><code>return ERROR_STACK_IS_EMPTY;\n</code></pre>\n\n<hr>\n\n<pre><code>int myStaticIntStack::peek()\n</code></pre>\n\n<p>Same thing about <code>cout</code>.\nAlso, <code>peek()</code> doesn't change anything, does it? Then consider making it <code>const</code>.</p>\n\n<pre><code>int myStaticIntStack::peek() const\n</code></pre>\n\n<hr>\n\n<p>Consider splitting your myStaticIntStack in two files: <code>myStaticIntStack.hpp</code> and <code>myStaticIntStack.cpp</code>.\nYour main function would be in a third file.</p>\n\n<hr>\n\n<p>Some extra thoughts:</p>\n\n<ul>\n<li>I suspect the \"better way\" might be to just use a vector internally. This would painlessly solve your \"rule of three\" problem. Bonus points since it'd make it easier to \"resize\" the stack after being created if you ever wanted to add that feature.</li>\n<li>Personally, I'd uppercase the first letter of the class name, but that's just personal preference. Nothing wrong with your particular style.</li>\n<li>Consider adding a <code>bool empty()</code> function, that checks if the stack is empty.</li>\n<li>Consider adding a <code>bool full()</code> function, that checks if the stack is full.</li>\n<li>Those two functions above could make your error detection code easier to understand. If your assignment forbids adding extra functions, consider adding them as private functions.</li>\n<li>Consider adding a <code>int size()</code> function, that returns storedElements.</li>\n<li>Consider adding a <code>int capacity()</code> function, that returns stackSize</li>\n<li>Normally, a class like this would be implemented as a template since it's useful to have stacks for more than just integers. Not sure if you've learned about templates yet.</li>\n</ul>\n\n<p>If you follow QuentinUK's suggestion of removing the <code>this-&gt;</code>, beware. There is one case that might cause you trouble.\nIn the constructor, <code>this-&gt;stackSize = stackSize;</code> is correct, but <code>stackSize = stackSize;</code> would not be.\nTo work around this issue, you could use something like this:</p>\n\n<pre><code>/*optionally add \"explicit\" here*/ myStaticIntStack::myStaticIntStack( int stackSize ) :\n stackSize(stackSize)\n{\n elements = new int[ stackSize ];\n storedElements = 0;\n}\n</code></pre>\n\n<p>This is all I can think of right now. Hope this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T01:47:03.167", "Id": "36385", "Score": "0", "body": "It helps a lot! I just need to think about it a correction at the time! If I have doubts can I comment you?Thanks anyways and I'm sure next time I'll get an A... ;D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T12:18:17.510", "Id": "36408", "Score": "0", "body": "If you have any further questions about this code snippet, feel free to add a comment. If your questions are about a different code snippet, then you should post a new question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-03T18:23:11.197", "Id": "85805", "Score": "0", "body": "\"Consider using `size_t` to store sizes and capacities.\" This excellent advice also provides *much better* names for `storedElements` and `stackSize`, respectively." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T01:30:45.883", "Id": "23602", "ParentId": "23597", "Score": "8" } }, { "body": "<p>If you have to implement a stack backwards, ok. :) It's a common thought pattern; i used to do it all the time too. But the truth is, it makes a lot of things easier if you consider the stack to grow upward.</p>\n\n<pre><code>void myStaticIntStack::push( int newElement )\n{\n if( storedElements == stackSize ) {\n cout &lt;&lt; \"Stack is full, you must POP an element before PUSHing a new one!\" &lt;&lt; endl;\n }\n else {\n // note the lack of index math :P\n elements[ storedElements ] = newElement;\n storedElements++;\n\n // you could even do this all in one line like:\n // elements[storedElements++] = newElement;\n // but i assume you're just learning c++, so. :)\n }\n}\n\nint myStaticIntStack::pop()\n{\n if( storedElements == 0 )\n {\n // For future reference, you should be throwing exceptions here, rather than\n // returning an int. You're forgiven this time, cause you're new. :)\n // But what if i wanted to store -1 in this thing? I can't reliably do that,\n // now that you've used -1 as an error code.\n\n cout &lt;&lt; \"Stack is empty, you must PUSH an element before POPping one!\" &lt;&lt; endl;\n return -1;\n }\n else\n {\n storedElements--;\n // again, note the indexing is much simpler\n return elements[storedElements];\n\n // You could likewise make this a one-liner...\n // return elements[--storedElements];\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T01:48:39.720", "Id": "36386", "Score": "0", "body": "thks a lot for your suggestions!They'll come handy and next time I won't do these mistakes anymore, I promise ;P" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T01:43:27.513", "Id": "23603", "ParentId": "23597", "Score": "3" } }, { "body": "<p>Ok, a few comments:</p>\n\n<ol>\n<li><p>If you are going to support a stack with no capacity, I don't know why you need to allocate memory at all. You could simply have the pointer as <code>NULL</code>.</p></li>\n<li><p>Using <code>cout</code> for error handling is not appropriate. You could either give \"undefined behaviour\" however may I suggest you throw an exception. You can handle your exceptions and use <code>cout</code> in your exception handler.</p></li>\n<li><p>Implement a deep copy constructor and implement <code>swap()</code>. Then implement assignment in terms of both of these. To swap you would do:</p>\n\n<pre><code>void MyStaticIntStack::swap( MyStaticIntStack &amp; other )\n{\n // swap each member\n}\n</code></pre></li>\n</ol>\n\n<p>If you don't like using <code>std::swap</code>, write your own. I am not sure you have to avoid all STL, you probably cannot use STL containers for this because the exercise is to write your own container, but utilities like swap may be permitted (plus you can throw std exceptions).</p>\n\n<p>I don't see why <code>-1</code> shouldn't be a valid number in your stack. If someone does not know whether your stack is empty and tries a <code>peek()</code> from code, they would get -1 (plus some <code>cout</code> that they cannot handle). Perhaps have a method</p>\n\n<pre><code>bool empty() const;\n</code></pre>\n\n<p>which tells you if the stack is empty or not. You could also have <code>size()</code> and <code>capacity()</code> access methods.</p>\n\n<p>You might want to be able to resize the capacity of your stack. If you find that difficult, have a private constructor that takes a new capacity plus a reference to an existing stack. That constructor can create the data with the relevant size and copy the data into it.</p>\n\n<p>Your internal method would call this constructor to create a new bigger capacity stack, then invoke the <code>swap()</code> method. The temporary one would now disappear. (Do not create it with new).</p>\n\n<p>On a style issue:</p>\n\n<ol>\n<li>Initialize your members in the constructor initialization list, not the body of your constructor.</li>\n<li>Do not use <code>this-&gt;</code> all over the code.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T21:38:36.737", "Id": "36551", "Score": "0", "body": "Thanks for all the suggestions, I found them very useful! can I please ask you some more specific details about the initialization list?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T11:02:08.913", "Id": "23616", "ParentId": "23597", "Score": "3" } } ]
{ "AcceptedAnswerId": "23602", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T00:22:01.747", "Id": "23597", "Score": "5", "Tags": [ "c++", "homework", "stack" ], "Title": "Simple static integer stack" }
23597
<p>Any idea how to write this code better."the html is nested tabs" Two selectors and two similar events, in a function would be better or a pattern to reduce lines. <a href="http://jsbin.com/utaxot/3/edit" rel="nofollow">eg .jsbin</a></p> <pre><code>$(function() { var $items = $('#vtab&gt;ul&gt;li'), $items2 = $('#vtab2&gt;ul&gt;li'); $items.mouseover(function() { var index = $items.index($(this)); $items.removeClass('selected'); $(this).addClass('selected'); $('#vtab&gt;div').hide().eq(index).show(); }).eq(1).mouseover(); $items2.mouseover(function() { var index = $items2.index($(this)); $items2.removeClass('selected'); $(this).addClass('selected'); $('#vtab2&gt;div').hide().eq(index).show(); }).eq(1).mouseover(); }); </code></pre>
[]
[ { "body": "<p>Give those <code>#vtab</code>s a class and it should be simple:</p>\n\n<pre><code>$(function() {\n $('.vtab &gt; ul &gt; li').mouseover(function() {\n var $this = $(this);\n\n $this.addClass('selected').siblings().removeClass('selected');\n $this.closest('.vtab').find('div').eq($this.index()).hide().siblings().show();\n }).each(function() {\n $(this).find('&gt; ul &gt; li').eq(1).mouseover();\n });\n});\n</code></pre>\n\n<p>Although I'd try turning it into a plugin at this point.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T02:23:10.983", "Id": "36387", "Score": "0", "body": "I put your code but did not work in [jsbin](http://jsbin.com/utaxot/3/edit)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T01:27:46.877", "Id": "23601", "ParentId": "23600", "Score": "1" } }, { "body": "<p>HTML (add <code>tab-panel</code> class to tab containers):</p>\n\n<pre><code>&lt;div id=\"vtab\" class=\"tab-panel\"&gt;\n\n&lt;div id=\"vtab2\" class=\"tab-panel\"&gt;\n</code></pre>\n\n<p>jQuery:</p>\n\n<pre><code>$(function () {\n\n $(\".tab-panel\").each(function () {\n\n var $currentPanel = $(this),\n $items = $currentPanel.find(\"&gt;ul&gt;li\");\n\n $items.mouseover(function () {\n var $this = $(this),\n index = $items.index($this);\n\n $items.removeClass('selected');\n $this.addClass('selected');\n $currentPanel.find(\"&gt;div\").hide().eq(index).show();\n }).eq(1).mouseover();\n\n });\n\n});\n</code></pre>\n\n<p>jsbin <a href=\"http://jsbin.com/utaxot/7/edit\" rel=\"nofollow\">here</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T02:23:33.747", "Id": "36388", "Score": "0", "body": "I put your code but did not work in [jsbin](http://jsbin.com/utaxot/3/edit)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T02:29:17.697", "Id": "36389", "Score": "0", "body": "Is your html as you want it to be? This bit of code assumes that `#vtab` and `#vtab2` are on the same level but it looks like they are nested, is this correct? \n\nCan you validate your html as well and update the jsbin please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T02:51:05.920", "Id": "36390", "Score": "0", "body": "are nested tabs. lacking specify this in the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T06:36:08.770", "Id": "36393", "Score": "0", "body": "@AURIGADL answer updated" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T02:01:53.860", "Id": "23604", "ParentId": "23600", "Score": "1" } } ]
{ "AcceptedAnswerId": "23604", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T01:21:31.550", "Id": "23600", "Score": "1", "Tags": [ "javascript", "jquery", "design-patterns" ], "Title": "Reduce JavaScript code. Double event, selector into one" }
23600
<p>I'm pretty new to programming in general. I work with MySQL at my job but my knowledge of scripting language is rudimentary at best. I've been learning JavaScript via Codecademy but I got bored and set out on my own. I made this Tic Tac Toe game, which is purely text-based and predictably boring. I was just wondering if anyone has suggestions for improving the code, especially in terms of following programming best practices. Also any advice for turning this into a visual game would be greatly appreciated, especially with HTML5.</p> <pre><code>var board = [0, 0, 0, 0, 0, 0, 0, 0, 0]; var gameOver = true; var check = true; var i = Math.floor(Math.random()*2); var transInput = function(p){ switch(p) { case "A3": return 0; case "B3": return 1; case "C3": return 2; case "A2": return 3; case "B2": return 4; case "C2": return 5; case "A1": return 6; case "B1": return 7; case "C1": return 8; default : console.log("Entry Unknown!"); } }; var transOutput = function(p){ switch(p) { case 1: return "x"; case 10: return "o"; default: return " "; } }; var drawBoard = function(){ console.log("3 " + transOutput(board[0]) + "|" + transOutput(board[1]) + "|" + transOutput(board[2])); console.log(" -----"); console.log("2 " + transOutput(board[3]) + "|" + transOutput(board[4]) + "|" + transOutput(board[5])); console.log(" -----"); console.log("1 " + transOutput(board[6]) + "|" + transOutput(board[7]) + "|" + transOutput(board[8])); console.log(" A B C"); }; drawBoard(); if(i === 0){ console.log("You go first!"); } else {console.log("Computer goes first!");} while (gameOver){ if(i === 0){ var playerMove = transInput(prompt("Your move!")); var check = true; while(check){ if(board[playerMove] === 0){ board[playerMove] = 1; drawBoard(); i = 1; check = false; } else { playerMove = transInput(prompt("Try again.")); } } } else if(i === 1){ console.log("Computer's turn..."); var check = true; while(check){ var compMove = Math.floor(Math.random()*9); if(board[compMove] === 0){ board[compMove] = 10; drawBoard(); i = 0; check = false; } } } var scores = [ board[0] + board[1] + board[2], board[3] + board[4] + board[5], board[6] + board[7] + board[8], board[0] + board[3] + board[6], board[1] + board[4] + board[7], board[2] + board[5] + board[8], board[0] + board[4] + board[8], board[2] + board[4] + board[6] ]; var scoreSum = 0; for(var k = 0; k &lt; board.length; k++){ scoreSum += board[k]; } for(var j = 0; j &lt; scores.length; j++){ if(scores[j] === 3){ console.log("You Win!"); gameOver = false; break; } else if(scores[j] === 30){ console.log("You Lose!"); gameOver = false; break; } } if( gameOver === true &amp;&amp; ( scoreSum === 54 || scoreSum === 45 ) ){ console.log("Draw!"); gameOver = false; } } </code></pre>
[]
[ { "body": "<p>Your code's pretty good actually. I don't see any of the typical beginner's syntactical pitfalls. Kudos! (Though I would prefer <code>gameOver</code>, given its name, to be <em>false</em> while the game's running).</p>\n\n<p>Structurally, there are many ways to build it. I'd probably split things into objects or constructors (aka classes).</p>\n\n<p>For instance, I'd make the board an object with its own methods for marking a square, checking for wins, resetting, etc.. Similarly, the players and the turn-taking could be modelled. It may be overkill for a simple Tic-Tac-Toe game, but the resulting code will be simpler to read (I think). It's basically the same strategy as creating views in MySQL to encapsulate complex/reusable queries.</p>\n\n<p>For instance something like this (not a complete implementation)</p>\n\n<pre><code>// Constructor\nfunction Board() {\n this.squares = new Array(9);\n}\n\n// Prototype functions (i.e. methods)\nBoard.prototype = {\n // get number of marked squares\n occupied: function () {\n var i, l, count = 0;\n for( i = 0, l = this.squares.length ; i &lt; l ; i++ ) {\n count += this.squares[i] ? 1 : 0;\n }\n return count;\n },\n\n // get a row\n row: function (index) {\n var i = index * 3;\n return this.squares.slice(i, 3);\n },\n\n // get a column\n column: function (index) {\n var i, l, column = [];\n for( i = index, l = this.squares.length ; i &lt; l ; i += 3 ) {\n column.push(this.squares[i]);\n }\n return column;\n },\n\n // get diagonal squares\n // index 0: from top-left\n // index 1: from top-right\n diagonal: function (index) {\n var step = index ? 2 : 4,\n squares = [];\n index = index ? 2 : 0;\n while( squares.length &lt; 3 ) {\n squares.push(this.squares[index]);\n index += step;\n }\n return squares;\n }\n};\n</code></pre>\n\n<p><em><strong>Edit:</strong> The above code has some issues. One was a straight-up typo on my part (fixed now). The other is a little more subtle: <code>slice()</code> will ignore undefined elements in an array. So <code>(new Array(3)).slice(0)</code> → <code>[]</code> instead of <code>[undefined, undefined, undefined]</code>. This could obviously cause trouble, as the array will be shorter than one might assume. So the array should either be seeded with values (zeros for instance), or the <code>slice</code>-call should be replaced with something similar to what <code>column()</code> is doing in the above: Looping and pushing values, even if they're undefined.</em></p>\n\n<p>Then you can call <code>new Board()</code> to get a, well, a new board. That board, in turn, provides functions for determining the state of play. (<em>Note that most of these functions can be simplified using array functions like <code>forEach</code> and win-conditions can be checked with <code>reduce</code> or a homemade array-sum function. However, that's an exercise for the reader</em>).</p>\n\n<p>With regard to visual output, you could start by simply \"printing\" to <code>&lt;pre&gt;</code> element on the page instead of the console. A minor step, yes, but just to get the hang of DOM manipulation/interaction. Actually, using your code, I've done that <a href=\"http://jsfiddle.net/cKx3M/\">here</a>. Of course, the real next step is using elements for each square, have them react to clicks, etc..</p>\n\n<p>For that, you could consider simply letting the DOM itself handle the state. I.e. rather than a separate array of values, simply use the elements themselves and their attributes to determine if/how a square is marked.</p>\n\n<p>For now, though, I'll stop here. See if you get something useful out of a more object oriented approach, before moving on the HTML GUI. The reason I'm suggesting this, is that the DOM is object oriented already, so getting the game logic on that footing will likely make creating the GUI easier/simpler. At least you're bound to learn something :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T16:28:53.053", "Id": "36422", "Score": "0", "body": "Thanks for the reply! I'll be going over this all tonight." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T18:07:59.593", "Id": "36433", "Score": "0", "body": "@JasonHamje No problem. Don't forget to click the checkmark (but give it a few days to see if you get more/better answers)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T03:17:35.227", "Id": "36519", "Score": "0", "body": "Thanks again for the help! You've given me a lot to work on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T15:09:59.067", "Id": "36535", "Score": "0", "body": "@JasonHamje No problem, glad I could help" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T09:59:33.327", "Id": "23613", "ParentId": "23606", "Score": "5" } } ]
{ "AcceptedAnswerId": "23613", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T06:02:20.717", "Id": "23606", "Score": "4", "Tags": [ "javascript", "beginner", "game", "tic-tac-toe" ], "Title": "First JavaScript game: Tic Tac Toe" }
23606
<p>I have a situation where I have a fixed point number that I want to convert to and from a floating point number. Specifically it is the <code>SANE_Fixed</code> type from the <a href="http://www.sane-project.org/html/doc011.html#s4.2" rel="nofollow">SANE API</a>. Here is the what the documentation says (I grabbed the bits I think are relavant):</p> <blockquote> <p>SANE_Fixed is used for variables that can take fixed point values in the range -32768 to 32767.9999 with a resolution of 1/65535.</p> <pre><code>#define SANE_FIXED_SCALE_SHIFT 16 typedef SANE_Word SANE_Fixed; </code></pre> <p>The macro SANE_FIXED_SCALE_SHIFT gives the location of the fixed binary point. This standard defines that value to be 16, which yields a resolution of 1/65536. </p> <p>SANE_Word: A word is encoded as 4 bytes (32 bits). The bytes are ordered from most-significant to least-significant byte (big-endian byte-order).</p> </blockquote> <p>So, over the wire I get 4 bytes which I convert into a .Net <code>int</code> like this (you can guess what <code>GetByte</code> and <code>SendByte</code> do):</p> <pre><code>public int GetWord() { int value = 0; value += (GetByte() &lt;&lt; 24); value += (GetByte() &lt;&lt; 16); value += (GetByte() &lt;&lt; 8); value += (GetByte() &lt;&lt; 0); return value; } </code></pre> <p>Then I want to convert that <code>int</code> into a floating point number (I went for <code>decimal</code>) like this:</p> <pre><code>public decimal ToFloating(int source) { decimal value = source / ((decimal)(1 &lt;&lt; 16)); return value; } </code></pre> <p>And I will also need to go back the other way so I would convert to fixed like this:</p> <pre><code>public int ToFixed(decimal source) { decimal value = source * ((decimal)(1 &lt;&lt; 16)); return (int)value; } </code></pre> <p>And then convert to four bytes like this to send it like so:</p> <pre><code>public void SendWord(int word) { SendByte((word &gt;&gt; 24) &amp; 0xff); SendByte((word &gt;&gt; 16) &amp; 0xff); SendByte((word &gt;&gt; 8) &amp; 0xff); SendByte((word &gt;&gt; 0) &amp; 0xff); } </code></pre> <p>So, here is my question:</p> <p>This seems a pretty simplistic implementation to me and I read lots of stuff on the internet about creating custom fixed point classes and whatnot but, given the constraints of my scenario, is this a safe approach to take? Could I lose precision and is the maths correct?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T09:17:41.357", "Id": "36396", "Score": "0", "body": "Have you tried it? Does it seem to work?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T10:13:26.390", "Id": "36401", "Score": "0", "body": "Yes, I have tried it and it does seem to work" } ]
[ { "body": "<p>If the <code>SANE_Fixed</code> type has a constantly fixed precision of 1/65536, that means it always stores the fractional part of the number as a 16 bit (two-byte) unsigned integer (hence the <code>SANE_FIXED_SCALE_SHIFT</code> of 16 bits). Since the whole number portion of the value can range from -32768 to 32767, that means that the whole part of the number is represented with a 16 bit signed integer (making the type use a total of 4 bytes).</p>\n\n<p>The <code>decimal</code> type in .NET, while it is a floating point type, it is far more precise that the traditional <code>float</code> type. It stores a 96 bit integer (plus an additional bit for the sign). It then stores the position of the decimal point as a 5-bit integer, which allows the decimal point to be located after any digit in the 96-bit integer value. As such, the larger the value gets, the lower the fractional precision becomes. </p>\n\n<p>In other words, the <code>decimal</code> type can store a value up to 79,228,162,514,264,337,593,543,950,335 (29 digits). If it does store a 29 digit number, however, it will be unable to store any fractional value with that. It will only store the whole part of the number. If, however, it is only storing a single digit value, the fractional part can be up to 28 digits long (e.g. 0.0000000000000000000000000001).</p>\n\n<p>Bearing all of that in mind, if the maximum whole number that the <code>SANE_Fixed</code> type can store is 32767 (a five digit number), when cast to a <code>decimal</code> type, that leaves 24 digits of precision (e.g. 1/10^24) in the fractional part of the number. That is still <em>far</em> more precise than the 1/65536 precision provided by the <code>SANE_Fixed</code> type. </p>\n\n<p>Therefore, you can be confident that the <code>decimal</code> type will accurately retain the precise value. Obviously, when casting from a <code>decimal</code> back into a <code>SANE_Fixed</code> type, you will lose precision, but since the value came from that type in the first place, your values are safe.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T14:47:43.217", "Id": "23621", "ParentId": "23608", "Score": "3" } } ]
{ "AcceptedAnswerId": "23621", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T07:03:52.667", "Id": "23608", "Score": "2", "Tags": [ "c#", ".net" ], "Title": "Will this converstion to/from fixed point cause me to lose precision?" }
23608
<p>Please review my following code for DAO layer.</p> <pre><code>public List&lt;Channel&gt; getListOfChannels() throws DataAccessException { // will have the channel in form of List // to hold the channels list List&lt;Channel&gt; listChannels = null; Connection conn = null; Statement statement = null; ResultSet resultSet = null; try { // get the db connection from pool // this is DBCP lib on top doing this conn = ManageConnections.getConnection(); statement = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); final String QUERY_STRING = "Select * from channel"; resultSet = statement.executeQuery(QUERY_STRING); // is this good practice to put this ? if (isResultSetEmptyOrNull(resultSet)) { throw new DataAccessException( "No more data of Channels found from db"); } Channel channel = null; listChannels = new ArrayList&lt;Channel&gt;(); while (resultSet.next()) { // get the object from the result set and listChannels.add(channel); } log.debug("getListOfChannels Got the list of channels " + listChannels); } catch (SQLException ex) { throw new DataAccessException(SQL_EXCEPTION + ex, ex); } catch (DBConnectionException ex) { // re thrown, no logging throw new DataAccessException(ex); } catch (Exception ex) { // Generic exception thrown , now throw Custom Exceptionn throw new DataAccessException(GENERIC_EXCEPTION + ex, ex); } finally { try { if (conn != null) { // this is DBCP lib on top doing this ManageConnections.close(conn); } if (statement != null) { statement.close(); } if (resultSet != null) { resultSet.close(); } } catch (SQLException ex) { throw new DataAccessException( "Exception while closing resource" + ex, ex); } catch (DBConnectionException ex) { throw new DataAccessException( "Exception while closing resource" + ex, ex); } } return listChannels; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T11:12:01.733", "Id": "36404", "Score": "1", "body": "Even if this code was perfect, what is your plan for avoiding repeating it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T14:47:54.327", "Id": "36411", "Score": "0", "body": "Do you have Java 7? Then an ARM block would be helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:16:49.093", "Id": "36492", "Score": "0", "body": "@abuzittingillifirca didnt get you ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:17:40.057", "Id": "36494", "Score": "0", "body": "@Landei Nope! we didnt migrated to Java7 yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T07:24:37.567", "Id": "36577", "Score": "1", "body": "@ajduke Opening/closing resources (connections, transactions, statements, resultsets) and exception handling etc, which are almost all the code you've provided, are common to all data access methods; and *somehow* should be refactored out. All you should need to write in a dao implementation is something like `em.createQuery(\"select c from Channel c\").toResultList()`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T07:42:05.747", "Id": "36578", "Score": "0", "body": "@abuzittingillifirca yes, true! Will refactored it out. Thanks!" } ]
[ { "body": "<p>There are a couple of improvements that can be made here:</p>\n\n<ul>\n<li>a) your QUERY_STRING is magic string. Move it to a different place,\nbecause it make your code difficult to maintain </li>\n<li>user linked list\ninstead of array list. It has O(1) on insertion in worst case,\nwhereas array list has O(n) </li>\n<li>do not rethrow exceptions in finally\nblock. You will lose all details of your original exception </li>\n<li>every time when you concatenate strings with \"+\" you make too many\noperations with memory, because strings are immutable. use *.format\ninstead</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:19:03.097", "Id": "36495", "Score": "0", "body": "can you explain more on \"why not to rethrow in finally block\" ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T21:47:07.803", "Id": "36726", "Score": "1", "body": "Can you explain more on \"why not to rethrow in finally block\" ? Your finally will get executed no matter what. Any SQL Exception thrown in finally block will discard exceptions thrown before." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T10:37:09.363", "Id": "23614", "ParentId": "23609", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T07:09:35.577", "Id": "23609", "Score": "3", "Tags": [ "java", "database" ], "Title": "DAO Layer Code Review" }
23609
<p>This is my first Java multi-threading code. It is part of an Android application that is a client to a webpage that serves books. Each page of the book is in a separate PDF, and the Book class represents the entire book, and has functions to download and render individual pages. This class is supposed to make things running smoother by caching some pages ahead and behind the currently viewed page.</p> <p>I am primarily interested in making sure this code is thread safe, but would be very happy to hear any thoughts and suggestions about improving it in any way.</p> <pre><code>import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import android.util.Log; enum PageStatus { PENDING, DOWNLOADED, RENDERED } public class PageCacheManager { private static final String TAG = "PageCacheManager"; private static final int DEFAULT_CACHE_SIZE_AHEAD = 5; private static final int DEFAULT_CACHE_SIZE_BEHIND = 3; private final Book mBook; private volatile PageCacheThread mCacheThread; private volatile int mLastPageRequested; private List &lt;PageStatus&gt; mPagesStatus; // For signaling that requested page is ready private ReentrantLock mLock = new ReentrantLock(); private final Condition mPageReadyCondition = mLock.newCondition(); public PageCacheManager(HebrewBook book, int page) { Log.i(TAG, "PageCacheManager created. BookID = " + book.getBookID()); mBook = book; mLastPageRequested = page; ArrayList&lt;PageStatus&gt; list = new ArrayList&lt;PageStatus&gt;(); for(int i = 0; i &lt; mBook.getNumPages() + 1; i++) { list.add(PageStatus.PENDING); } mPagesStatus = Collections.synchronizedList(list); // Start the background thread mCacheThread = new PageCacheThread(); mCacheThread.start(); } public PageCacheManager(HebrewBook book) { this(book, 0); } public File getPage(int page) { Log.i(TAG, "getPage(): waiting for page " + page); if(page &lt; 1 || page &gt; mBook.getNumPages()) { Log.e(TAG, "Requesting invalid page number"); return null; } mLastPageRequested = page; // Make sure the background thread is running if(! mCacheThread.isAlive()) { mCacheThread = new PageCacheThread(); mCacheThread.start(); } // Wait for file to be rendered Log.i(TAG, "Waiting for page to be rendered"); mLock.lock(); try { while(mPagesStatus.get(page) != PageStatus.RENDERED) { mPageReadyCondition.await(); } } catch (InterruptedException e) { } finally { mLock.unlock(); } Log.i(TAG, "Recieved signal that page was rendered"); // Find the file (asking it to be rendered when it already has, will just find it in the cache) File file = null; try { file = mBook.renderPage(page); } catch (Exception e) { Log.e(TAG, "Error: " + e.toString()); } Log.i(TAG, "getPage, got page at " + file.getAbsolutePath()); return file; } private int getNextPageToDownload() { // Is there a page we have requested but hasn't been done yet? if((mLastPageRequested &gt; 0) &amp;&amp; (mPagesStatus.get(mLastPageRequested) == PageStatus.PENDING)) { return mLastPageRequested; } // Check ahead if any pages need to be cached int checkAhead = (mLastPageRequested + 1 + DEFAULT_CACHE_SIZE_AHEAD) &lt;= mBook.getNumPages() ? mLastPageRequested + 1 + DEFAULT_CACHE_SIZE_AHEAD : mBook.getNumPages(); for(int i = mLastPageRequested + 1; i &lt; checkAhead; i++) { if(mPagesStatus.get(i) == PageStatus.PENDING) { return i; } } // Check behind if any pages need to be cached int checkBehind = (mLastPageRequested - 1 - DEFAULT_CACHE_SIZE_BEHIND) &gt; 0 ? mLastPageRequested - 1 - DEFAULT_CACHE_SIZE_BEHIND : 1; for(int i = mLastPageRequested; i &gt; checkBehind; i--) { if(mPagesStatus.get(i) == PageStatus.PENDING) { return i; } } // Cache is up to date return 0; } class PageCacheThread extends Thread { @Override public void run() { Log.i(TAG, "PageCacheThread starting"); int page = getNextPageToDownload(); while(page != 0) { // Download and render the file try { Log.i(TAG, "Downloading page " + page); File file = mBook.getPage(page); mPagesStatus.set(page, PageStatus.DOWNLOADED); Log.i(TAG, "Download complete for page " + page + ". Now rendering"); Thread.yield(); mBook.renderPage(file); Log.i(TAG, "Render complete for page " + page); mPagesStatus.set(page, PageStatus.RENDERED); } catch (Exception e) { // TODO: Better error handling Log.e(TAG, "Error in PageCacheThread: " + e.toString()); } // If we have rendered the requested page, notify other threads if(page == mLastPageRequested) { Log.i(TAG, "Signalling that page is ready"); mLock.lock(); mPageReadyCondition.signalAll(); mLock.unlock(); } page = getNextPageToDownload(); } // TODO: investigate possible performance benefits of rendering in separate thread while downloading next page } } } </code></pre>
[]
[ { "body": "<p>Here are a few comments:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/5623285/java-why-not-to-start-a-thread-in-the-constructor-how-to-terminate\">you should not start a thread from the constructor</a> - for example, the thread could see <code>mPagesStatus</code> as null and throw a NullPointerException. So you should provide an <code>init</code> method for example, that must be called by the client.</li>\n<li>I'm not a big fan of Hungarian notation (prefixing all instance variables with <code>m</code>) - my IDE already shows me what I need to know with a colour scheme.</li>\n<li>It is good practice to code to interface, for example: <code>ArrayList&lt;PageStatus&gt; list = new ArrayList&lt;PageStatus&gt;();</code> could be <code>List&lt;PageStatus&gt; list = new ArrayList&lt;PageStatus&gt;();</code></li>\n<li><code>mPagesStatus</code> is only assigned once, I would make it <code>final</code></li>\n<li>same thing for the lock: <code>private final ReentrantLock mLock = new ReentrantLock();</code></li>\n<li>your <code>PageCacheThread</code> class is a <code>Runnable</code> really - I would make it so</li>\n<li>I would use an ExecutorService to manage the threads instead of manually starting them</li>\n<li>You don't really use the extra features of <code>Condition</code>, so I would use a simple wait/notifyAll mechanism and avoid the complexity of locks (for example, you don't always unlock your lock in a finally block, which can lead to deadlock)</li>\n<li>There seems to be an issue with your signalling code - <code>mPageReadyCondition.signalAll();</code> is only called if <code>page == mLastPageRequested</code> - if two threads call <code>getPage</code> concurrently, you might fail to wake the conditions that are waiting. I would simply remove the <code>if</code> and signal every time a page is loaded</li>\n<li>For similar reasons, your <code>getNextPageToDownload</code> could miss an update if the <code>getPage</code> is called by two threads concurrently</li>\n<li>I would use a <code>BlockingQueue</code> mechanism for the pages to update, and put the page numbers in the queue from the <code>getPage</code> method and <code>take</code> from the queue in the <code>Runnable</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T08:16:21.293", "Id": "23725", "ParentId": "23610", "Score": "7" } } ]
{ "AcceptedAnswerId": "23725", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T08:28:03.157", "Id": "23610", "Score": "4", "Tags": [ "java", "multithreading", "android", "thread-safety", "cache" ], "Title": "Java thread safety and caching techniques" }
23610
<p>After some 'digging' into the dark corners of legacy code I've found class, which handles INI files. It does reading and writing to the file, but I haven't found any exception handling logic. What kind of potential problems, if any, can you detect and what is your suggestion/advise for improving the code, based on these three C++ code snippets:</p> <p>Constructor</p> <pre><code>IniValue::IniValue(const char* FileName, const char* Section, const char* Entry, int sz, PersistMediumEnum medium_, int iniprofileId_) :filename(NULL) ,section(new char[strlen(Section)+1]) ,entry(new char[strlen(Entry)+1]) ,buffer(new char[sz]) ,bufsiz(sz) { if (FileName == NULL) { FileName = "somefile.ini"; } // 'GetFullInifileName' calls windows functions 'GetEnvironmentVariable', 'CreateDirectory', 'CopyFile', 'DeleteFile' std::string fullname = GetFullInifileName(FileName); filename = new char[fullname.length()+1]; strcpy(filename, fullname.c_str()); strcpy(section, Section); strcpy(entry, Entry); buffer[0] = 0; } </code></pre> <p>Some function, which reads values from the file:</p> <pre><code>void IniValue::TheGetProfileString() { char* defstr = new char[bufsiz]; strncpy(defstr, buffer, bufsiz); IniPersistIF* inf = IniPersistIF::get(medium); //calls windows 'GetPrivateProfileString' inf-&gt;Read(section, entry, defstr, buffer, bufsiz, filename, iniprofileId); delete [] defstr; } </code></pre> <p>Destructor</p> <pre><code>IniValue::~IniValue() { IniValue* thys = this; assert(section[0] != '\0'); assert(filename[0] != '\0'); IniPersistIF* inf = IniPersistIF::get(medium); assert(inf != NULL); assert(section[0] != '\0'); assert(filename[0] != '\0'); // Calls Windows 'WritePrivateProfileString' function inf-&gt;Write(section, entry, buffer, filename, iniprofileId, defaultval, bModified); delete [] buffer; delete [] entry; delete [] section; delete [] filename; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T15:05:13.680", "Id": "36413", "Score": "1", "body": "If it is not broken then don't try and fix it. But feel free to add unit tests." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T16:16:32.750", "Id": "36419", "Score": "0", "body": "constructor does not initialize `defaultval`, but the destructor frees it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T16:17:21.670", "Id": "36420", "Score": "0", "body": "If the code in `IniValue::TheGetProfileString()` between `new` and `delete` can throw an exception - you have a memleak (`defstr`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T07:05:58.543", "Id": "36452", "Score": "0", "body": "@fork thanks for correction. 'defaultval' was accidental copy-paste mistake, I've just removed it from the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T07:19:52.140", "Id": "36453", "Score": "0", "body": "@Loki, sure, I'll have your comment in mind. My intension is to understand what C++ software engineers will do differently, than they did 20 years ego." } ]
[ { "body": "<p>This was posted just a short while ago on StackOverflow.com</p>\n\n<p>Firstly, if this is legacy code that has existed in production for a long time, then even if you can make it semantically better, you have to really weigh up the gains against the losses. Changing code is a cost, can introduce bugs even when the new code appears to be a lot better, and has to be justified. That the existing code uses a lot of arrays does not mean it has any bugs, nor would the \"improvements\" give you better performance in any way.</p>\n\n<p>However, on the basis of giving this code a review I will do so.</p>\n\n<p>Basically, start off by getting rid of all the arrays and calls to new[] and delete[] and use std::string (which is used there in one place so it is obviously known to the programmer).</p>\n\n<p>Ensure your IniPersistInf class is const-correct so takes if it takes a string that it only reads, it uses <code>const char *</code> or <code>const std::string &amp;</code> rather than <code>char *</code>.</p>\n\n<p><code>buffer</code> in <code>IniValue</code> appears to be for writing into, so for this one you might use <code>std::vector&lt;char&gt;</code>. In such a case, to get the pointer out of it, use <code>&amp;buffer[0]</code> when you pass it to the <code>IniPersistIf</code> methods.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T12:13:43.677", "Id": "36407", "Score": "0", "body": "Can those Windows functions: WritePrivateProfileString, GetPrivateProfileString, CreateDirectory, etc. throw an exception?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-17T15:24:44.750", "Id": "62297", "Score": "0", "body": "If they are C functions they cannot throw as there are no exceptions in C." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T11:13:35.663", "Id": "23617", "ParentId": "23615", "Score": "2" } }, { "body": "<p>All those functions: 'GetFullInifileName', 'Read' and 'Write' should provide no-throw guarantee. otherwise it will lead to memory leak and even results to undefined behavoir if exception is thrown from the destructor. Right now these functions refferring to Windows API C functions like GetPrivateProfileString, WritePrivateProfileString, etc. and in C there is no such exception idiom. To some extent the 'IniValue' class is 'safe', but do not provide any error handling mechanism; typically C can manage such situation with last error number returned ('errno.h'). IniValue class designer made a 'Write' function call in destructor! There is no way to return information to the user of IniValue class about success or failure of 'write' operation (remmember, do not throw exception from destructor.) By my opinion IniValue class is dumb, brittle and still in production as legacy code. For how long?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T08:21:03.837", "Id": "23689", "ParentId": "23615", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T11:01:33.923", "Id": "23615", "Score": "3", "Tags": [ "c++", "c++03" ], "Title": "legacy code and exception handling" }
23615
<p>Well, i'm starting a function to 'mess' with a image gallery, i made an <a href="http://jsfiddle.net/yVnTR/17/" rel="nofollow"><strong>example</strong></a></p> <p>i wanna know if the way i'm doing is realy the BEST way, the function work perfect, but i fill that can be better, something more dynamic, like never flow over the edge, and mess with the number of images that user places inside the gallery, now i set as index 0 to 5.</p> <p>Is there any easy way to improve this little function, make the code faster/smaller then that?</p> <p>Any tips, be my guest.</p> <hr> <h2>jQuery</h2> <pre><code>$("#ran").click(function () { mess(1, $(".holder img")); }); function mess(type, gallery) { var getNumImg = gallery.length, winWidht = $("#galeria").width(), winheight = $("#galeria").height(), imgHeight = $("#content-wrapper img").height(), ftBottom = winheight - ($(".stats").height() + imgHeight + 150); $(".holder").width(winWidht / 2); gallery.each(function (index) { var randonLeft, randonRight, randonTop, randonTransform, maxIndex; var leftFt, topFt, transFt; var sign = "- "; var signRes = sign.charAt(Math.floor(Math.random() * sign.length)); if (type == 1) { if (index == 0) { maxIndex = getNumImg; transFt = { "from": 1, "to": 30 } topFt = { "from": 1, "to": ftBottom } } else if (index == 1) { leftFt = { "from": 30, "to": 40 } transFt = { "from": 1, "to": 30 } topFt = { "from": 1, "to": ftBottom } } else if (index == 2) { leftFt = { "from": -30, "to": -40 } transFt = { "from": 1, "to": 30 } topFt = { "from": 1, "to": ftBottom } } else if (index == 3) { leftFt = { "from": -30, "to": -40 } transFt = { "from": 1, "to": 30 } topFt = { "from": 1, "to": ftBottom } } else if (index == 4) { transFt = { "from": 1, "to": 30 } topFt = { "from": 1, "to": ftBottom } } else if (index == 5) { leftFt = { "from": 40, "to": 50 } transFt = { "from": 1, "to": 30 } topFt = { "from": 1, "to": ftBottom } } } if (typeof leftFt != "undefined") { randonLeft = Math.floor(Math.random() * leftFt.to) + leftFt.from; } if (typeof transFt != "undefined") { randonTransform = Math.floor(Math.random() * transFt.to) + transFt.from; } if (typeof topFt != "undefined") { randonTop = Math.floor(Math.random() * topFt.to) + topFt.from; } // make it happen $(this).css({ zIndex: maxIndex, left: randonLeft, top: randonTop, transform: "rotate(" + signRes + randonTransform + "deg)" }); }); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T13:13:22.027", "Id": "36409", "Score": "0", "body": "Example was not working, updated right now" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T15:35:01.193", "Id": "36417", "Score": "0", "body": "Quer uma resposta em Port?" } ]
[ { "body": "<p>I think your code is good and more importantly it works. The main thing I would change is that huge if else statement. You repeat yourself a lot there. Here's another way you could do it:</p>\n\n<p>Also here's your edited <strong><a href=\"http://jsfiddle.net/yVnTR/18/\" rel=\"nofollow\">fiddle</a></strong>.</p>\n\n<p>Acho que o seu trabalho está bom e mais importante ele funciona. A parte que chama minha atenção é o if/else enorme. Você se repete muito ali. Outra forma que você pode fazer é assim:</p>\n\n<pre><code>if(type === 1){\n //You had these every time, so you can declare them once here.\n //Você declara isso em todos os casos, mas só precisa fazer uma vez aqui.\n topFt = { \"from\" : 1, \"to\" : ftBottom };\n transFt = { \"from\" : 1, \"to\" : 30 };\n\n //I Took out all the repetitions and left the cases where we actually change something.\n //Tirei todos os casos em que você estava se repetindo e deixei somente os que realmente estão mudando algo.\n switch(index){ \n case 0:\n maxIndex = getNumImg;\n break;\n case 1:\n leftFt = { \"from\" : 30, \"to\" : 40 }\n break;\n case 2: //If index === 2\n case 3: //OR if index === 3\n leftFt = { \"from\" : -30, \"to\" : -40 }\n break;\n case 5:\n leftFt = { \"from\" : 40, \"to\" : 50 }\n break;\n //Add more cases if you want/need to.\n //Adicione mais casos aqui se precisar.\n default:\n break;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T16:36:18.487", "Id": "23624", "ParentId": "23619", "Score": "2" } } ]
{ "AcceptedAnswerId": "23624", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T13:07:01.557", "Id": "23619", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Dynamically mess images inside a container" }
23619
<p>Can someone help in making this clock code more modular so I will be able to use it in other bigger projects for example: turn into a c function. Here is the code: </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; #include &lt;windows.h&gt; COORD coord = {0, 0}; void gotoxy (int x, int y) { coord.X = x; coord.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); } void delay(unsigned int mseconds) { clock_t goal = mseconds + clock(); while (goal &gt; clock()); } void showClock(int x_1, int x_2, int x_3,int y){ long i = 0; clock_t now = 0; int interval = 1; int elapsed = 0; int min=0,MIN=0,hrs=0,sec=0; int d=0,f=0; now = clock(); for(i = 0L ; ; i++){ elapsed = (clock()-now)/CLOCKS_PER_SEC; if(elapsed&gt;=interval){ interval += 1; if(elapsed%60==0){ min=elapsed/60; d=60*min; if(min%60==0){ hrs=min/60; f=60*hrs; } } sec=elapsed-d; MIN=min-f; if(hrs&lt;10){ gotoxy(x_1,y);printf("0%d",hrs); }else{ gotoxy(x_1,y);printf(":%d",hrs); } if(min&lt;10){ gotoxy(x_2,y);printf(":0%d",MIN); }else{ gotoxy(x_2,y);printf(":%2d",MIN); } if(sec&lt;10){ gotoxy(x_3,y);printf(":0%d",sec); }else{ gotoxy(x_3,y);printf(":%2d",sec); } } } } int main() { showClock(2,4,7,4); return 0; } </code></pre>
[]
[ { "body": "<p>General comments</p>\n\n<p>You should read the manual pages on <code>time()</code>, which gives you the time in seconds since 1970, library functions such as <code>localtime</code>, <code>strftime</code> and <code>ctime</code> that can be used to present time values and the <code>sleep()</code> function, which sleeps the process for a specified\n number of seconds.</p>\n\n<p>Also:</p>\n\n<ul>\n<li><p>variables and structure fields are normally not all-uppercase (X,Y,MIN)</p></li>\n<li><p>put a single definition or expression on each line</p></li>\n<li><p>leave a blank line between functions.</p></li>\n<li><p><code>printf</code> has many formatting options. Of relevance here is the \"%02d\"\nformat string which prints an integer in 2 places, zero-padded if necessary</p>\n\n<p>So for 1, it prints '01' and for 10 it prints '10'.</p></li>\n<li><p>I prefer to see a space after <code>while</code> and <code>if</code> etc. and spaces around\noperators (<code>!=</code>, <code>%</code>, <code>/</code> etc)</p></li>\n<li><p>make all functions <code>static</code> where possible (in this program, all except\n<code>main</code>)</p></li>\n</ul>\n\n<p><hr>\n- your function <code>delay</code> is not a good way of delaying, as it ties up the processor. Better use <code>sleep</code></p>\n\n<h2>Function <code>showClock</code></h2>\n\n<ul>\n<li><p>I presume you wanted to call <code>delay</code>, but you didn't. This function loops\ncontinually using 100% of CPU time. Better would be to use <code>sleep()</code> which\nlets other processes run. So sleep(1) would sleep for 1 second.</p></li>\n<li><p>using <code>time()</code> would be better than <code>clock()</code>, as you want intervals in\nseconds</p></li>\n<li><p>the single printf format \"%02d:%02d:%02d\" does what you want without pasing\nthree x-coordinates to the function</p></li>\n<li><p>most of the rest is unnecessary if you use <code>sleep</code> and <code>time</code> and the other library functions to present the time interval</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T15:55:34.067", "Id": "36418", "Score": "0", "body": "Note that sleep is not ideal for more precise timing, because the thread may sleep *longer* than your delay. If you want something to happen after a specific amount of time, you usually need OS-specific code (e.g., [Waitable Timer Objects](http://msdn.microsoft.com/en-us/library/windows/desktop/ms687012.aspx) in Windows)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T15:26:08.377", "Id": "23622", "ParentId": "23620", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T13:46:41.087", "Id": "23620", "Score": "3", "Tags": [ "c", "windows" ], "Title": "Aid in making a clock code more modular" }
23620
<pre><code>#!/usr/bin/env python import os, sys variable = sys.argv def enVar(variable): """ This function returns all the environment variable set on the machine or in active project. if environment variable name is passed to the enVar function it returns its values. """ nVar = len(sys.argv)-1 if len(variable) == 1: # if user entered no environment variable name for index, each in enumerate(sorted(os.environ.iteritems())): print index, each else: # if user entered one or more than one environment variable name for x in range(nVar): x+=1 if os.environ.get(variable[x].upper()): # convertes to upper if user mistakenly enters lowecase print "%s : %s" % (variable[x].upper(), os.environ.get(variable[x].upper())) else: print 'Make sure the Environment variable "%s" exists or spelled correctly.' % variable[x] enVar(variable) </code></pre> <p>i run the above file as <code>show.py</code> is their a better way to do it ?</p>
[]
[ { "body": "<p>Some notes:</p>\n\n<ul>\n<li>Indent with 4 spaces (<a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>)</li>\n<li>Use <code>underscore_names</code> for function and variables.</li>\n<li>Use meaningful names for functions (specially) and variables.</li>\n<li>Be concise in docstrings.</li>\n<li>Don't write <code>for index in range(iterable):</code> but <code>for element in iterable:</code>.</li>\n<li>Don't write <code>variable = sys.argv</code> in the middle of the code, use it directly as an argument.</li>\n<li>Use an import for each module.</li>\n</ul>\n\n<p>I'd write (Python 3.0):</p>\n\n<pre><code>import sys\nimport os\n\ndef print_environment_variables(variables):\n \"\"\"Print environment variables (all if variables list is empty).\"\"\"\n if not variables:\n for index, (variable, value) in enumerate(sorted(os.environ.items())):\n print(\"{0}: {1}\".format(variable, value))\n else: \n for variable in variables:\n value = os.environ.get(variable)\n if value:\n print(\"{0}: {1}\".format(variable, value))\n else:\n print(\"Variable does not exist: {0}\".format(variable))\n\nprint_environment_variables(sys.argv[1:])\n</code></pre>\n\n<p>But if you asked me, I would simplify the function without second thoughts, functions are more useful when they are homogeneous (that's it, they return similar outputs for the different scenarios):</p>\n\n<pre><code>def print_environment_variables(variables):\n \"\"\"Print environment variables (all if variables list is empty).\"\"\"\n variables_to_show = variables or sorted(os.environ.keys())\n for index, variable in enumerate(variables_to_show):\n value = os.environ.get(variable) or \"[variable does not exist]\"\n print(\"{0}: {1}={2}\".format(index, variable, value))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T18:46:50.090", "Id": "23628", "ParentId": "23623", "Score": "3" } } ]
{ "AcceptedAnswerId": "23628", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T15:29:46.960", "Id": "23623", "Score": "6", "Tags": [ "python" ], "Title": "this code returns environment varibles or passed enverionment variable with values" }
23623
<p>I'd like to know if I'm doing profile configuration in the wrong place or in the wrong way.</p> <p>I'm following the Onion Architecture, so that restricts the direction of my dependencies towards the center.</p> <p><img src="https://i.stack.imgur.com/ECZcG.png" alt="Onion Architecture"></p> <h2>Core</h2> <p>My domain model and <code>AutoMapper</code> facade:</p> <pre><code>namespace Core.Domain { public class MyModel { // model stuff } } namespace Core.Services { public interface IMapper { object Map(object source, Type sourceType, Type destinationType); } } </code></pre> <h2>Infrastructure</h2> <p>AutoMapper facade implementation:</p> <pre><code>namespace Infrastructure.Mapping { public class Mapper : IMapper { private readonly IMappingEngine _mappingEngine; public Mapper(IMappingEngine mappingEngine) { _mappingEngine = mappingEngine; } public object Map(object source, Type sourceType, Type destinationType) { return _mappingEngine.Map(source, sourceType, destinationType); } } } </code></pre> <h2>UI</h2> <p>This is my controller and view model. I'm using the <code>AutoMapper</code> via a filter, following <a href="http://lostechies.com/jimmybogard/2009/06/30/how-we-do-mvc-view-models/" rel="noreferrer">this example</a>.</p> <pre><code>namespace UI.Controllers { public class HomeController : Controller { [AutoMap(typeof(MyModel), typeof(MyViewModel))] public ActionResult Index() { var myItem = _myRepository.GetById(0); return View(myItem); } } } namespace UI.ViewModels { public class MyViewModel { // view stuff } } </code></pre> <h2>Dependency Resolution</h2> <p>This is where I have my doubts:</p> <pre><code>namespace DependencyResolution { public class MappingModule : NinjectModule { public override void Load() { Mapper.Initialize(cfg =&gt; cfg.AddProfile(new MyProfile())); Bind&lt;IMappingEngine&gt;().ToMethod(ctx =&gt; Mapper.Engine); Bind&lt;IMapper&gt;().To&lt;Mapping.Mapper&gt;(); Kernel.BindFilter&lt;AutoMapFilter&gt;(FilterScope.Controller, 0) .WhenActionMethodHas&lt;AutoMapAttribute&gt;() .WithConstructorArgumentFromActionAttribute&lt;AutoMapAttribute&gt;("sourceType", att =&gt; att.SourceType) .WithConstructorArgumentFromActionAttribute&lt;AutoMapAttribute&gt;("destType", att =&gt; att.DestType); } } public class MyProfile : Profile { protected override void Configure() { Mapper.CreateMap&lt;MyModel, MyViewModel&gt;().ForMember(...); } } } </code></pre> <h2>Questions</h2> <ol> <li>Is the way I bind to <code>AutoMapper</code> wrong? </li> <li>Is this the wrong place for the profile (keep in mind the dependency restriction)?</li> </ol> <p>In the ideal world I would have placed</p> <pre><code>Mapper.CreateMap&lt;MyModel, MyViewModel&gt;().ForMember(...) </code></pre> <p>in Global.asax, but how do I expose <code>CreateMap</code> without referencing <code>AutoMapper</code>?</p> <p>Is there anything else you have noticed?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-29T19:22:13.913", "Id": "53606", "Score": "0", "body": "I assume that this code works the way you intended it to work. and it sounds like you want to create a session variable to hold your Mapper, is that what you are asking there about the `Mapper.CreateMap<MyModel, MyViewModel>().ForMember(...)`???" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-02T13:18:43.573", "Id": "59853", "Score": "0", "body": "How did you solve this eventually?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T21:30:44.783", "Id": "78206", "Score": "0", "body": "Its been a while, but let me try to recap. I ended up using the above. However I had to use post build scripts to move assemblies to the MVC project which wasn't too bad. But the MVC publish functionallity doesn't run custom scripts, so that was a major pain. I had to deploy manually. So these days I just put AutoMapper and Ninject inside the MVC project, they're still easy to switch out if needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-04T12:26:50.930", "Id": "98691", "Score": "0", "body": "Yes - this is the correct way to do this...don't take my word for it though, read what the architect of Onion Architecture had to say on a very similar question... [Jeffrey Palermo reply](http://stackoverflow.com/questions/2336273/onion-archicecture-dependencies-in-the-same-layer-infrastructure-and-web-commun)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-05T08:39:45.160", "Id": "106302", "Score": "0", "body": "@Snæbjørn Just to comment. From what I've read a purist way would be to have a Bootstrapper layer which does the wiring for you and hooks into MVC startup modules. Hence the WebApp would only reference the Core which would contain your interfaces.." } ]
[ { "body": "<p>What is the purpose of the <code>IMapper</code> interface and <code>Mapper</code> class? It looks to me that they are just wrapping the <code>IMappingEngine</code> interface and <code>MappingEngine</code> class. While this is a good method when you have a third party class that doesn't have an interface, I think it is overkill here. Why don't you just use the <code>IMappingEngine</code> where you need that functionality?</p>\n\n<p>If you are going to keep your <code>Mapper</code> class, I would rename it, having two <code>Mapper</code> classes is confusing.</p>\n\n<p>As for where it is, I don't have a problem with doing it this way. All the wire-up is done in one place, and its easy to find and add to as needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-20T21:35:14.553", "Id": "78207", "Score": "5", "body": "I did it because I'm not aware of a way to extract the IMappingEngine from the assembly. So I would have to reference AutoMapper which is what I wanted to avoid. So IMapper should be a generic mapping interface which any mapping library could build an adapter for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T21:03:06.620", "Id": "435905", "Score": "0", "body": "I think this is over eagerly trying to avoid dependencies in code. Certain aspects (mapping, logging, ...) should not require a custom wrapper library. They provide sufficient layers and maturity to introspect and extend them." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-04T21:47:32.237", "Id": "43453", "ParentId": "23625", "Score": "5" } } ]
{ "AcceptedAnswerId": "43453", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T16:42:37.220", "Id": "23625", "Score": "20", "Tags": [ "c#", "dependency-injection", "asp.net-mvc-4" ], "Title": "Injecting AutoMapper profiles" }
23625
<pre><code>(defn merge [pred left right] (loop [v [] l left r right] ; v is a vector, so conj will append to the end (if (and (seq l) (seq r)) ; if both left and right are not empty (if (pred (first l) (first r)) (recur (conj v (first l)) (rest l) r) (recur (conj v (first r)) l (rest r))) (concat v l r)))) ; One of l and r is empty, so concatenate what is already sorted (defn mergesort [pred v] (let [ n (count v) h1 (int (/ n 2)) ; floor(n/2) h2 (int (/ (inc n) 2))] ; ceil(n/2) (if (&lt; n 2) v (merge pred (mergesort pred (take h1 v)) ; take the first half of elements (mergesort pred (take-last h2 v)))))) ; take the last half of elements </code></pre> <p>I'd like critics on how to turn this mergesort algorithm more Clojuric, if there are any Clojure API I could use to simplify it and other issues.</p> <p>Specially, I've used a vector to store elements within <code>merge</code>, because otherwise the <code>conj</code> would append to its front, thus producing a reversed sequence. Also, is <code>take</code> and <code>take-last</code> the way to go to catch two halfs of a <code>seq</code>?</p> <p>The following test code shows it works for vectors, lists and maps. Anything else I should consider?</p> <pre><code>(def v [3 -2 4 5 -3 0 7 -8 1 -1 2]) (def m [{:x 1 :y 2} {:x 0 :y 3} {:x 2 :y 1}]) (def s (seq v)) (mergesort &lt; v) ;=&gt; (-8 -3 -2 -1 0 1 2 3 4 5 7) (mergesort &gt; v) ;=&gt; (7 5 4 3 2 1 0 -1 -2 -3 -8) (mergesort #(&lt; (java.lang.Math/abs %1) (java.lang.Math/abs %2)) v) ;=&gt; (0 -1 1 2 -2 -3 3 4 5 7 -8) (mergesort #(&lt; (:x %1) (:x %2)) m) ;=&gt; ({:x 0, :y 3} {:x 1, :y 2} {:x 2, :y 1}) (mergesort &gt; s) ;=&gt; (7 5 4 3 2 1 0 -1 -2 -3 -8) </code></pre>
[]
[ { "body": "<p>A few points, though I'm not a Clojure expert:</p>\n\n<ul>\n<li><p>Indentation. You use four-space indentation, but two-space indentation is more common for Lisp in general and also generally preferred for Clojure. (there seems to be a Clojure <a href=\"https://github.com/bbatsov/clojure-style-guide\" rel=\"nofollow\">community style guide</a>)</p></li>\n<li><p>Instead of <code>take-last</code>, you may want to use <code>drop</code>. Since you're traversing the whole list anyway, you could also just use <code>split-at</code> (though that's basically the same as using both <code>take</code> and <code>drop</code>).</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T17:52:43.203", "Id": "23698", "ParentId": "23627", "Score": "1" } }, { "body": "<p>I've followed the suggestions in Asumu Takikawa's answer (specially concerning code style) and rewrote the code for future reference. It suffers from an efficiency problem that I still haven't addressed: <code>split-at</code> calls <code>drop</code>, that in turn runs linearly thru the sequence. This is necessary in case of a list, but not with a vector.</p>\n\n<pre><code>(defn merge* [pred left right]\n (loop [v [] l left r right]\n (if (and (seq l) (seq r))\n (if (pred (first l) (first r))\n (recur (conj v (first l)) (rest l) r)\n (recur (conj v (first r)) l (rest r)))\n (concat v l r))))\n\n(defn mergesort [pred coll]\n (let [n (count coll)]\n (if (&lt; n 2)\n coll\n (let [[left right] (split-at (/ n 2) coll)]\n (merge* pred\n (mergesort pred left)\n (mergesort pred right))))))\n</code></pre>\n\n<p>I also expected some difference in running times for collections with and without a power-of-two count, but it seems excessive...</p>\n\n<pre><code>(def test-list #(take % (repeatedly rand)))\n(def test-mergesort #(time (do (mergesort &lt; (test-list %)) nil)))\n(test-mergesort (* 128 1024))\n;=&gt; \"Elapsed time: 986.060739 msecs\"\n(test-mergesort (* 127 1031)) ; prime numbers\n;=&gt; \"Elapsed time: 1344.07105 msecs\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T01:16:20.907", "Id": "23937", "ParentId": "23627", "Score": "0" } } ]
{ "AcceptedAnswerId": "23698", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T18:44:10.040", "Id": "23627", "Score": "3", "Tags": [ "clojure", "sorting", "mergesort" ], "Title": "Mergesort implementation in Clojure" }
23627
<p>I'm trying to make a card game, using OOP style. I decided to make suit a class rather than an <code>enum</code> as I would first have done. How am I doing so far? Am I over-complicating things by making it a class?</p> <pre><code>namespace Cards { class Suit { public: Suit(); ~Suit(); std::string GetName(bool plural, bool capital) const; bool IsRed() const; bool IsBlack() const; bool IsDifferentColour(const Suit&amp; other) const; bool IsSameColour(const Suit&amp; other) const; bool operator == (const Suit&amp; other) const; bool operator != (const Suit&amp; other) const; bool operator &lt; (const Suit&amp; other) const; static const Suit hearts, diamonds, clubs, spades; private: enum Type { Type_Null, Type_Hearts, Type_Diamonds, Type_Clubs, Type_Spades } type; explicit Suit(Type type); }; } const Cards::Suit Cards::Suit::hearts(Type_Hearts); const Cards::Suit Cards::Suit::diamonds(Type_Diamonds); const Cards::Suit Cards::Suit::clubs(Type_Clubs); const Cards::Suit Cards::Suit::spades(Type_Spades); Cards::Suit::Suit() : type(Type_Null) {} Cards::Suit::Suit(Type type) : type(type) {} Cards::Suit::~Suit() {} std::string Cards::Suit::GetName(bool plural, bool capital) const { std::string name; switch (type) { case Type_Hearts: { name = "Heart"; } break; case Type_Diamonds: { name = "Diamond"; } break; case Type_Clubs: { name = "Club"; } break; case Type_Spades: { name = "Spade"; } break; default: { assert(false); } break; } if (! capital) { name[0] = static_cast&lt;std::string::value_type&gt;(::tolower(name[0])); } if (plural) { name += "s"; } return name; } bool Cards::Suit::IsRed() const { bool red; switch (type) { case Type_Hearts: { red = true; } break; case Type_Diamonds: { red = true; } break; case Type_Clubs: { red = false; } break; case Type_Spades: { red = false; } break; default: { assert(false); // prevent compiler warning red = false; } } return red; } bool Cards::Suit::IsBlack() const { return ! IsRed(); } bool Cards::Suit::IsDifferentColour(const Suit&amp; other) const { return this-&gt;IsRed() != other.IsRed(); } bool Cards::Suit::IsSameColour(const Suit&amp; other) const { return this-&gt;IsRed() == other.IsRed(); } bool Cards::Suit::operator == (const Cards::Suit&amp; other) const { return this-&gt;type == other.type; } bool Cards::Suit::operator != (const Cards::Suit&amp; other) const { return ! (*this == other); } bool Cards::Suit::operator &lt; (const Cards::Suit&amp; other) const { return this-&gt;type &lt; other.type; } </code></pre>
[]
[ { "body": "<p>Yes I think you are over complicating things. In C++11 I would use a strongly typed enum:</p>\n\n<pre><code>enum class Suite {Hearts,\n Diamonds,\n Clubs,\n Spades};\n</code></pre>\n\n<p>I might also have considered a simple class hierarchy </p>\n\n<pre><code>namespace suite\n{\n class SuiteBase{...};\n class Hearts : public SuiteBase {...};\n class Diamonds : public SuiteBase {...};\n class Clubs : public SuiteBase {...};\n class Spades : public SuiteBase {...};\n}\n</code></pre>\n\n<p>Then create needed operations between suites. Preferably using some double dispatch technique to be able to compare <code>SuiteBase</code> pointers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T23:53:04.493", "Id": "23638", "ParentId": "23636", "Score": "2" } }, { "body": "<p>If the destructor does nothing remove it:</p>\n\n<pre><code>Cards::Suit::~Suit()\n{}\n</code></pre>\n\n<p>We can shorten that switch statement to make it readable.</p>\n\n<pre><code> switch (type)\n {\n case Type_Hearts: name = \"Heart\"; break;\n case Type_Diamonds: name = \"Diamond\";break;\n case Type_Clubs: name = \"Club\"; break;\n case Type_Spades: name = \"Spade\"; break;\n default: assert(false); break;\n }\n</code></pre>\n\n<p>Or we can replace it with a look up:</p>\n\n<pre><code> static std::string names[] = {\"NULL\", \"Heart\", \"Diamond\", \"Club\", \"Spade\"};\n if (type == Type_Null)\n { assert(false); // Or throw.\n }\n name = names[type];\n</code></pre>\n\n<p>If you want more checking:</p>\n\n<pre><code> static std::vector&lt;std::string&gt; names = {\"Heart\", \"Diamond\", \"Club\", \"Spade\"};\n name = names.at(type-1); // will throw on bad value.\n</code></pre>\n\n<p>This seems a bit over keen. </p>\n\n<pre><code> name[0] = static_cast&lt;std::string::value_type&gt;(::tolower(name[0]));\n</code></pre>\n\n<p><code>std::string::value_type</code> by definition is char.<br>\ntolower() may return an int unless you pass in an EOF you will get a character back.</p>\n\n<p>I would have just done:</p>\n\n<pre><code> name[0] = ::tolower(name[0]);\n</code></pre>\n\n<p>In this switch use fall throug:</p>\n\n<pre><code>switch (type)\n{\n case Type_Hearts: /* fall through */\n case Type_Diamonds: return true;\n\n case Type_Clubs: /* fall through */\n case Type_Spades: return false;\n default: assert(false);\n // prevent compiler warning\n return true;\n}\n</code></pre>\n\n<p>Is A Null_Suit the same as another Null_Suit?<br>\nin double a NaN is not equal to another NaN you may want that kind of functionality.</p>\n\n<pre><code>bool Cards::Suit::operator == (const Cards::Suit&amp; other) const\n{\n return this-&gt;type == other.type;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T01:16:26.153", "Id": "23639", "ParentId": "23636", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T23:36:33.950", "Id": "23636", "Score": "2", "Tags": [ "c++", "object-oriented", "playing-cards" ], "Title": "Suit class for card game" }
23636
<p>I have a Ruby class into which I want to include both class and instance methods. Following the pattern described in "<a href="http://www.dan-manges.com/blog/27" rel="nofollow">Ruby Pattern: Extend through Include</a>", I'm currently using the following:</p> <pre><code>class SomeObject include SomeObject::Ability def self.some_builder_method(params) # use some_class_method ... end end module SomeObject::Ability module ClassMethods def some_class_method(param) # ... end end def self.included(klass) klass.extend(ClassMethods) end def some_instance_method # ... end end </code></pre> <p>I'd rather not make two separate modules, one being included and the other being extended, because all the methods in my module logically fit together. On the other hand, this pattern requires me to:</p> <ol> <li>Define an additional <code>ClassMethods</code> module.</li> <li>Write a boilerplate <code>self.included</code> method for every module.</li> </ol> <p>Is this the most idiomatic way to approach this? </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T15:29:49.853", "Id": "36473", "Score": "1", "body": "AFAIK `self.included` + `.extend(ClassMethods)` is pretty much the way to do it. If you're using Rails, you can use [ActiveSupport::Concern](http://api.rubyonrails.org/classes/ActiveSupport/Concern.html) which handles this kind of thing." } ]
[ { "body": "<p>You're doing it right :) It's a very common idiom, and widely accepted as the preferred way to handle this.</p>\n\n<p>In case you're still in doubt, here are a few examples of the same pattern found in major projects out in the wild: <a href=\"https://github.com/mperham/sidekiq/blob/4e66339f653496b43b2f117905f65f9d73ac0eb3/lib/sidekiq/actor.rb#L3-L5\" rel=\"nofollow\">sidekiq</a>, <a href=\"https://github.com/mongoid/moped/blob/master/lib/moped/connection/socket/connectable.rb#L26-L36\" rel=\"nofollow\">mongoid</a> and <a href=\"https://github.com/datamapper/dm-core/blob/master/lib/dm-core/model/hook.rb#L8-L12\" rel=\"nofollow\">datamapper</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T03:54:18.057", "Id": "30160", "ParentId": "23637", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-08T23:40:28.627", "Id": "23637", "Score": "1", "Tags": [ "ruby", "singleton", "modules" ], "Title": "Mixin both instance and class methods in Ruby" }
23637
<p>I have a class something like the following: </p> <pre><code>class ItemManager { List&lt;Item&gt; items; public ItemManager() { items = Database.retrieveItems(); } } </code></pre> <p>An item has several attributes, so much so that I used a Builder class instead of a typical constructor(Like the builder classes found in Joshua Bloch's <em>Effective Java</em>). I want to use ItemManager to keep track of a large number of items and I want to be able to search for Items that match one or more given attributes. My question is, is the following method a reasonable approach, where can I improve it, and what is a common method of tackling this problem?</p> <pre><code>class ItemManager { ... // constructor etc. public Search getSearch() { return new Search(); } public class Search { // Set default search parameters AttrA attrA = null; AttrB attrB = null; AttrC attrC = null; public Search setAttrA(AttrA a) { attrA = a; return this; } ... // set method for all attributes public List&lt;Item&gt; search() { List&lt;Item&gt; results = new ArrayList&lt;Item&gt;(); for(Item i : items) { // If the search parameter is still null OR if the attribute // matches the search parameter, add it to the result set if ( (attrA==null || i.getAttrA().equals(attrA) ) &amp;&amp; (attrB==null || i.getAttrB().equals(attrB) ) &amp;&amp; (attrC==null || i.getAttrB().equals(attrC) ) { results.add(i); } } return results; } } } </code></pre> <p>The implementation would look somethign like this (bear in mind the actual Item class would have much more than three attributes):</p> <pre><code>ItemManager itemManager = new ItemManager(); List&lt;Item&gt; items = itemManger.getSearch() .setAttrA(a) .setAttrB(b) .search(); </code></pre> <p>There's a number of ways I can think of to improve this, but I didn't want to include them all (so they're welcome).</p>
[]
[ { "body": "<p>You can generify your ItemManager</p>\n\n<pre><code>class ItemManager&lt;T extends Item&gt; {\n\n List&lt;T&gt; items;\n\n public ItemManager() {\n\n items = Database.retrieveItems();\n\n }\n}\n</code></pre>\n\n<p>The search method can be refactored with this help of <a href=\"http://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections/CollectionUtils.html#select%28java.util.Collection,%20org.apache.commons.collections.Predicate%29\" rel=\"nofollow\">CollectionUtils</a> like this</p>\n\n<pre><code>public Collection&lt;Item&gt; search() {\n return getMatchedItems();\n}\n</code></pre>\n\n<p>And her is getMatchedItems()</p>\n\n<pre><code>public Collection&lt;Item&gt; getMatchedItems() {\n CollectionUtils.select(items, new Predicate() {\n public boolean evaluate(Object o) {\n Item item = (Item)o;\n return containsA(item) &amp;&amp; containsB(item) &amp;&amp; containsC(item) //explain below \n }\n });\n\n return items\n}\n</code></pre>\n\n<p>IMO its better to create seperate methods like containsA() , containsB().... </p>\n\n<p>Because as you mentioned you have many attributes(let presume 50), then one big <strong>if</strong> will sooner or later lend you in problems like readability, maintainability and testing.\nYou may say that creating separate methods may degrade your performance but jvm handles method inlining pretty well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T13:43:07.083", "Id": "23655", "ParentId": "23640", "Score": "1" } } ]
{ "AcceptedAnswerId": "23655", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T02:45:41.423", "Id": "23640", "Score": "2", "Tags": [ "java", "object-oriented" ], "Title": "Merit of a \"Search\" class similar to a \"Builder\" class" }
23640
<p>Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.</p> <p>If the last word does not exist, return 0.</p> <p>Note: A word is defined as a character sequence consists of non-space characters only.</p> <p>For example:</p> <pre><code>s result "Hello World" 5 "a " 1 " a " 1 " ba " 2 "ba " 2 </code></pre> <p>The following is my code:</p> <pre><code>int lengthOfLastWord(const char* s) { const char* end=s; while (*end != '\0') { ++end; } --end; while ((end &gt;= s) &amp;&amp; (*end == ' ')) { --end; } const char* start = end; while ((start &gt;= s) &amp;&amp; (*start != ' ')) { --start; } return end-start; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T17:44:29.803", "Id": "36487", "Score": "0", "body": "Not sure how this works: `\"b a \" 2`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T17:59:02.620", "Id": "36488", "Score": "0", "body": "@LokiAstari, it should be `\"ba \" 2`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T22:48:29.810", "Id": "36557", "Score": "0", "body": "For an interview question, surely an important part is explaining how it works, so how about some comments?" } ]
[ { "body": "<p>(Just a quick note, I don't have too much time now.) Here is another approach:</p>\n\n<pre><code>int lengthOfLastWord2(const char* input)\n{ \n int result = 0;\n while (*input != '\\0') {\n if (*input != ' ') {\n result++;\n } else {\n result = 0;\n }\n input++;\n }\n\n return result;\n}\n</code></pre>\n\n<p>Please note that it returns zero when the last character is a space (it was not specified in the question).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T16:27:33.110", "Id": "36478", "Score": "0", "body": "sorry for confusion. I've edited the question. It should return the length of last non-empty word." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:31:12.567", "Id": "36497", "Score": "0", "body": "I added and answer that extends your solution to ignore trailing spaces. Hope you don't mind..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T19:00:55.747", "Id": "36501", "Score": "0", "body": "@WilliamMorris: Of course not, +1, thanks! On the other hand, content on Stack Exchange is under Creative Commons (AFAIK), so it's legal too :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T16:36:52.623", "Id": "36688", "Score": "0", "body": "BTW, I think I have earned more points from this cut-and-paste of your work than for any of my reviews :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T20:55:34.697", "Id": "36702", "Score": "0", "body": "@WilliamMorris: I guess it's easier to read/understand then upvote shorter answers than the deeper and longer ones... There are only 19 Civic Duty and 5 Electorate badges awarded on the site, so I see a lot of space for improvement :) Related: http://meta.codereview.stackexchange.com/questions/612/vote-early-vote-often" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T05:15:14.123", "Id": "23642", "ParentId": "23641", "Score": "3" } }, { "body": "<p>This is just the @palacsint solution extended to ignore trailing spaces.</p>\n\n<pre><code>int lengthOfLastWord2(const char* input)\n{\n int result = 0;\n int last_result = 0;\n\n while (*input != '\\0') {\n if (*input != ' ') {\n result++;\n } else if (result) {\n last_result = result;\n result = 0;\n }\n input++;\n }\n return result ? result : last_result;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:29:50.757", "Id": "23672", "ParentId": "23641", "Score": "4" } }, { "body": "<p>All of the other answers assume \"space\" is only <code>' '</code>, when in fact it can be \\f, \\n, \\t \\r or \\v (see <code>man isspace</code>). The original question states \"empty space characters\" which implies there is more than one meaning (to me) that it is including all space characters. Some of the examples previous included would fail</p>\n\n<pre><code>\"joseph\\n\"\n\"joseph\\v\"\n</code></pre>\n\n<p>counting this as 7 characters instead of 6.</p>\n\n<p>So I thought I would rewrite this using the <code>isspace</code> standard library function, and test it against these other cases as well.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nint lengthOfLastWord3(const char *input )\n{\n const char *end = input;\n const char *last_word_start = NULL;\n const char *last_word_end = NULL;\n char prev_char = '\\0';\n int word_length = 0;\n\n while ( *end != '\\0')\n {\n if ( !isspace( *end ) &amp;&amp; \n ( isspace( prev_char ) || ( prev_char == '\\0' )))\n {\n last_word_start = end;\n last_word_end = end+1;\n }\n else if ( !isspace( prev_char ) &amp;&amp; ( isspace( *end ) ) )\n {\n last_word_end = end;\n }\n else if ( !isspace( prev_char ) &amp;&amp; ( !isspace( *end ) ) )\n {\n last_word_end = end+1;\n }\n\n prev_char = *end;\n\n end++;\n }\n\n if ( last_word_start )\n {\n word_length = last_word_end - last_word_start;\n }\n\n return( word_length );\n}\n</code></pre>\n\n<p>This works for a bunch of additional cases, including entries where <code>\\n</code> <code>\\t</code> <code>\\v</code> <code>\\f</code> are used.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-08T21:07:23.740", "Id": "207265", "ParentId": "23641", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T03:26:02.340", "Id": "23641", "Score": "4", "Tags": [ "c", "strings", "interview-questions" ], "Title": "Length of last word" }
23641
<p>I recently started running but hate running both in the quiet and with music, so i've been listening to podcasts. Unfortunately, I've caught up with all my favorites and so I've started listening to some iTunesU courses, but unfortunately (again) very few of them have audio-only versions.</p> <p>I wrote a shell script to copy any recently added iTunesU video files to another folder as m4a files (via ffmpeg) but since it's the first such script that i've ever written I am slightly worried to set it to run every morning ...</p> <p>Anyway, I would appreciate some feedback from you expert types of what potential problems there might be with how I have it working now or suggestions of how I might improve part of it. Also, as you'll see, I tried to set up a function to do the extension check but couldn't get it to work that way, is there a way to do that?</p> <pre><code>#!/bin/bash oldIFS="$IFS" # allow for files/directories with spaces in the names IFS=$'\n' is_video_file () { ext=$1 if ([ $ext = "m4v" ] || [ $ext = "mp4" ]); then return 1 else return 0 fi } # couldn't get this to work right... iTunesU_Source=~/Music/iTunes_U/ iTunesU_Destination=~/Music/iTunesU_audio/ cd $iTunesU_Source for sub in */; do echo; echo $sub dest_sub=${iTunesU_Destination}/${sub} # create the sub folder if it doesn't exist does_not_exist=false [ -d $dest_sub ] || does_not_exist=true if $does_not_exist; then mkdir $dest_sub fi # get the modified times for the two subfolders source_sub_time=$(stat -f "%m" -t "%s" ${sub}) dest_sub_time=$(stat -f "%m" -t "%s" ${dest_sub}) if $does_not_exist || (( $source_sub_time &gt; $dest_sub_time )); then cd $sub for file in *; do filename=$(basename $file) extension="${filename##*.}" filename="${filename%.*}" dest_file=$dest_sub$filename".m4a" # if ! [[ -f $dest_file ]] &amp;&amp; (is_video_file $extension = 1); if ! [[ -f $dest_file ]] &amp;&amp; ([ $extension = "m4v" ] || [ $extension = "mp4" ]); then ffmpeg -i $file -vn -acodec copy $dest_file fi done; # each file in source sub_folder cd .. fi # source sub_folder is new or recently modified done IFS="$oldIFS" </code></pre>
[]
[ { "body": "<h3>Function</h3>\n\n<p>The command</p>\n\n<pre><code>is_video_file $extension = 1\n</code></pre>\n\n<p>just passes the arguments <code>$extension</code> , <code>=</code> and <code>1</code> to the function <code>is_video_file</code>.</p>\n\n<p>To check if the return value of <code>is_video_file</code> is <em>1</em>, do the following:</p>\n\n<pre><code>is_video_file \"$extension\"\n\nif [ $? = 1 ]; then ...\n</code></pre>\n\n<p>However, making a function return <em>1</em> usually indicates an error; the return value <em>0</em> indicates success.</p>\n\n<p>If you swap <em>1</em> and <em>0</em> in the definition of <code>is_video_file</code>, you can use</p>\n\n<pre><code>if is_video_file \"$extension\"; then ...\n</code></pre>\n\n<h3>Further problems</h3>\n\n<ul>\n<li><p>Every time you do not know the value of a variable with certainty, you should surround it with double quotes.</p>\n\n<p>Most of your variables are unquoted, while the strings are quoted. The latter is unnecessary.</p>\n\n<p>For example, you wrote</p>\n\n<pre><code>[ $ext = \"m4v\" ]\n</code></pre>\n\n<p>which might fail if <code>$ext</code> contains unanticipated characters.</p>\n\n<p>The commands</p>\n\n<pre><code>[ \"$ext\" = \"m4v\" ]\n</code></pre>\n\n<p>and</p>\n\n<pre><code>[ \"$ext\" = m4v ]\n</code></pre>\n\n<p>will both work fine.</p></li>\n</ul>\n\n<h3>Suggestions</h3>\n\n<ul>\n<li><p>There is not need to restore the IFS and the end of the script. Modifying the IFS will only affect the script itself.</p></li>\n<li><p>Setting <code>IFS=$'\\n'</code> gives a false sense of security. It's <em>still</em> necessary to quote all variables if their values are unknown.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T08:00:48.900", "Id": "36456", "Score": "0", "body": "Beware that the OP is on OS X, so `stat`'s `-f` and `-t` options have arguments." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T10:25:58.433", "Id": "36460", "Score": "0", "body": "Ah, that makes sense. The OP didn't mention OS X anywhere." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T21:52:04.983", "Id": "36508", "Score": "0", "body": "Thank you for the help. It is so weird to quote variables but not strings... Also, the function based verification works now." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T03:10:51.240", "Id": "23646", "ParentId": "23645", "Score": "4" } }, { "body": "<ul>\n<li>There is no need for the parentheses in the first <code>if</code> statement.</li>\n<li>You only need a semicolon at the end of an <code>if</code> statement if you put the <code>then</code> on the same line.</li>\n<li><code>then</code> and <code>else</code> belong on the same indentation as <code>if</code>.</li>\n<li>Functions return the exit code of the last statement.</li>\n<li>As @Dennis mentioned, return code 0 is \"true\" and you should always quote variables.</li>\n</ul>\n\n<p>So instead of</p>\n\n<pre><code> if ([ $ext = \"m4v\" ] || [ $ext = \"mp4\" ]); \n then\n return 1\n else\n return 0\n fi \n</code></pre>\n\n<p>you can write simply</p>\n\n<pre><code> [ \"$ext\" = \"m4v\" ] || [ \"$ext\" = \"mp4\" ]\n</code></pre>\n\n<p>To avoid nasty problems with strange filenames you should use <code>./</code> before any glob starting with <code>*</code>, as in <code>for file in ./*</code>.</p>\n\n<p>You don't need a semicolon after <code>done</code> - It's only ever needed if you want to add another command on <em>the same line</em> or (of course) if the semicolon is an actual parameter to the command, as in <code>find . -exec grep foo {} \\;</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-03T11:41:03.280", "Id": "24661", "ParentId": "23645", "Score": "1" } } ]
{ "AcceptedAnswerId": "23646", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T01:09:02.857", "Id": "23645", "Score": "3", "Tags": [ "file-system", "bash", "osx" ], "Title": "Shell script to copy video files to another folder" }
23645
<p>Is there a better way to write this in vs2010 C#?</p> <pre><code>public bool IsAccept() { //check the status is accept if (Status == null) return false; return Status.ToLower() == "accept"; } public bool IsRefer() { //check the status is refer if (Status == null) return false; return Status.ToLower() == "refer"; } public bool IsAnyReviewState() { if (IsAccept() || IsRefer()) return true; return false; } </code></pre> <p>Maybe a simplified way in C# 4 which I'm still learning.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T21:14:48.793", "Id": "36506", "Score": "0", "body": "not a real answer: just make it a ternary operator `public bool IsAccept() { return (Status == null) ? false : Status.ToLower() == \"accept\"; }`" } ]
[ { "body": "<h2>First wave</h2>\n\n<pre><code>public bool IsAccept\n{\n get { return Status != null &amp;&amp; Status.ToLower() == \"accept\"; }\n}\n\npublic bool IsRefer\n{\n get { return Status != null &amp;&amp; Status.ToLower() == \"refer\"; }\n}\n\npublic bool IsAnyReviewState\n{\n get { return IsAccept || IsRefer; }\n}\n</code></pre>\n\n<h2>Second - enums</h2>\n\n<p>The Status property shold be an anum or a type code class. With an enum, you will have a simple solution you just have to watch for some problems when using it: 0 is universal enum value, (SomeEnum)564564 is valid, even if the enum only contain 1, 2; always have a default in a switch statement when using enums.</p>\n\n<h2>Type code</h2>\n\n<p>Type code classes are sealed, they constructors are private and the available options are public static readonly fields. They are much like enums exept they can have other functions, like telling you IsReviewState() or you can easily localize them (you need a ResourceManager, a strongly typed resource file and for example a Display property to get the localized text).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T12:46:26.843", "Id": "23651", "ParentId": "23649", "Score": "5" } }, { "body": "<p>A simpler version of your code (will work in all .NET versions down to 2.0) is the following:</p>\n\n<pre><code>public bool IsAccept\n{\n get { return string.Equals(\"accept\", Status, StringComparison.OrdinalIgnoreCase); }\n}\n\npublic bool IsRefer\n{\n get { return string.Equals(\"refer\", Status, StringComparison.OrdinalIgnoreCase); }\n}\n\npublic bool IsAnyReviewState\n{\n get { return IsAccept || IsRefer; }\n}\n</code></pre>\n\n<p>But a more appropriate solution would be to avoid string literals where an enumeration fits. If you receive the value from an external source, you should parse it into an enum as soon as possible, so that rest of the code deals with typed data only.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T12:53:41.567", "Id": "23652", "ParentId": "23649", "Score": "12" } }, { "body": "<p>Gave this answer on SO, posting here since the question wasn't migrated.</p>\n\n<pre><code>public bool IsAnyReviewState()\n{\n return new [] {\"accept\", \"refer\"}.Contains((Status??string.empty).ToString().ToLower())\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T15:39:42.663", "Id": "23661", "ParentId": "23649", "Score": "0" } } ]
{ "AcceptedAnswerId": "23652", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T12:06:29.900", "Id": "23649", "Score": "1", "Tags": [ "c#", "asp.net" ], "Title": "Simplify C# Code" }
23649
<p>I'm new to front-end development and now I'm learning JavaScript with jQuery. I couldn't understand JavaScript's classes and objects and jQuery plugins, but after reading some articles and examples I wrote simple notifications system.</p> <pre><code>(function ($) { var notification = function (title, msg, duration) { var self = this; this.hide = function () { self.element.fadeOut(1000, function () { self.element.remove(); }) } this.element = $('&lt;div class="notification"&gt;&lt;h3&gt;' + title + '&lt;/h3&gt;&lt;div class="notification_body"&gt;' + msg + '&lt;br/&gt;&lt;i&gt;(double click to hide)&lt;/i&gt;&lt;/div&gt;&lt;/div&gt;'); this.element.dblclick(self.hide); if (duration !== undefined) { setTimeout(function () { self.hide(); }, duration * 1000); } $('#notifications_bar').prepend(this.element.hide().fadeIn(1000)); }; $.extend({ notify:function (title, msg, duration) { return new notification(title, msg, duration); } }); </code></pre> <p>Example:</p> <pre><code>$(function() { $.notify('Title', 'Message'); // sticky note $.notify('Title', 'Message', 2); // 2-seconds notification }); </code></pre> <p>The most terrible were closures and <code>this</code> keyword. I couldn't understand how to use them, so I want to know if there in my code above 'bad-practice' parts.</p>
[]
[ { "body": "<p>First of, for someone learning jQuery and JavaScript, you've done a great job of avoiding the pitfalls of most new developers to JavaScript;</p>\n\n<ol>\n<li>You're not passing strings to <code>setTimeout</code>, which a lot of people do.</li>\n<li>You've got a good grasp on closures (no matter how long they took you to learn :)).</li>\n<li>You're using strict equals (<code>===</code>) rather than equals.</li>\n</ol>\n\n<p>... so, if you want me to be really, <em>really</em> picky;</p>\n\n<ol>\n<li><p>I don't see much point in adding your code to the jQuery namespace. It would work just as well to be added to your own namespace. A lot of people fall into the habit of defining <em>everything</em> on <code>$</code>, and are scared of declaring your own namespace; don;t be:</p>\n\n<pre><code>var ME = {};\n\nME.notify = function (title, msg, duration) {\n return new notification(title, msg, duration);\n};\n</code></pre></li>\n<li><p>It's a code convention to use a capital letter for constructors (e.g. functions you need to call <code>new</code> on); change <code>function notification</code> to <code>function Notification</code>.</p></li>\n<li><p>You could make use of <a href=\"https://stackoverflow.com/questions/572897/how-does-javascript-prototype-work\">prototypical inheritance</a>. As it stands, you're defining and adding a <code>hide</code> function on every instance of a notification you create. Obviously this has a negligible memory impact. Instead, use prototypical inheritance, and declare the function once;</p>\n\n<pre><code>function Notification (blah, blah, blah) {\n // blah blah blah\n} \n\nNotification.prototype.hide = function () {\n var self = this;\n\n this.element.fadeOut(1000, function () {\n self.element.remove();\n });\n}\n</code></pre>\n\n<p>... you'd then have to change your double click handler to use the anonymous function approach I recommended in <a href=\"https://stackoverflow.com/a/15309663/444991\">my answer</a>, as <code>this</code> will no longer be the correct <code>this</code>.</p></li>\n<li><p>You've got a potential <a href=\"http://en.wikipedia.org/wiki/Cross-site_scripting\" rel=\"nofollow noreferrer\">XSS exploit</a>. For example, given the <code>message</code>:</p>\n\n<pre><code>&lt;script&gt;alert(document.cookie);&lt;/script&gt;\n</code></pre>\n\n<p>This will be injected, and evaluated in your page. You can fix this by setting the <code>h3</code> and <code>p</code> using <code>text()</code> explicitly;</p>\n\n<pre><code>this.element = $('&lt;div class=\"notification\"&gt;&lt;h3&gt;&lt;/h3&gt;&lt;div class=\"notification_body\"&gt;&lt;span class=\"text\"&gt;&lt;/span&gt;&lt;br/&gt;&lt;i&gt;(double click to hide)&lt;/i&gt;&lt;/div&gt;&lt;/div&gt;');\n\nthis.element.find('h3').text(title);\nthis.element.find('span.text').text(message);\n</code></pre></li>\n</ol>\n\n<p>... but again, I want to re-iterate that I'm being <em>very</em>, <strong><em>very</em></strong> picky. What you've got is well written, functioning JavaScript.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T16:46:21.507", "Id": "36481", "Score": "0", "body": "Awesome answer, big thank you again for taking the time for me. I have some questions about your corrections:\n1. In which namespace constructor Notification should be? `Me.Notification` and `Me.notify`?\n4. Notification's info receiving from server, so I think I needn't use `text` method, is it correct? Some HTML codes can be used (for example <b>, <i>, etc.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:04:11.443", "Id": "36489", "Score": "0", "body": "@DarkNeo: You can still keep your `Notification` constructor private as you have done, and only expose the `notify` method on your own namespace. Note that the captial `E` (i.e. `ME`) was deliberate for your namespace; I recommend either using all caps (`ME`) or camelCase (`me`) for your namespace, otherwise it could get confused as a Constructor function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:04:40.383", "Id": "36490", "Score": "0", "body": "@DarkNeo: And yes, it was only a possible XSS exploit; providing you're sanitizing the input, you're good to go." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:16:57.410", "Id": "36493", "Score": "0", "body": "Okay, Matt, thank you, I made changes in my code as you recommended. Have a nice day :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T13:42:02.187", "Id": "23654", "ParentId": "23653", "Score": "3" } } ]
{ "AcceptedAnswerId": "23654", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T13:24:03.613", "Id": "23653", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Simple JS/jQuery notification system" }
23653
<p>I am writing a specialized version of the cross correlation function as used in neuroscience. The function below is supposed to take a time series <code>data</code> and ask how many of its values fall in specified bins. My function <code>xcorr</code> works but is horrifically slow even. A test data set with 1000 points (and so 0.5*(1000*999) intervals) distributed over 400 bins takes almost ten minutes.</p> <p><strong>Bottleneck</strong></p> <p>The bottleneck is in the line <code>counts = array([sum ...</code>. I assume it is there because each iteration of the <code>foreach</code> loop searches through the entire vector <code>diffs</code>, which is of length <code>len(first)**2</code>.</p> <pre><code>def xcorr(first,second,dt=0.001,window=0.2,savename=None): length = min(len(first),len(second)) diffs = array([first[i]-second[j] for i in xrange(length) for j in xrange(length)]) bins = arange(-(int(window/dt)),int(window/dt)) counts = array[sum((diffs&gt;((i-.5)*dt)) &amp; (diffs&lt;((i+.5)*dt))) for i in bins] counts -= len(first)**2*dt/float(max(first[-1],second[-1])) #Normalization if savename: cPickle.dump((bins*dt,counts),open(savename,'wb')) return (bins,counts) </code></pre>
[]
[ { "body": "<p>Here's a crack at my own question that uses built-in functions from <code>NumPy</code> </p>\n\n<p><strong>Update</strong></p>\n\n<p>The function chain <code>bincount(digitize(data,bins))</code> is equivalent to <code>histogram</code>, which allows for a more succinct expression.</p>\n\n<pre><code> def xcorr(first,second,dt=0.001,window=0.2,savename=None):\n length = min(len(first),len(second))\n diffs = array([first[i]-second[j] for i in xrange(length) for j in xrange(length)])\n counts,edges = histogram(diffs,bins=arange(-window,window,dt))\n counts -= length**2*dt/float(first[length])\n if savename:\n cPickle.dump((counts,edges[:-1]),open(savename,'wb'))\n return (counts,edges[:-1])\n</code></pre>\n\n<p>The indexing in the <code>return</code> statement comes because I want to ignore the edge bins. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T16:05:23.163", "Id": "23663", "ParentId": "23656", "Score": "1" } }, { "body": "<p>Going to try to help you do this in a faster fashion rather than write the code for you entirely:</p>\n\n<pre><code>import pandas as pd\ndata = pd.DataFrame(data)\n</code></pre>\n\n<p>Now you can easily do your diffs without those slow loops - note my comments should help but basically you are taking advantage of Pandas very fast and simple calculation on the time series; .shift(1) if 1st row is the OLDEST date (example is for the NEWEST date in 1st row .shift(-1)). Likewise you can shift(2) if the calculation is 2 rows away. Modify to use your algorithm:</p>\n\n<pre><code>diffs = (data[0:] - data[0:].shift(-1))/data[0:]\n</code></pre>\n\n<p>Okay back to your bottleneck issue. Can you tell in your question after your NumPy modification which line is slow? Just counting bins?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-03-21T19:17:07.297", "Id": "123484", "ParentId": "23656", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T14:43:36.820", "Id": "23656", "Score": "3", "Tags": [ "python", "performance", "numpy", "statistics" ], "Title": "Specialized version of the cross correlation function" }
23656
<p>I made this simple game code. Can you please give me some advice on how I can improve it?</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;conio.h&gt; #include &lt;time.h&gt; #include &lt;windows.h&gt; void main () { printf("\t\tWelcome to our gessing game\n\n\n"); printf("the computer choose a random number between 1-99, try to gess the random number..."); srand(time(NULL)); int gess,i=0,found=0, r = rand()%100; while (i&lt;10 &amp;&amp; found==0) { printf("\n My gess is:\t"); scanf("%d",&amp;gess); if (gess==r) { found=1; i++; } else if(gess&gt;r) { printf("\n Too big\n"); i++; } else if(gess&lt;r) { printf("\n Too small\n"); i++; } } if (found==1&amp;&amp;gess==1) printf("\n Very good the number is %d this is your %dst gess",gess,i); else if(found==1&amp;&amp;gess==2) printf("\n very good the number is %d this is your %dnd gess",gess,i); else if(found==1&amp;&amp;gess==3) printf("\n very good the number is %d this is your %drd gess",gess,i); else if(found==1&amp;&amp;gess!=1&amp;&amp;gess!=2&amp;&amp;gess!=3) printf("\n very good the number is %d this is your %dth gess",gess,i); else printf("\n Never mind try again"); getch(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T17:14:27.857", "Id": "36484", "Score": "0", "body": "Tabs don't translate well to the web. Please format your code so it is easy to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T17:23:33.813", "Id": "36485", "Score": "0", "body": "easier to read now ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T17:39:58.080", "Id": "36486", "Score": "0", "body": "I already formatted so it was easy to read. You just overwrote it. But if you are going to make an effort please look at it and make sure it looks good (you seem to have put all the `if` against the left side). Its hard to read code at the best of times try not to make it harder with bad formatting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T00:25:01.343", "Id": "36513", "Score": "1", "body": "Why did you include windows.h?" } ]
[ { "body": "<p>One variable per line please.</p>\n\n<pre><code>int gess,i=0,found=0, r = rand()%100;\n</code></pre>\n\n<p>This makes the code hard to read. There is also one corner case (with pointers) were this will not work as expected for beginners. As a result this is usually banned in most companies coding standards.</p>\n\n<p>You are using <code>found</code> as a boolean variable.<br>\nTreat it as such. use TRUE/FALSE.</p>\n\n<p>I would change the <code>while()</code> into a <code>for(;;)</code> loop. Then you can remove all the increments.</p>\n\n<pre><code>while (i&lt;10 &amp;&amp; found==0)\n\n--\n\nfor(int i = 0; i &lt; 10 &amp;&amp; !found; ++i)\n</code></pre>\n\n<p>White space is your friend:</p>\n\n<pre><code>if (found==1&amp;&amp;gess==1) // This is hard to read and will get worse with more conditions.\n\nif (found &amp;&amp; (guess == 1)) // much more readable\n// ^^^^^ boolean use it as such.\n</code></pre>\n\n<p>Your \"st\", \"nd\", \"rd\", \"th\" is not correct.</p>\n\n<pre><code>10-19 =&gt; th\nx1 =&gt; st\nx2 =&gt; nd\nx3 =&gt; rd\nx[4-9] =&gt; th\n</code></pre>\n\n<p>Also you print basically the same string every time on success. So we not have one print statement and just separate the logic for getting the ending.\nI would change the logic:</p>\n\n<pre><code>if (!found)\n{\n printf(\"\\n Never mind try again\");\n}\nelse\n{\n char const* ext = \"th\";\n if ((gess &lt; 10) || (gess &gt;= 20)) // 10-&gt;19 already set\n {\n int end = gess % 10;\n if (end == 1) { ext = \"st\";}\n else if (end == 2) { ext = \"nd\";}\n else if (end == 3) { ext = \"rd\";} \n }\n\n printf(\"\\n Very good the number is %d this is your %d%s gess\", gess, i, ext);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:32:33.083", "Id": "36498", "Score": "0", "body": "and by the way the game is meant to be 10 guesses otherwise it wont be fun..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:59:31.553", "Id": "36500", "Score": "0", "body": "Even so. I still prefer my bit at the end. It look tidier with one print statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T00:03:12.837", "Id": "36511", "Score": "0", "body": "Also, gess->guess." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T00:14:44.500", "Id": "36512", "Score": "0", "body": "@luiscubal: I don't correct spelling of text output. That;s the job of a manager. It could be another language for all I know." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T08:39:38.070", "Id": "37678", "Score": "0", "body": "shouldn't it be `gess < 10 || gess >= 20`? As it stands, this will never be true." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T17:35:30.223", "Id": "23668", "ParentId": "23657", "Score": "10" } }, { "body": "<pre><code>#include&lt;stdio.h&gt;\n#include&lt;stdlib.h&gt;\n#include &lt;time.h&gt;\n\n\n\nint main() // Main always return int ...ALWAYS...\n {\n printf(\"\\t\\tWelcome to our gessing game\\n\\n\\n\"); // This could be device specific. If i run it on a minimized screen it might look akward\n\n /*\n maybe, call a function like take_device_width() then use the value returned to\n print the welcome message\n */\n printf(\"the computer choose a random number between 1-99, try to gess the random number...\");\n\n /* You could write something like this\n\n #define MIN_NUM 1\n #define MAX_NUM 99\n\n printf(\"\"The Computer chooses a random number between %d and %d. \\\n You have to guess it using minumun number of guesses\\n\", MIN_NUM, MAX_NUM);\n\n So that when ever you want to change the values for number range you can just\n change it once at pre processor macro.\n\n */\n\n srand(time(NULL)); // srand((unsigned) time(NULL));\n\n /* Dont use bad spellings and always indent code cleanly: i,e int guess, i = 0, found = 0*/\n\n int gess,i=0,found=0, r = rand()%100;\n\n /* INstead of saying that number of guesses is i, you can name it as num_of_guesses. So that next time\n when you look at code you will know what num_of_guesses does . Similarly for r.\n */\n\n /* Instead of using magic number 10, you could write it as a macro:\n\n #define MAX_ATTEMPTS 10\n\n */\n\n\n while (i&lt;10 &amp;&amp; found==0) // indent it here: while(num_of_guesses &lt; MAX_ATTEMPT &amp;&amp; found == 0) \n {\n printf(\"\\n My gess is:\\t\"); // no need of \\t here\n scanf(\"%d\",&amp;gess);\n\n /* Indent it. After a block that does something add a comment of what next block does nad write that code */\n if (gess==r)\n {\n found=1; // instead of found we can do this\n\n /* if(guess == r)\n {\n num_of_guesses++;\n printf(\"You guessed the correct answer in %d guesses\", num_of_guesses);\n exit(0);\n }\n\n will avoid checking for while(condition) even after guessing correct answer\n */\n i++;\n }\n\n else if(gess&gt;r)\n {\n printf(\"\\n Too big\\n\");\n i++;\n }\n else // else is enough here\n {\n printf(\"\\n Too small\\n\");\n i++;\n }\n\n /* most of the newline char are unneccesary */\n }\n\n /* Indent here */\n\n /* This looks daunting. What are you trying to do here. Why so many conditions */\n\n if (found==1&amp;&amp;gess==1)\n printf(\"\\n Very good the number is %d this is your %dst gess\",gess,i);\n else if(found==1&amp;&amp;gess==2)\n printf(\"\\n very good the number is %d this is your %dnd gess\",gess,i);\n else if(found==1&amp;&amp;gess==3)\n printf(\"\\n very good the number is %d this is your %drd gess\",gess,i);\n else if(found==1&amp;&amp;gess!=1&amp;&amp;gess!=2&amp;&amp;gess!=3)\n printf(\"\\n very good the number is %d this is your %dth gess\",gess,i);\n else\n printf(\"\\n Never mind try again\");\n getchar();\n\n /* it could be \n * if(num_of_guesses &gt;= MAX_ATTEMPTS)\n {\n printf(\"You couldn't guess it in suggested attempts. Sorry!\");\n exit(1);\n\n you can even add a yes or no condition to play again\n\n }\n\n */\n return 0;\n }// end main\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-12T18:25:22.297", "Id": "210651", "Score": "2", "body": "Your suggestions are hard to read this way, as comments embedded in the code. I suggest to take the comments outside, see how other answerers do it. It will be a lot more readable, and that's the aim, isn't it? Giving answers that are easy to read, just like code should be easy to read, accessible." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-26T14:54:25.507", "Id": "24389", "ParentId": "23657", "Score": "-1" } }, { "body": "<p>As mentioned in the comments, there's no need for <code>&lt;windows.h&gt;</code> here. For portability reasons, don't include it unless you're actually using code from it. It has nothing to do with running the program <em>on</em> a Windows system, if that's what you were thinking.</p>\n\n<p>Also, your unformatted output statements (no <code>%</code>) can use <a href=\"http://pubs.opengroup.org/onlinepubs/009695399/functions/puts.html\" rel=\"nofollow\"><code>puts()</code></a> instead of <code>printf()</code>. The former also provides a <code>\\n</code> at the end of the output.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-12T18:24:08.440", "Id": "113747", "ParentId": "23657", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T14:57:08.420", "Id": "23657", "Score": "5", "Tags": [ "c", "windows", "number-guessing-game" ], "Title": "Simple random number guessing game" }
23657
<p><strong>Premise:</strong> Write a program that counts the frequencies of each word in a text, and output each word with its count and line numbers where it appears. We define a word as a contiguous sequence of non-white-space characters. Different capitalizations of the same character sequence should be considered same word (e.g. Python and python). The output is formatted as follows: each line begins with a number indicating the frequency of the word, a white space, then the word itself, and a list of line numbers containing this word. You should output from the most frequent word to the least frequent. In case two words have the same frequency, the lexicographically smaller one comes first. All words are in lower case in the output.</p> <p><strong>Solution:</strong></p> <pre><code># Amazing Python libraries that prevent re-invention of wheels. import re import collections import string from operator import itemgetter # Simulate work for terminal print 'Scanning input for word frequency...' # Text files input = open('input.txt', 'r') output = open('output.txt', 'w') # Reads every word in input as lowercase while ignoring punctuation and # returns a list containing 2-tuples of (word, frequency). list = collections.Counter(input.read().lower() .translate(None, string.punctuation).split()).most_common() # Sorts the list by frequency in descending order. list = sorted(list, key=itemgetter(0)) # Sorts the list by lexicogrpahical order in descending order while maintaining # previous sorting. list = sorted(list, key=itemgetter(1), reverse=True) # Gets the lines where each word in list appears in the input. for word in list: lineList = [] # Reads the input line by line. Stores each text line in 'line' and keeps a # counter in 'lineNum' that starts at 1. for lineNum, line in enumerate(open('input.txt'),1): # If the word is in the current line then add it to the list of lines # in which the current word appears in. The word frequency list is not # mutated. This is stored in a separate list. if re.search(r'(^|\s)'+word[0]+'\s', line.lower().translate(None, string.punctuation), flags=re.IGNORECASE): lineList.append(lineNum) # Write output with proper format. output.write(str(word[1]) + ' ' + word[0] + ' ' + str(lineList)+'\n') # End work simulation for terminal print 'Done! Output in: output.txt' </code></pre> <p>How can I get the line numbers without re-reading the text? I want to achieve sub-O(n^2) time complexity. I am new to Python so feedback on other aspects is greatly appreciated as well.</p>
[]
[ { "body": "<p>You're right, the basic point to make this program faster is to store the line numbers in the first pass.</p>\n\n<p>The <code>for word in list</code> loop will run many times. The count depends on how many words you have. Every time it runs, it reopens and rereads the whole input file. This is awfully slow.</p>\n\n<p>If you start using a more generic data structure than your <code>Counter()</code>, then you'll be able to store the line numbers. For example you could use a dictionary. The key of the dict is the word, the value is a list of line numbers. The hit count is stored indirectly as the length of the list of line numbers.</p>\n\n<p>In one pass over the input you can populate this data structure. In a second step, you can properly sort this data structure and iterate over the elements.</p>\n\n<p>An example implementation:</p>\n\n<pre><code>from collections import defaultdict\nimport sys \n\nif __name__ == \"__main__\":\n hit = defaultdict(list)\n for lineno, line in enumerate(sys.stdin, start=1):\n for word in line.split():\n hit[word.lower()].append(lineno)\n for word, places in sorted(hit.iteritems(), key=lambda (w, p): (-len(p), w)):\n print len(places), word, \",\".join(map(str, sorted(set(places))))\n</code></pre>\n\n<p>A few more notes:</p>\n\n<ol>\n<li><p>If you <code>open()</code> a file, <code>close()</code> it too. As soon as you're done with using it. (Or use <a href=\"http://docs.python.org/2/reference/compound_stmts.html#the-with-statement\" rel=\"nofollow\">the <code>with</code> statement</a> to ensure that it gets closed.)</p></li>\n<li><p>Don't hardcode input/output file names. Read from standard input (<code>sys.stdin</code>), write to standard output (<code>sys.stdout</code> or simply <code>print</code>), and let the user use his shell's redirections: <code>program &lt;input.txt &gt;output.txt</code></p></li>\n<li><p>Don't litter standard output with progress messages. If you absolutely need them use <code>sys.stderr.write</code> or get acquainted with the <code>logging</code> module.</p></li>\n<li><p>Don't use regular expressions, unless it's necessary. Prefer string methods for their simplicity and speed.</p></li>\n<li><p>Name your variables in <code>lower_case_with_underscores</code> as <a href=\"https://www.google.co.uk/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;ved=0CDIQFjAA&amp;url=http://www.python.org/dev/peps/pep-0008/&amp;ei=8Pc9UfzGLKaM7AaSloB4&amp;usg=AFQjCNERHdnSYA5JWg_ZfKT_cVYU4MWGyw&amp;bvm=bv.43287494,d.ZGU\" rel=\"nofollow\">PEP8</a> recommends.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T05:38:24.860", "Id": "36524", "Score": "0", "body": "Great review. Are there any performance reasons for note 2? Also, when you say \"let the user use his shell's redirections: `program <input.txt >output.txt`\" does that mean that when I run my program from the terminal I can pass the filenames as arguments?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T09:21:06.210", "Id": "36528", "Score": "1", "body": "There are cases when (2) can help in better performance. In a pipeline like `prg1 <input.txt | prg2 >output.txt` prg1 and prg2 are started in parallel (at least in unix-like OSes). prg2 does not have to wait for prg1 to finish, but can start to work when prg1 produced any output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T09:28:59.343", "Id": "36529", "Score": "1", "body": "__Can I pass the filenames as arguments?__ Yes, you can specify the filenames in the terminal. To be precise, these are not arguments, they are not processed by your program. They are called `shell redirections` and are processed by your command shell. They are extra useful, google them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T17:18:21.743", "Id": "36621", "Score": "0", "body": "@Gareth Rees: I'm not sure whether you have noticed, but with your edit you introduced a little semantic change. The edited code counts a word at most once per line. Previously (as in the OP) it counted multiple occurences in the same line, but later printed the line number only once." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T17:29:44.803", "Id": "36625", "Score": "0", "body": "@rubasov: You're quite right. That was my mistake." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T22:39:58.410", "Id": "23681", "ParentId": "23662", "Score": "3" } } ]
{ "AcceptedAnswerId": "23681", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T16:00:50.760", "Id": "23662", "Score": "4", "Tags": [ "python", "optimization" ], "Title": "Improve efficiency for finding word frequency in text" }
23662
<blockquote> <p>Given a number represented as an array of digits, plus one to the number.</p> <pre><code>input expected [8,9,9,9] [9,0,0,0] [1,0,0,0,0] [1,0,0,0,1] [9,8,7,6,5,4,3,2,1,0] [9,8,7,6,5,4,3,2,1,1] </code></pre> </blockquote> <p>The following is my C++ code:</p> <pre><code>vector&lt;int&gt; plusOne(vector&lt;int&gt; &amp;digits) { vector&lt;int&gt; result; vector&lt;int&gt;::iterator it; int plus = 1; for (it = digits.end() - 1; it &gt;= digits.begin(); --it) { int sum = *it + plus; if (sum &gt; 9) { plus = 1; result.push_back(0); } else { result.push_back(sum); plus = 0; } } if (plus==1) { result.push_back(1); } reverse(result.begin(), result.end()); return result; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T01:33:50.580", "Id": "36660", "Score": "0", "body": "What should [9, 9, 9] do? Should it cause an error, or push anew element onto the vector to return [1, 0, 0, 0]?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T18:44:46.680", "Id": "36995", "Score": "0", "body": "@Dave, it should return [1, 0, 0, 0]" } ]
[ { "body": "<p>Since you are returning a result.<br>\nPass the parameter by const reference so that you don't accidentally modify it:</p>\n\n<pre><code>vector&lt;int&gt; plusOne(vector&lt;int&gt; const&amp; digits)\n</code></pre>\n\n<p>The less than operator is not defined for iterators.<br>\nYou are just getting lucky.</p>\n\n<pre><code>for (it = digits.end() - 1; it &gt;= digits.begin(); --it)\n</code></pre>\n\n<p>To iterate over a container in the reverse direction use <code>rbegin()</code> and <code>rend()</code></p>\n\n<pre><code>for (it = digits.rbegin(); it != digits.rend(); ++it)\n</code></pre>\n\n<p>To help with efficiency you could reserve space in your result:</p>\n\n<pre><code>result.reserve(digits.size()+1); // The +1 is for cases where the result overflows.\n // Note: reserve() does not change the size of the\n // vector just the underlying capacity.\n</code></pre>\n\n<p>Personally I would have refactored:</p>\n\n<pre><code> if (sum &gt; 9)\n {\n plus = 1;\n result.push_back(0);\n }\n else\n {\n result.push_back(sum);\n plus = 0;\n }\n</code></pre>\n\n<p>the body into:</p>\n\n<pre><code> plus = (sum == 10) ? 1 : 0\n sum = (sum == 10) ? 0 : sum;\n\n result.push_back(sum);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T03:00:00.767", "Id": "36518", "Score": "0", "body": "\"The less than operator is not defined for iterators.\" Not true. `std::random_access_iterator` supports all equality comparisons." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T03:43:59.450", "Id": "36520", "Score": "0", "body": "@Yuushi: I was very precise in what I said. But lets make the assumption that its `std::random_access_iterator`. Now its only valid if the iterators are between begin() and end(). In the above code `it >= digits.begin()` will always be true. At any point where it may potentially be false we have strayed into undefined behavior." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T03:52:10.787", "Id": "36521", "Score": "0", "body": "I don't disagree with you, but I do think the wording could be better. What you've said in your comment should be in your answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T17:01:02.963", "Id": "23667", "ParentId": "23666", "Score": "4" } }, { "body": "<p>Sometimes it might be good to come up with a different way of solving a instance problem <a href=\"http://codepad.org/cpJYxKau\" rel=\"nofollow\">http://codepad.org/cpJYxKau</a></p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\nusing namespace std;\n\ntypedef std::vector&lt;int&gt; IntVector;\n\nint findAddablePosition(const IntVector&amp; src){\n int position = src.size() - 1;\n while( position &gt;= 0){\n if(src[position] &lt; 9) break;\n else --position ;\n }\n return position;\n}\nIntVector addOne(const IntVector&amp; src){\n int addablePosition= findAddablePosition(src);\n IntVector result(src);\n result[addablePosition] += 1;\n std::fill( result.begin() + addablePosition + 1, result.end(), 0);\n return result;\n}\n\nvoid print(const IntVector&amp; vec){\n cout &lt;&lt; \"[\";\n for(unsigned i = 0; i &lt; vec.size(); ++i) cout &lt;&lt; vec[i] &lt;&lt; \" \";\n\n cout &lt;&lt; \"]\";\n}\n\nint main(){\n int input[] = {8,9,9,9};\n IntVector vecInput(input,input + sizeof(input)/sizeof(input[0]));\n print(vecInput);\n cout &lt;&lt; \" --&gt; \";\n print( addOne(vecInput) );\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T20:01:15.557", "Id": "37002", "Score": "0", "body": "does the code work for [9,9,9]?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T22:27:59.407", "Id": "37056", "Score": "0", "body": "no not for that case just need to check if addablePosition is -1, if so then push front and zero-fill the tail." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T22:27:56.217", "Id": "23754", "ParentId": "23666", "Score": "1" } }, { "body": "<p>I can't believe no one is attempting to do this with some sort of carry and modulus operation.</p>\n\n<p>It's not very efficient to branch inside a loop.</p>\n\n<pre><code>// we add 1 by simply initializing the carry to 1 (instead of zero)\nint carry = 1;\n\nfor (auto it = digits.rbegin(); it != digits.rend(); ++it)\n{\n int x = *it + carry;\n result.push_back(x % 10);\n carry = x / 10;\n}\n\nif (carry &gt; 0)\n{\n result.push_back(x % 10);\n}\n\nreverse(result.begin(), result.end());\n</code></pre>\n\n<p>This being an interview question and all I think it's important to point you that you should show that you understand the basics of numeral systems.</p>\n\n<p>The above code contains less corner cases because it's built on top of a rigid formula. This is a more elegant solution and I'd recommend this style of writing simply because it results in less code.</p>\n\n<p>It's unfortunate that the question appears to imply a big endian, in this case it would have been more efficient to store least significant number in the lower range of the vector since that would allow for a faster forward scan (reverse scan is slower) when performing the operation with the carry. Though, it wouldn't surprise me if it was put there just to mess with people's heads.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-12T16:58:03.297", "Id": "26084", "ParentId": "23666", "Score": "2" } } ]
{ "AcceptedAnswerId": "23667", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T16:47:32.347", "Id": "23666", "Score": "5", "Tags": [ "c++", "interview-questions", "vectors" ], "Title": "Given a number represented as an array of digits, plus one to the number" }
23666
<blockquote> <p>Given a sorted linked list, delete all duplicates such that each element appears only once.</p> <p>For example:</p> <ul> <li>Given 1->1->2, return 1->2.</li> <li>Given 1->1->2->3->3, return 1->2->3.</li> </ul> </blockquote> <p>The following is my code:</p> <pre><code>struct ListNode { int data; ListNode *next; ListNode(int x) : data(x), next(NULL) {} }; ListNode *getNextElement(ListNode *head){ while ((head != NULL) &amp;&amp; (head-&gt;next != NULL) &amp;&amp; (head-&gt;data == head-&gt;next-&gt;data)){ head = head-&gt;next; } return head-&gt;next; } ListNode *deleteDuplicates(ListNode *head) { // Start typing your C/C++ solution below // DO NOT write int main() function ListNode *cur = head; ListNode *next = NULL; while (cur != NULL){ next = getNextElement(cur); cur-&gt;next = next; cur = next; } return head; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:48:36.860", "Id": "36499", "Score": "0", "body": "Are the nodes dynamically allocated. If so you are leaking." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T19:40:54.323", "Id": "36502", "Score": "0", "body": "yes, I don't write code to free dynamically allocated memory~" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-29T14:36:09.453", "Id": "136542", "Score": "0", "body": "Do the duplicates occur in quick succession or they can randomly be anywhere in the list?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-20T12:04:48.190", "Id": "334132", "Score": "0", "body": "@Fihop Hey, I really like the simplicity of your solution. Is it possible to do this recursively instead of using a while loop? I've tried a couple varieties but they all mess up with edge cases." } ]
[ { "body": "<p>You could browse all the elements of the linked list and store their value, address, and the number of time they appear in an array. After that you just have to remove (form the linked list) the address stored in the array which correspond to values that appears more than once.</p>\n\n<p>One advantage of this method is that you have to browse your linked list only once. on the other hand, you have to store all the value of your linked list in an array which uses more memory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T20:47:08.263", "Id": "36504", "Score": "1", "body": "The list is sorted to begin with, so you only need to go through it once in either way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T21:14:55.560", "Id": "36507", "Score": "0", "body": "Oh, you're right I didn't notice the \"sorted\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:21:27.690", "Id": "23671", "ParentId": "23670", "Score": "0" } }, { "body": "<p>head can never be NULL</p>\n\n<pre><code>ListNode *getNextElement(ListNode *head){ \n while ((head != NULL) // This can't be NULL\n // because you test before calling. \n &amp;&amp; (head-&gt;next != NULL) \n &amp;&amp; (head-&gt;data == head-&gt;next-&gt;data)){\n head = head-&gt;next; \n }\n\n\n // If head can be NULL then you should also be checking here.\n // Otherwise this may fail.\n return head-&gt;next;\n}\n</code></pre>\n\n<p>Small notes:</p>\n\n<pre><code>ListNode *deleteDuplicates(ListNode *head) {\n // Start typing your C/C++ solution below\n // DO NOT write int main() function\n\n // Replace with for(;;)\n for(ListNode* cur = head; cur != NULL; cur = cur-&gt;next){\n // Move declaration of next here.\n // It is not used outside the loop so why pollute\n ListNode *next = getNextElement(cur);\n\n // May want to make sure you don't leak.\n ListNode *old = cur-&gt;next;\n while(old != next)\n {\n ListNode* toFree = old; // you can probably put this logic in getNext()\n old = old-&gt;next;\n free(toFree);\n }\n cur-&gt;next = next;\n } \n return head;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-18T16:17:37.470", "Id": "333753", "Score": "0", "body": "Hey, I really like the simplicity of your solution. Is it possible to do this recursively instead of using a while loop? I've tried a couple varieties but they all mess up with edge cases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-20T02:43:28.423", "Id": "334074", "Score": "1", "body": "@takanuva15: I did not write this I just wrote a review on it. Look above to the OP." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-20T12:05:09.463", "Id": "334133", "Score": "0", "body": "Oops yeah, I see that now; srry" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:57:41.557", "Id": "23674", "ParentId": "23670", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:18:12.370", "Id": "23670", "Score": "3", "Tags": [ "c++", "linked-list" ], "Title": "Remove duplicates from a linked list" }
23670
<p>I am trying to delete a large folders (with many levels of subfolders) over a network (i.e, on a remote machine). </p> <p>I have the following code and it takes 10 minutes. Is there a way to improve this drastically?</p> <pre><code>public static boolean deleteDirectory(File directory) { File[] files = directory.listFiles(); // Value is null if the file is not an directory or if the file doesn't exist if(null!=files &amp;&amp; files.length&gt;0){ //Gets in here only if the file is directory long filesCount = files.length; for(int i=0; i&lt;filesCount; i++) { deleteDirectory(files[i]); } } return(directory.delete()); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T22:24:04.773", "Id": "36509", "Score": "2", "body": "Do you have command line access to the machines? Because it would probably be faster to have the OS do it with `rmdir`/`rm -rf` in a `Runtime.exec()` if so." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T23:18:18.507", "Id": "36560", "Score": "0", "body": "@MrLore The remote machine can run on windows or linux or something else too. Will this still help ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T21:01:38.160", "Id": "36650", "Score": "0", "body": "In that case it would be a bit of a hassle as you'd have to write different commands for each, or a big if block." } ]
[ { "body": "<p>I decide to write my own function(using native process) to delete the files(tested on <strong>windows</strong>), no external dependencies on jars.</p>\n\n<p>Implementation details for windows:</p>\n\n<ul>\n<li><p>I am using <a href=\"http://en.wikipedia.org/wiki/Robocopy\" rel=\"nofollow\">robocopy</a> because <strong>rmdir</strong> fails for complex or deeply nested file paths.</p></li>\n<li><p>The logic to delete files on windows works like <a href=\"http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collection.html#retainAll%28java.util.Collection%29\" rel=\"nofollow\">Collections.retainsAll()</a>.</p></li>\n</ul>\n\n\n\n<pre><code>import java.io.File;\n\nimport java.io.IOException;\n\npublic class RecursiveDelete {\n\n public static void main(String[] args) throws IOException {\n String dirPath = \"C:\" + File.separator + \"dev_tools\" + File.separator + \"dir_to_delete\";\n System.out.println(\"Delete folder path=\" + dirPath);\n execute(dirPath);\n }\n\n public static void execute(String folderToDelete) throws IOException {\n String os = System.getProperty(\"os.name\").toLowerCase();\n File emptyFolder = createEmptyDirectory();\n if (isWindows(os)) {\n Runtime.getRuntime().exec(\"cmd /c robocopy \" + emptyFolder + \" \" + folderToDelete + \" /purge &amp; rmdir \" + folderToDelete);\n } else if (isUnix(os) || isMac(os) || isSolaris(os)) {\n Runtime.getRuntime().exec(\"rm -r -f \" + folderToDelete);\n }\n }\n\n private static File createEmptyDirectory() {\n File emptyFolder = new File(\"EmptyFolder\");\n if (!emptyFolder.exists()) {\n boolean isCreated = emptyFolder.mkdir();\n System.out.println(\"Is empty folder created ?\" + isCreated);\n System.out.println(\"EmptyFolder path\" + emptyFolder.getAbsolutePath());\n }\n\n return emptyFolder;\n }\n\n public static boolean isWindows(String os) {\n return (os.contains(\"win\"));\n }\n\n public static boolean isUnix(String os) {\n return (os.contains(\"nix\") || os.contains(\"aix\") || os.contains(\"nux\"));\n }\n\n public static boolean isSolaris(String os) {\n return (os.contains(\"sunos\"));\n }\n\n public static boolean isMac(String os) {\n return (os.contains(\"mac\"));\n }\n}\n</code></pre>\n\n<p></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T14:45:51.783", "Id": "36534", "Score": "0", "body": "Yes. This uses the same File.listFiles and delete(). So not going to improve performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T15:34:01.240", "Id": "36538", "Score": "0", "body": "Just check the local copy of src code and realize that one of our team member had tweeked the library to perform some optimization for the in house file system developed and used by us. I also updated my answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T23:15:45.030", "Id": "36558", "Score": "0", "body": "@sol4me performance boost is the only concern for me. I wouldn't mind to have 10 lines of code in place of adding a new jar file for apache commons" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T14:24:33.530", "Id": "36594", "Score": "0", "body": "@sol4me Can you let me know what kind of optimization your team member had done ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T20:41:15.193", "Id": "36648", "Score": "0", "body": "@hop I updated my answer" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T21:37:02.403", "Id": "36652", "Score": "2", "body": "@sol4me +1. This is super fast. But, this won't help in deleting the file in a remote machine right? As Runtime.getRuntime() is the server and not the machine I want to delete the file from. Is my understanding correct ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T12:26:49.867", "Id": "36916", "Score": "0", "body": "@hop you are right, but can't you just invoke this code under the hood on server by creating some service like htpp://somedomain.com/deleteService\nand pass it the directory name which you want to delete like htpp://somedomain.com/deleteService?dirToDelete=foo" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T09:21:31.147", "Id": "23690", "ParentId": "23673", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T18:46:17.150", "Id": "23673", "Score": "4", "Tags": [ "java", "optimization", "performance" ], "Title": "Deleting large folders on remote machines" }
23673
<p>I've designed the basics of an admin page I'd like to use for a small website. I'd like to know if I'm using the language properly. Please rip apart the code and tell me what I could do better.</p> <p>Admin page code, file called "index.php" (just the file name in my "netbeans" folder):</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;link rel="stylesheet" type="text/css" href="admin.css"&gt; &lt;title&gt;Admin Page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;table style="width:100%"&gt; &lt;td valign="center" width="25%"&gt;&lt;img src="BSQ_Logo.jpg" width="61" height="36"&gt;&lt;/td&gt; &lt;td valign="center" align="center" width="15%"&gt;&lt;b&gt;Total Accounts:&lt;/b&gt;&lt;/td&gt; &lt;td valign="center" align="center" width="15%"&gt;&lt;b&gt;Logged On:&lt;/b&gt;&lt;/td&gt; &lt;td valign="center" align="center" width="15%"&gt;&lt;b&gt;Last Updated:&lt;/b&gt;&lt;/td&gt; &lt;td width="25%"&gt; &lt;ul id="navlist"&gt; &lt;li&gt;&lt;a href="#"&gt;Item 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Item 2&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/td&gt; &lt;/table&gt; &lt;/div&gt; &lt;br /&gt; &lt;div&gt; &lt;table id="labels" border="1" style="width:100%"&gt; &lt;td width="20%"&gt;User&lt;/td&gt; &lt;td width="10%"&gt;ID&lt;/td&gt; &lt;td width="10%"&gt;Listings&lt;/td&gt; &lt;td width="10%"&gt;Connections&lt;/td&gt; &lt;td width="5%"&gt;Flags&lt;/td&gt; &lt;td width="10%"&gt;Days&lt;/td&gt; &lt;td width="25%"&gt;Email&lt;/b&gt;&lt;/td&gt; &lt;td width="10%"&gt;Suspend&lt;/td&gt; &lt;/table&gt; &lt;/div&gt; &lt;?php include 'data_sheet.php'; // call funciton form data_sheet.php to get array of data table $user_data = load_data($r); // array to line up the cells in the tables // each row under the collumn headings will be it's own table $cell_width = array('20%','10%','10%','10%', '5%', '10%','25%','10%'); $listings_array = array( array('8343','7410', '1352'), array('6400','1432'), array(), array('3721','0185','4903','2132') ); // funciton to that will return the a dropdown mennu function drop_menu ($listings) { $n_of_items = count($listings); echo "&lt;form&gt;&lt;select&gt; &lt;option&gt;" . $n_of_items . "&lt;/option&gt;\n"; foreach ($listings as $key =&gt; $element) { echo "&lt;option&gt;" . $element . "&lt;/option&gt;\n"; } echo "&lt;/select&gt;&lt;/form&gt;"; } // end of drop_menu function // function 'create_row creates a table for each row /* * aruments need to be: * --$prime coutner counts which row we are in * --$element i.e. array of info for each cell, which * should be the sub array from the database call * -- $cell_width from the cell width formatting araay * -- an array for each dropdown menue * starting with 'listings' and 'connections' * -- $cell_width array - for formating each cell */ function create_row ($prime_counter, $element, $listings, $connections, $cell_width) { // $sub_counter is for keeping track of which cell // in the row is being dealth with $sub_counter = 0; // being the table for the account - one account/table per row echo &lt;&lt;&lt;EOT &lt;br /&gt;&lt;div&gt;&lt;table border="1" style="width:100%"&gt; EOT; // primary foreach loop goes through each // account and lays out data in each cell; // data form a call to teh database foreach ($element as $subkey =&gt; $sub_element) { // begin cell in table echo &lt;&lt;&lt;EOT &lt;td width=$cell_width[$sub_counter]&gt; EOT; // this determins what goes in the cell switch ($sub_counter) { // case 2 is the listing information // need code here to putt the correct array // from the array of array of listings case 2: // drop menu is to show a list of listings // in the cell under the listings column drop_menu($listings[$prime_counter]); break; // default is the data from thte datbase call default: echo $sub_element; break; } // end cell in table echo "&lt;/td&gt;"; $sub_counter++; }// end foreach sub // close the table echo &lt;&lt;&lt;EOT &lt;/table&gt;&lt;/div&gt; EOT; } // end create row function // ****begin display code for the tables under the column headings ********************** /* foreach loop that puts data into the tables * under the column headings * one table for each row * $user_data is the two dimentional array from the dataase */ foreach ($user_data as $key =&gt; $element) { // need a database call based on the user data to get the // list of connections and listing for each user // $key to trigger the right arugments for // each row create_row($key, $element, $listings_array, 0, $cell_width); }// end foreach main ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T16:03:34.253", "Id": "37483", "Score": "2", "body": "At first glance, I don't see anything \"wrong\" with this. However, have you considered separating the logic from the view i.e. using the [MVC](http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller) pattern?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T17:02:54.143", "Id": "37489", "Score": "1", "body": "You are using tables as layout/design. Cascading StyleSheets (CSS) is for layout." } ]
[ { "body": "<h2>PHP Related Things</h2>\n\n<ul>\n<li>Try not to mix HTML and PHP. PHP logic should come on top of the document, HTML below it. Within the HTML, there are just some minor <code>echo</code> and <code>if</code> statements and some loops. If you go a little bit more advanced, you should use something like the MVC pattern (like @karancan suggested).</li>\n</ul>\n\n<h3>Tips</h3>\n\n<ul>\n<li>Take a look at PHPdocs. That's a common used way of documenting you PHP code.</li>\n</ul>\n\n<h2>HTML/CSS Related Things</h2>\n\n<pre><code>&lt;td valign=\"center\" width=\"25%\"&gt;&lt;img src=\"BSQ_Logo.jpg\" width=\"61\" height=\"36\"&gt;&lt;/td&gt;\n</code></pre>\n\n<p>You should not use inline HTML (e.g. <code>width=</code>, <code>height=</code>, <code>valign=</code>). This should be done with CSS in a stylesheet or within a <code>&lt;style&gt;</code> element.</p>\n\n<hr>\n\n<p>There is not much more to say about this script. You are now using functions. I suggest to take a look at Object Oriented Programming (OOP) if you are a little bit more familier to PHP.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T17:02:52.477", "Id": "24310", "ParentId": "23675", "Score": "2" } } ]
{ "AcceptedAnswerId": "24310", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T20:17:09.757", "Id": "23675", "Score": "2", "Tags": [ "php", "html" ], "Title": "Admin page for a small website" }
23675
<p>I created this version of Hangman in Python 3. Does anyone have any tips for optimization or improvement?</p> <pre><code>import random HANGMAN = ( ''' -------+''', ''' + | | | | | -------+''', ''' -----+ | | | | | -------+''', ''' -----+ | | | | | | -------+''', ''' -----+ | | O | | | | -------+''', ''' -----+ | | O | | | | | -------+''', ''' -----+ | | O | /| | | | -------+''', ''' -----+ | | O | /|\ | | | -------+''', ''' -----+ | | O | /|\ | / | | -------+''', ''' -----+ | | O | /|\ | / \ | | -------+''') MAX = len(HANGMAN) - 1 WORDS = ('jazz', 'buzz', 'hajj', 'fuzz', 'jinx', 'jazzy', 'fuzzy', 'faffs', 'fizzy', 'jiffs', 'jazzed', 'buzzed', 'jazzes', 'faffed', 'fizzed', 'jazzing', 'buzzing', 'jazzier', 'faffing', 'fuzzing') sizeHangman = 0 word = random.choice(WORDS) hiddenWord = list('-' * len(word)) lettersGuessed = [] print('\tHANGMAN GAME\n\t\tBy Lewis Cornwall\n') while sizeHangman &lt; MAX: print('This is your hangman:' + HANGMAN[sizeHangman] + '\nThis is the word:\n' + ''.join(hiddenWord) + '\nThese are the letters you\'ve already guessed:\n' + str(lettersGuessed)) guess = input('Guess a letter: ').lower() while guess in lettersGuessed: print('You\'ve already guessed that letter!') guess = input('Guess a letter: ').lower() if guess in word: print('Well done, "' + guess + '" is in my word!') for i in range(len(word)): if guess == word[i]: hiddenWord[i] = guess if hiddenWord.count('-') == 0: print('Congratulations! My word was ' + word + '!') input('Press &lt;enter&gt; to close.') quit() else: print('Unfortunately, "' + guess + '" is not in my word.') sizeHangman += 1 lettersGuessed.append(guess) print('This is your hangman: ' + HANGMAN[sizeHangman] + 'You\'ve been hanged! My word was actually ' + word + '.') input('Press &lt;enter&gt; to close.') </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T13:22:45.947", "Id": "36588", "Score": "2", "body": "Not an optimization, but you could load your words from a - possibly encrypted - text file instead of having them in your raw code :)" } ]
[ { "body": "<p>You can avoid repeating <code>guess = input('Guess a letter: ').lower()</code> by changing the inner while loop to:</p>\n\n<pre><code>while True:\n guess = input('Guess a letter: ').lower()\n if guess in lettersGuessed:\n print('You\\'ve already guessed that letter!')\n else:\n break\n</code></pre>\n\n<p>Instead of <code>for i in range(len(word))</code> use:</p>\n\n<pre><code>for i, letter in enumerate(word):\n</code></pre>\n\n<p>You could also avoid indexing by <code>i</code> altogether by using a list comprehension. I'm not sure if this is as clear in this case, though.</p>\n\n<pre><code>hiddenWord = [guess if guess == letter else hidden for letter, hidden in zip(word, hiddenWord)]\n</code></pre>\n\n<p>Instead of <code>hiddenWord.count('-') == 0</code> use:</p>\n\n<pre><code>'-' not in hiddenWord\n</code></pre>\n\n<p><a href=\"http://docs.python.org/3/library/constants.html#constants-added-by-the-site-module\">The docs</a> say <code>quit()</code> should not be used in programs. Your <code>count('-') == 0</code> check is unnecessarily inside the <code>for i</code> loop. If you move it after the loop, you could use <code>break</code> to exit the main loop. You could add an <code>else</code> clause to the main <code>with</code> statement for dealing with the \"You've been hanged\" case. The main loop becomes:</p>\n\n<pre><code>while sizeHangman &lt; MAX:\n print('This is your hangman:' + HANGMAN[sizeHangman] + '\\nThis is the word:\\n' + ''.join(hiddenWord) + '\\nThese are the letters you\\'ve already guessed:\\n' + str(lettersGuessed))\n while True:\n guess = input('Guess a letter: ').lower()\n if guess in lettersGuessed:\n print('You\\'ve already guessed that letter!')\n else:\n break\n if guess in word:\n print('Well done, \"' + guess + '\" is in my word!')\n for i, letter in enumerate(word):\n if guess == letter:\n hiddenWord[i] = guess\n if '-' not in hiddenWord:\n print('Congratulations! My word was ' + word + '!')\n break\n else:\n print('Unfortunately, \"' + guess + '\" is not in my word.')\n sizeHangman += 1\n lettersGuessed.append(guess)\nelse:\n print('This is your hangman: ' + HANGMAN[sizeHangman] + 'You\\'ve been hanged! My word was actually ' + word + '.')\ninput('Press &lt;enter&gt; to close.')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T13:36:26.593", "Id": "23733", "ParentId": "23678", "Score": "6" } }, { "body": "<p>Some ideas:</p>\n\n<ul>\n<li><p>You might want to make sure that the guess is actually a single letter.</p></li>\n<li><p><code>lettersGuessed</code> should be a <em>set</em>, so membership tests (<code>guess in lettersGuessed</code>) is a constant time operation.</p></li>\n<li><p>Similarly, you could store either the (correctly) guessed letters or the letters that still have to be (correctly) guessed in a set. For example:</p>\n\n<pre><code>word = random.choice(WORDS)\nrequiredGuesses = set(word)\nlettersGuessed = set()\n\n# then later\nif guess in lettersGuessed:\n print('You already guessed this')\nelif guess in requiredGuesses:\n print('Correct guess!')\n requiredGuesses.remove(guess)\n lettersGuessed.add(guess)\nelse:\n print('Incorrect guess')\n</code></pre>\n\n<p>This also makes the test if the whole word was guessed easier:</p>\n\n<pre><code>if not requiredGuesses:\n print('You found the word')\n</code></pre></li>\n<li><p>Instead of keeping a <code>hiddenWord</code> which you keep adjusting whenever a correct guess is made, you could just create the hidden output on the fly:</p>\n\n<pre><code>print(''.join('-' if l in requiredGuesses else l for l in word))\n</code></pre></li>\n<li><p>You might want to add a class for this game that encapsulates some of the game logic.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-25T00:44:26.487", "Id": "38054", "ParentId": "23678", "Score": "3" } }, { "body": "<p>You should implement the ability to read words from a txt document. This can be done by:</p>\n\n<pre><code>f = open(\"wordlist.txt\", 'w')\nword_list.append(f.readlines())\n</code></pre>\n\n<p>this would allow you to have far bigger lists to choose from.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-06T21:40:30.857", "Id": "149149", "ParentId": "23678", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T21:43:33.187", "Id": "23678", "Score": "6", "Tags": [ "python", "optimization", "game", "python-3.x", "hangman" ], "Title": "Hangman in Python" }
23678
<p><strong>Update:</strong> Great answers up to now, but I would still love to have a bit of review about possibility of variable caching and the filter I'm using for rows and page sets!</p> <hr> <p>After seeing a lot of Paginator plugin that never fit my needs, I've decided to create my own. I have followed the <a href="http://docs.jquery.com/Plugins/Authoring" rel="nofollow noreferrer">jQuery Authoring advices</a>.</p> <p><strong>Configuration prerequisites:</strong></p> <ol> <li>The plugin CSS have to be fully configurable, thus classes name have to be dynamic.</li> <li>The plugin text/html on buttons else than page number have to be configurable.</li> <li>The number of buttons and the number of elements on a page have to be configurable.</li> <li>The configuration can be done by <code>data-</code> or by JavaScript.</li> </ol> <p><strong>Other prerequisites :</strong></p> <ol> <li>The plugin have to build his own html.</li> <li>Basic plugin functions can be called after initialization : <ul> <li>update (to cast a showPage (example: the table order get modified by a sorter, and you want to refresh the row shown)</li> <li>changeSettings (update dynamically plugin settings)</li> <li>destroy (remove the generated plugin html)</li> </ul></li> <li>The plugin private variables are accessed by only getter outside of the constructor.</li> <li>More than on table can get "paginated" on the page. And each table can have its own settings.</li> <li>As side-effect-less as possible</li> </ol> <p><strong>What to I think could get some improvement :</strong></p> <ul> <li>I'm not very used with JavaScript scope and even less when in a plugin. Thus there might be a lot of more variable caching that could be done. The thing is that we have to keep in mind that the table could change dynamically (adding removing rows) and that should not affect anything.</li> <li><p>The selector for the row shown and page set shown which looks ugly : </p> <pre>':eq(' + first + '),:eq(' + last + ')' + ',:lt(' + last + '):gt(' + first + ')'</pre></li> <li><p>The length of the file(?). I'm not very knowledgeable about good practices in JavaScript, and thus I would like to have your opinions. Should I cut it or let it like that?</p></li> </ul> <p>I do not think optimization is really an issue here as I haven't had any issue yet with the plugin being slow.</p> <p>I do think the code style is correct, but I am open to any suggestion has this is my first plugin. And if you have any else suggestion to make, feel free! I'm always happy to improve my coding practice and code.</p> <p><strong>Example of initialization the plugin :</strong></p> <pre><code>$(document).ready(function () { $('table').paginate({'elemsPerPage': 2, 'maxButtons': 6}) }); </code></pre> <p><a href="http://jsfiddle.net/dozoisch/5QB6p/" rel="nofollow noreferrer">Here is a live fiddle</a></p> <p><strong>Here is the code :</strong></p> <p>I know it's a bit long, but couldn't really reduce it.</p> <pre><code>(function ($, Math) { "use strict"; var prefix = 'paginate'; var defaults = { 'elemsPerPage': 5, 'maxButtons': 5, //Css classes 'disabledClass': prefix + 'Disabled', 'activeClass': prefix + 'Active', 'containerClass': prefix + 'Container', 'listClass': prefix + 'List', 'previousClass': prefix + 'Previous', 'nextClass': prefix + 'Next', 'previousSetClass': prefix + 'PreviousSet', 'nextSetClass': prefix + 'NextSet', 'showAllClass': prefix + 'ShowAll', 'pageClass': prefix + 'Page', 'anchorClass': prefix + 'Anchor', //Text on buttons 'previousText': '&amp;laquo;', 'nextText': '&amp;raquo;', 'previousSetText': '&amp;hellip;', 'nextSetText': '&amp;hellip;', 'showAllText': '&amp;dArr;' }; var methods = { init: function (options) { var table = $(this); if (table.data(prefix)) { return; } var paginator = new Paginator(this, options); table.data(prefix, paginator); }, update: function (pageNumber) { $(this).data(prefix).showPage(pageNumber || 1); }, changeSettings: function (options) { $(this).data(prefix).updateConfig(options || {}).showPage(1); }, destroy: function () { var elem = $(this); elem.data(prefix).destroy(); elem.removeData(prefix); } }; $.fn.paginate = function (args) { return this.each(function () { if (methods[args]) { return methods[args].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof args === 'object' || !args) { return methods.init.apply(this, [args]); } else { $.error('Incorrect usage of jQuery.Paginate'); } }); }; var Paginator = function (element, options) { var table = $(element); var config = $.extend({}, defaults, table.data() || {}, options || {}); var container = null; this.getConfig = function () { return config; }; this.getContainer = function () { return container; }; this.getTable = function () { return table; }; this.getSelector = function (name) { if ($.isArray(name)) { var response = ''; for (var index in name) { response += this.getSelector(name[index]); } return response; } return '.' + config[name + 'Class']; }; this.updateConfig = function (settings) { $.extend(config, settings); return this; }; this.destroy = function () { container.remove(); return table; }; container = new Builder(this); table.before(container); this.showPage(1); }; Paginator.prototype.previousPage = function () { var previousPageNumber = parseInt( this.getContainer().find(this.getSelector(['page', 'active'])).children('a').text()) - 1; if (isNaN(previousPageNumber)) { previousPageNumber = 1; } this.showPage(previousPageNumber); return this; }; Paginator.prototype.nextPage = function () { var nextPageNumber = parseInt(this.getContainer().find( this.getSelector(['page', 'active'])).children('a').text()) + 1; if (isNaN(nextPageNumber)) { nextPageNumber = 1; } this.showPage(nextPageNumber); return this; }; Paginator.prototype.previousSet = function () { var previousPage = parseInt(this.getContainer().find( this.getSelector('page')).filter(visibleFilter).first().children('a').text()) - 1; this.showSet(previousPage); return this; }; Paginator.prototype.nextSet = function () { var nextPage = parseInt(this.getContainer().find( this.getSelector('page')).filter(visibleFilter).last().children('a').text()) + 1; this.showSet(nextPage); return this; }; Paginator.prototype.showAll = function () { var config = this.getConfig(); var container = this.getContainer(); this.getTable().find('tbody tr').show(); container.find(this.getSelector('active')).removeClass(config['activeClass']); container.find(this.getSelector('showAll')).addClass(config['activeClass']); container.find(this.getSelector('previous')).addClass(config['disabledClass']); container.find(this.getSelector('next')).addClass(config['disabledClass']); return this; }; /** * * @param {int} pageNumber 1indexed * @returns {_L1.Paginator.prototype} */ Paginator.prototype.showPage = function (pageNumber) { var config = this.getConfig(); var container = this.getContainer(); var tableTr = this.getTable().find('tbody tr'); var maxPageNumber = Math.ceil(tableTr.length / config['elemsPerPage']); if (pageNumber &gt; maxPageNumber) { pageNumber = maxPageNumber; } else if (pageNumber &lt; 1) { pageNumber = 1; } container.find(this.getSelector('disabled')).removeClass(config['disabledClass']); if (pageNumber === 1) { container.find(this.getSelector('previous')).addClass(config['disabledClass']); } else if (pageNumber === maxPageNumber) { container.find(this.getSelector('next')).addClass(config['disabledClass']); } var zeroIndexPN = pageNumber - 1; container.find(this.getSelector('active')).removeClass(config['activeClass']); container.find(this.getSelector('page')).eq(zeroIndexPN).addClass(config['activeClass']); tableTr.hide(); var firstRow = (zeroIndexPN) * config['elemsPerPage']; var lastRow = firstRow + config['elemsPerPage']; tableTr.filter(':eq(' + firstRow + '),:lt(' + lastRow + '):gt(' + firstRow + ')').show(); //Adjust the set this.showSet(pageNumber); return this; }; /** * * @param {integer} pageNumber 1 indexed. * @returns {_L1.Paginator.prototype} */ Paginator.prototype.showSet = function (pageNumber) { var config = this.getConfig(); var container = this.getContainer(); // Zero Indexed --pageNumber; var numberOfPage = Math.ceil(this.getTable().find('tbody tr').length / config['elemsPerPage']) - 1; // 2 buttons (previous, next sets) + 1 the first button var maxButtons = config['maxButtons'] - 3; var firstPageToShow = Math.ceil(pageNumber - maxButtons / 2); var lastPageToShow = firstPageToShow + maxButtons; container.find(this.getSelector('previousSet')).show(); container.find(this.getSelector('nextSet')).show(); if (firstPageToShow &lt;= 1) { ++maxButtons; firstPageToShow = 0; lastPageToShow = firstPageToShow + maxButtons; container.find(this.getSelector('previousSet')).hide(); } else if (lastPageToShow &gt;= (numberOfPage - 1)) { ++maxButtons; lastPageToShow = numberOfPage; firstPageToShow = (numberOfPage &gt; maxButtons) ? numberOfPage - maxButtons : 0; container.find(this.getSelector('nextSet')).hide(); } var pages = container.find(this.getSelector('page')); pages.hide(); pages.filter(':eq(' + firstPageToShow + '),:eq(' + lastPageToShow + ')' + ',:lt(' + lastPageToShow + '):gt(' + firstPageToShow + ')').show(); return this; }; // NEW BUILDER ------------------------------- var Builder = function (paginate) { var config = paginate.getConfig(); var container = paginate.getContainer(); var create = function (name, attr) { if (typeof attr === 'string') { attr = {'class': attr}; } return $('&lt;' + name + '&gt;', attr || {}); }; var createLi = function (type, content) { return create('li', { 'class': config[type + 'Class'], 'html': create('a', { 'class': config.anchorClass, 'html': content || config[type + 'Text'] }) }); }; var tableLength = paginate.getTable().find('tbody tr').length; var numberOfPage = Math.ceil(tableLength / config.elemsPerPage); var inNeedOfSetButtons = false; if (numberOfPage &gt; config.maxButtons) { inNeedOfSetButtons = true; } container = create('div', config.containerClass); var list = new Array(numberOfPage + inNeedOfSetButtons * 2 + 2), index = 0; list[index++] = createLi('previous').click(function (e) { e.preventDefault(); paginate.previousPage.apply(paginate); }); if (inNeedOfSetButtons) { list[index++]= createLi('previousSet').click(function (e) { e.preventDefault(); paginate.previousSet.apply(paginate); }); } for (var i = 1; i &lt;= numberOfPage; i++) { list[index++] = createLi('page', i).click(function (e) { e.preventDefault(); paginate.showPage.apply(paginate, [parseInt($(this).text())]); }); } if (inNeedOfSetButtons) { list[index++] = createLi('nextSet').click(function (e) { e.preventDefault(); paginate.nextSet.apply(paginate); }); } list[index++] = createLi('next').click(function (e) { e.preventDefault(); paginate.nextPage.apply(paginate); }); var listObj = create('ul', config.listClass); listObj.append(list); container.append( [ listObj, create('ul', config['showAllListClass']).append( createLi('showAll').click(function (e) { e.preventDefault(); paginate.showAll.apply(paginate); })) ]); return container; }; function visibleFilter () { return $(this).css('display') !== 'none'; } })(jQuery, Math); </code></pre> <hr> <p><strong>EDIT :</strong> After comments, I've updated the builder. Let me know what you think about it. The old version is still in the <a href="http://jsfiddle.net/dozoisch/5QB6p/" rel="nofollow noreferrer">JsFiddle</a>.</p> <p><em>Note: I posted a <a href="https://codereview.stackexchange.com/questions/23680/css-good-practice-on-a-javascript-pugin">question for the CSS</a> as the issues of CSS and JavaScript are really not related, thus no need to mention CSS style it here.</em></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-03T02:35:07.817", "Id": "137459", "Score": "0", "body": "I'm closing this as the question is now harder to follow for future visitors and reviewers, and the updated answer prevents this question's update from being justifiably reversed." } ]
[ { "body": "<p>You do have a lot of code for review so here are some quite general suggestions:</p>\n\n<p>Code length shouldn't be a problem when you minify/gzip. Even though it is 300+ lines. If you can reduce more, power to you! I see you've used prototypes well and that should have already reduced quite a bit. Maybe focus on the Builder constructor for future reduces, as I do see some very similar, but not repeated, code there. The main thing I'm concerned in Builder is all the appends. What you might want to do is separate your tests, and set variables with the results, then call a single (or fewer) appends if at all possible. You avoided a common beginner mistake of putting an append in a loop so kudos to you.</p>\n\n<p>Some reading materials for appends which I recommend:\n<a href=\"http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly\" rel=\"nofollow\">http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly</a>\n<a href=\"http://rune.gronkjaer.dk/en-US/2010/08/14/jquery-append-speed-test/\" rel=\"nofollow\">http://rune.gronkjaer.dk/en-US/2010/08/14/jquery-append-speed-test/</a></p>\n\n<p>I'll add more to this answer concerning the rest of your plugin as I get some more time. One last thing that can help you with scopes is if you use Chrome Dev tools and set breakpoints, on the right you can see scope variables and a whole lot more.</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>I've seen your update and refactored parts of the Builder for ya. Here's the <a href=\"http://jsfiddle.net/5QB6p/4/\" rel=\"nofollow\">Fiddle</a>. The parts I've edited follow:</p>\n\n<pre><code>//Edits start here\ncontainer = create('div', config.containerClass);\nvar list = [numberOfPage + inNeedOfSetButtons * 2 + 2], //Use the bracket notation instead: var list = [...];\n index = 0,\n prevOrNext = [\"previous\", \"next\"]; //Two mainly used values\n\n$.each(prevOrNext, function(n, v) { //Reduced your code. Read jQuery.each docs for clarification.\n list[index++] = createLi(v).on('click', function(e) {\n e.preventDefault();\n paginate[v + \"Page\"].apply(paginate);\n });\n});\n\nif (inNeedOfSetButtons) {\n $.each(prevOrNext, function(n, v) {\n list[index++] = createLi(v + 'Set').on('click', function(e) {\n e.preventDefault();\n paginate[v + \"Set\"].apply(paginate);\n });\n });\n}\n\nfor (var i = 1; i &lt;= numberOfPage; i++) {\n list[index++] = createLi('page', i).on('click', function (e) {\n e.preventDefault();\n paginate.showPage.apply(paginate, [parseInt($(this).text())]);\n });\n}\n\nlist[list.length] = list[3]; //Move the nextSet to end.\nlist[list.length +1] = list[1]; //Move paginateNext item to the end.\nvar listObj = create('ul', config.listClass);\nlistObj.append(list);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T15:07:00.103", "Id": "23912", "ParentId": "23679", "Score": "1" } }, { "body": "<p>Some minor things I did not see mentioned before:</p>\n\n<ul>\n<li><code>.nextPage()</code> refers to config, and then does not use it</li>\n<li><code>.previousSet()</code> refers to config, and then does not use it</li>\n<li><code>.nextPage()</code> is using the UI to determine the next page, meaning that you violate MVC here. <code>currentPage</code> should be a property of your class with a getter/setter</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T19:32:07.500", "Id": "37421", "Score": "0", "body": "You are right about \"refers to config\" then does not use it! It's caused by some refactor, where I forgot to remove the unused var! Might want to edit the word **MVC** not sure thats the word you wanted since this plugin is not MVC!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T19:35:11.137", "Id": "37422", "Score": "1", "body": "I mean that you store state information 'which page are we on' not in your class, you use the UI as a means to know where you are, and hence you are not separating the UI and state(model) concerns." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T19:28:46.770", "Id": "24259", "ParentId": "23679", "Score": "0" } } ]
{ "AcceptedAnswerId": "23912", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T21:51:35.267", "Id": "23679", "Score": "3", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "jQuery Object Oriented Plugin" }
23679
<p>I've realized a jQuery Plugin recently and made a basic default CSS for it.</p> <p>As I'm mainly a server-side guy, I'm not too familiar with CSS and would like to have insight about what could be improved.</p> <p>The main issues I've targeted are :</p> <ul> <li>Are the CSS selectors appropriate, knowing that this CSS is meant to be on a plugin and to be side-effect-less as much as possible.</li> <li>Are the property usages appropriate or are there better way of using some of the properties I have used.</li> </ul> <p>Any suggestion of code style is also highly appreciated!</p> <p><a href="http://jsfiddle.net/dozoisch/5QB6p/" rel="nofollow noreferrer">Here is a working fiddle</a></p> <p><strong>Here is the css :</strong></p> <pre><code>div.paginateContainer { display : block; text-align: center; } div.paginateContainer &gt; ul.paginateList{ display: inline-block; } div.paginateContainer &gt; ul &gt; li{ display: inherit; } div.paginateContainer &gt; ul &gt; li &gt; a.paginateAnchor{ font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; text-decoration: none; cursor: pointer; line-height: 20px; padding: 4px 12px; background-color: #ddd; color: #08c; font-size : 16px; min-width: 16px; float: left; border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; /* Select None */ -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } div.paginateContainer &gt; ul &gt; li &gt; a.paginateAnchor:hover { color : #fff; background-color: #2ae; border-top: 1px solid #2ae; border-bottom: 1px solid #2ae; } div.paginateContainer &gt; ul:first-child &gt; li.paginatePrevious &gt; a{ border-top-left-radius: 10px; border-bottom-left-radius: 10px; border: 1px solid #ccc; font-size : 18px; font-weight: bold; } div.paginateContainer &gt; ul:first-child &gt; li.paginatePrevious &gt; a:hover { border: 1px solid #2ae; } div.paginateContainer &gt; ul:first-child &gt; li.paginateNext &gt; a { border-top-right-radius: 10px; border-bottom-right-radius: 10px; border: 1px solid #ccc; font-size : 18px; font-weight: bold; } div.paginateContainer &gt; ul:first-child &gt; li.paginateNext &gt; a:hover { border: 1px solid #2ae; } div.paginateContainer &gt; ul:last-child &gt; li &gt; a { border-radius: 10px; font-size: 18px; font-weight: bold; } div.paginateContainer ul.paginateList:last-child { float: right; } div.paginateContainer &gt; ul &gt; li.paginateActive &gt; a, div.paginateContainer &gt; ul &gt; li.paginateActive &gt; a:hover { color : #fff; cursor: default; background-color: #08c; border-top: 1px solid #08c; border-bottom: 1px solid #08c; } div.paginateContainer &gt; ul:first-child &gt; li.paginateDisabled &gt; a, div.paginateContainer &gt; ul:first-child &gt; li.paginateDisabled &gt; a:hover { color : #bbb; background-color: #eee; cursor: default; border: 1px solid #ddd; } </code></pre> <p><em>Note that I've posted a <a href="https://codereview.stackexchange.com/questions/23679/jquery-object-oriented-plugin">question to review the JavaScript</a> also, so this post is only about CSS. The JavaScript having no real dependency with the CSS in this case.</em></p>
[]
[ { "body": "<p>You styles are pretty solid, it's mainly your selectors that have issues I feel. Here are some notes:</p>\n\n<ul>\n<li><p>It's normally best to not include the type of element if it has a class. This is for maintainability and extensibility purposes, you could switch in <code>&lt;ol&gt;</code> for <code>&lt;ul&gt;</code> with less work for example. Inversely, if all <code>&lt;ul&gt;</code>'s have the same style, they don't even need the same class.</p></li>\n<li><p>You never want to go too deep with you CSS selectors, more specific is less flexible.</p>\n\n<pre><code>/* Bad */\ndiv.paginateContainer &gt; ul &gt; li.paginateActive &gt; a\n\n/* Good*/\n.paginateContainer .paginateActive a\n</code></pre></li>\n<li><p>Avoid the use of the direct descendant <code>&gt;</code> selector where ever possible, again it just locks your CSS down and makes it less flexible. I recommend only ever using this if you need it to add styles to a legacy application or have a situation where you have a hierarchy something like this that doesn't make sense to add different classes.</p>\n\n<pre><code>&lt;ul class=\"menu\"&gt;\n &lt;li&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>These target different elements</p>\n\n<pre><code>.menu &gt; li { /* ... */}\n.menu li { }\n</code></pre>\n\n<p>See in this situation putting a <code>.submenu</code> class on the inner <code>&lt;ul&gt;</code> won't make a different, <code>.menu li</code> will still target both.</p></li>\n<li><p>Try to keep your selectors consistent, for example you refer to both <code>ul.paginateList</code> and <code>ul</code> to mean the same thing.</p></li>\n<li><p>I would add a different class to your first <code>&lt;ul&gt;</code> so you don't need to refer to it as <code>ul:first-child</code>, you may want to change the order in the future for example. Maybe only include <code>.paginateList</code> on the first <code>&lt;ul&gt;</code>.</p></li>\n<li><p>Due to your use of specific pixel font sizes your plugin may require modification in order to be used on someone's site. Generally these days we use 'ems' which represent the size of the character 'M'. Currently your font-size is fixed at <code>18px</code> and it will not change whatever site you put it on, using <code>font-size:1.2em</code> for example would scale to be 20% larger than the font-size of the element containing <code>.paginateContainer</code>. </p>\n\n<p>It also allows for better mobile support, taking advantage of the default font size set by the user. This does require a bit of work though as you should apply it to <code>padding</code>, <code>border-radius</code>, <code>line-height</code>, <code>font-size</code> and <code>min-width</code> (everything except <code>border-size</code>).</p></li>\n</ul>\n\n<p>And here is your modified CSS</p>\n\n<pre><code>.paginateContainer {\n display : block;\n text-align: center;\n}\n\n\n.paginateContainer ul {\n display: inline-block;\n}\n\n.paginateContainer li {\n /* Better to state the display explicitly */\n /*display: inherit;*/\n display:inline-block;\n}\n\n.paginateContainer a {\n font-family: \"Helvetica Neue\",Helvetica,Arial,sans-serif;\n text-decoration: none;\n\n /* Put the cursor rule on :hover */\n /*cursor: pointer;*/\n\n line-height: 20px;\n padding: 4px 12px;\n background-color: #ddd;\n color: #08c;\n font-size : 16px;\n min-width: 16px;\n float: left;\n\n border-top: 1px solid #ccc;\n border-bottom: 1px solid #ccc;\n\n /* Select None */\n -webkit-touch-callout: none;\n -webkit-user-select: none;\n -khtml-user-select: none;\n -moz-user-select: none;\n -ms-user-select: none;\n user-select: none;\n}\n\n.paginateContainer a:hover {\n color : #fff;\n background-color: #2ae;\n border-top: 1px solid #2ae;\n border-bottom: 1px solid #2ae;\n cursor:pointer;\n}\n\n.paginateContainer ul:first-child .paginatePrevious a {\n border-top-left-radius: 10px;\n border-bottom-left-radius: 10px;\n border: 1px solid #ccc;\n font-size : 18px;\n font-weight: bold;\n}\n\n.paginateContainer ul:first-child .paginatePrevious a:hover {\n border: 1px solid #2ae;\n}\n\n.paginateContainer ul:first-child .paginateNext a {\n border-top-right-radius: 10px;\n border-bottom-right-radius: 10px;\n border: 1px solid #ccc;\n font-size : 18px;\n font-weight: bold;\n}\n\n.paginateContainer ul:first-child .paginateNext &gt; a:hover {\n border: 1px solid #2ae;\n}\n\n.paginateContainer ul:last-child a {\n border-radius: 10px;\n font-size: 18px;\n font-weight: bold;\n}\n\n.paginateContainer ul:last-child {\n float: right;\n}\n\n.paginateContainer .paginateActive a,\n.paginateContainer .paginateActive a:hover {\n color : #fff;\n cursor: default;\n background-color: #08c;\n border-top: 1px solid #08c;\n border-bottom: 1px solid #08c;\n}\n\n.paginateContainer ul:first-child .paginateDisabled a, \n.paginateContainer ul:first-child .paginateDisabled a:hover {\n color : #bbb;\n background-color: #eee;\n cursor: default;\n border: 1px solid #ddd;\n}\n</code></pre>\n\n<p><strong>EDIT:</strong> As for you question about why I've used <code>&lt;a&gt;</code> tags instead of the class. It's a similar situation to why I've referred to your lists as <code>ul</code> and not <code>.paginateList</code>, the class literally provides no additional information because every single <code>&lt;a&gt;</code> tag has the class present. Changing it to use <code>a</code> instead of <code>.paginateAnchor</code> will make both your HTML and CSS more lightweight.</p>\n\n<p>I also noticed just now that you're using inline styles applied with your JavaScript.</p>\n\n<p><img src=\"https://i.stack.imgur.com/zGbhV.png\" alt=\"Inline styles\"></p>\n\n<p>This would be an ideal situation to use classes, the elements that are <code>inline-block</code> can have no class (which will use <code>div.paginateContainer &gt; ul &gt; li { display:inherit; }</code>) and the hidden elements can have a class called <code>.hidden</code>. The reasoning for this is separation of concerns, your JavaScript should not need to do any styling, instead it should offload that detail to your CSS so everything is in one place.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T15:54:10.697", "Id": "36539", "Score": "0", "body": "First, thank you for your answer it's really insightful! I have a question. You talk about using classes instead of elements. You do that for everything except the anchor elements. Is there a reason why specifically for this element? Also would you mind finishing the sentence \"I recommend only ever using this if you have\" You seem to bring an important point but you forgot to end it!! I'll let a few day pass and will mark it as accepted afterwards" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T01:39:12.033", "Id": "36568", "Score": "0", "body": "@HugoDozois I was jumped around a bit when I wrote it, I guess I missed that part :) updated the answer to talk about direct descendant, `a` vs class and styles applied with js." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T01:45:52.887", "Id": "36569", "Score": "0", "body": "About the `.foo > .bar` selector - it is beneficial in terms of performance - broswers will look for `.foo` only on `.bar` parent instead of navigating the whole DOM tree to the root. Also specificity makes your css more solid - instead of losing flexibility (with all due exceptions of course - e.g. over-qualified selectors)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T01:50:03.950", "Id": "36570", "Score": "0", "body": "@Luca I actually mentioned that in a post on StackOverflow and got downvoted a bunch. While it is true, you'll find that most of the CSS community is against it because it prevents you from thinking in a modular and reusable way. The performance of CSS is pretty insignificant anyhow unless the page is gigantic or you're using CSS3 animations/transitions/transforms/etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T01:55:04.173", "Id": "36572", "Score": "0", "body": "@Tyriar the inline styles are caused by `show()` `hide()` methods. While I agree I could have used an hidden class, the code is clearer using show and hide and is independent of the css style sheet. While as if there is an hidden class css needed, the user has to include my style sheet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T01:55:20.993", "Id": "36573", "Score": "0", "body": "@tyriar downloaded a bunch, sometimes I struggle to understand the so called community!! it's no brainer that `ul > li` is better and clearer than `ul li` - unless `ul li` is *needed* but then wouldn't you use a class with a semantic name instead? I'm all for modular and reusable CSS, but I don't understand the extremism of \"never use this or that\" - just use it the right way. Good points overall in your answer anyway :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T02:22:36.783", "Id": "36574", "Score": "0", "body": "@Luca extremism can force you into better practice behaviour though. I very rarely style with IDs any more every since reading this CSS-Tricks article and my CSS has definitely become better as it makes you think about it. http://css-tricks.com/a-line-in-the-sand/ It's all a trade-off between performance and maintainability though, much like pretty much every problem in software development. Low-level highly optimised code is harder to maintain, same with CSS." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T05:52:19.980", "Id": "23687", "ParentId": "23680", "Score": "4" } } ]
{ "AcceptedAnswerId": "23687", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-09T22:11:15.613", "Id": "23680", "Score": "6", "Tags": [ "css", "plugin" ], "Title": "CSS Good Practice on a JavaScript Plugin" }
23680
<p>Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.</p> <p>For example,</p> <pre><code>Given 1-&gt;2-&gt;3-&gt;3-&gt;4-&gt;4-&gt;5, return 1-&gt;2-&gt;5. Given 1-&gt;1-&gt;1-&gt;2-&gt;3, return 2-&gt;3. </code></pre> <p>The following is my code:</p> <pre><code>ListNode *getNextElement(ListNode *head, bool&amp; repeated){ while ((head-&gt;next) != NULL &amp;&amp; (head-&gt;val == head-&gt;next-&gt;val)){ head = head-&gt;next; repeated = true; } return head-&gt;next; } ListNode *deleteDuplicates(ListNode *head) { ListNode *result = NULL; ListNode *copy_result = result; ListNode *next = NULL; for (ListNode *cur = head; cur != NULL; cur = next){ bool cur_repeat = false; next = getNextElement(cur, cur_repeat); if (cur_repeat == true){ while(cur!=next){ ListNode *toFree = cur; cur = cur-&gt;next; delete toFree; } } else{ if(result == NULL){ result = cur; copy_result = result; } else{ result-&gt;next = cur; result = result-&gt;next; } } } if(result != NULL) result-&gt;next = NULL; return copy_result; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T02:43:06.650", "Id": "36516", "Score": "0", "body": "This is the same question as your previous one. Why do that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T04:29:36.160", "Id": "36522", "Score": "0", "body": "it's not the same one. The previous one keeps the duplicate(only one)." } ]
[ { "body": "<p>Iterate through the list and remember the pointer to the first element in the group node. Then check if the current element has the same value as the first element in the group. Remove the current element and set some flag to remember to remove the first element in this group. Then if you have a new value, set the first element pointer to this value and do it all over again.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T01:15:50.110", "Id": "23684", "ParentId": "23683", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T00:43:57.510", "Id": "23683", "Score": "1", "Tags": [ "c++", "interview-questions", "linked-list" ], "Title": "remove all nodes with same value in a linked list" }
23683
<p>I need to join source-specific multicast group and receive data. When I don't need to receive data anymore, I need to leave the group and disconnect the socket.</p> <p>Am I doing everything right? In particular, is this order of actions in <code>Disconnect</code> correct and complete?</p> <ol> <li>Leave the group</li> <li>Call <code>shutdown</code> for socket</li> <li>Call <code>closesocket</code> for socket</li> </ol> <p></p> <pre><code>int join_ssm_group(int s, UINT32 group, UINT32 source, UINT32 inter) { struct ip_mreq_source imr; imr.imr_multiaddr.s_addr = group; imr.imr_sourceaddr.s_addr = source; imr.imr_interface.s_addr = inter; return setsockopt(s, IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, (char *) &amp;imr, sizeof(imr)); } int leave_ssm_group(int s, UINT32 group, UINT32 source, UINT32 inter) { struct ip_mreq_source imr; imr.imr_multiaddr.s_addr = group; imr.imr_sourceaddr.s_addr = source; imr.imr_interface.s_addr = inter; return setsockopt(s, IPPROTO_IP, IP_DROP_SOURCE_MEMBERSHIP, (char *) &amp;imr, sizeof(imr)); } void Receiver::ConnectSocket() { // Make socket socketId = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); sockaddr_in Sender; int SenderAddrSize = sizeof(Sender); struct sockaddr_in binda; // Bind it to listen appropriate UDP port binda.sin_family = AF_INET; binda.sin_port = htons(port); binda.sin_addr.s_addr = htonl(INADDR_ANY); bind(socketId,(struct sockaddr*)&amp;binda, sizeof(binda)); // Join to group join_ssm_group(socketId, group, source, INADDR_ANY); } void Receiver::DisconnectSocket() { leave_ssm_group(socketId, group, source, INADDR_ANY); int iResult = shutdown(socketId, SD_BOTH); if (iResult == SOCKET_ERROR) { printf("shutdown failed: %d\n", WSAGetLastError()); } closesocket(socketId); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-11-10T15:17:02.690", "Id": "453162", "Score": "0", "body": "Can you please supply test cases in code to show how these functions are used? Right now the question can be closed as off-topic due to Lack of Concrete Context." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T08:17:55.813", "Id": "23688", "Score": "2", "Tags": [ "c++", "socket" ], "Title": "Join / leave source-specific multicast group and connect / disconnect corresponding socket" }
23688
<p>In my system I frequently require data by Ajax requests. For example, different lists, content of modal dialogs, etc. This data can't be changed after request, so I wrote cache mechanism which stores Ajax result and then before Ajax request checks is there stored data. Here is example:</p> <pre><code>YFeX.cache = { }; // YFex is my own namespace $('#account_modal_button').click(function () { if (YFeX.cache.account_modal !== undefined) { YFeX.modal(YFeX.cache.account_modal.title, YFeX.cache.account_modal.body); } else { $.ajax({ type:'GET', url:'/?/login', dataType:'json', context:$(this), success:function (data) { YFeX.cache.account_modal = data.modal; // YFeX.modal will be called automatically } }); } return false; }); </code></pre> <p>Are there any 'bad' parts in my solution?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T11:32:20.377", "Id": "36530", "Score": "1", "body": "Not much to improve in just the couple of lines, but why not use browser's default caching?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T11:43:14.217", "Id": "36531", "Score": "0", "body": "@Juhana but Ajax request is executed in any case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T15:22:48.320", "Id": "36536", "Score": "0", "body": "No, it isn't. That's the whole point of cache." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T17:04:49.987", "Id": "36542", "Score": "1", "body": "Doesn't [jQuery already have a cache mechanism](http://api.jquery.com/jQuery.ajax/) for it's AJAX functions? Adding `cache : true` should cache the response internally in jQuery. True, the AJAX routine still needs to be called. But if jQuery determines that there is cached data, probably it will not make a request and the response of the call will be from the cache." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T18:03:45.360", "Id": "36545", "Score": "0", "body": "@JosephtheDreamer I already tried set `cache` to `true`, but Firegug shows that Ajax request still sent." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T18:04:26.543", "Id": "36546", "Score": "0", "body": "@Juhana can you give an example?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T18:05:59.227", "Id": "36547", "Score": "0", "body": "It's not enough to set `cache: true`, the server must also send the correct headers. `cache: false` makes sure the response is not cached, but `cache: true` can't override the server instructions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T19:19:16.603", "Id": "36550", "Score": "0", "body": "@Juhana oh, thank you, now I understand how to use HTTP cache... If you want — answer my question and I will mark it is accepted." } ]
[ { "body": "<p>From a once over;</p>\n\n<ul>\n<li>Unless <code>YFeX</code> is also a constructor, it should be <code>yFex</code></li>\n<li>lowerCamelCase is good for you: <code>account_modal</code> -> <code>accountModal</code></li>\n<li>I would store <code>YFeX.cache.account_modal</code> into a <code>var cachedAccountModal</code> so that you do not have to repeat <code>YFeX.cache.account_modal</code> all the time</li>\n<li>Your code is very optimistic, you should also deal with <code>fail</code></li>\n<li>Consider using the shorthand <code>$.get()</code></li>\n</ul>\n\n<p>Other than that, the code looks fine to me.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-23T10:20:07.013", "Id": "84122", "Score": "0", "body": "Oh, after a year I see my own mistakes.\nBut anyway thank you, it maybe helpful for someone...\n\nPS. `account_modal` means account[modal], I didn't want to create another arrays in `cache` array." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-10T17:43:49.980", "Id": "43956", "ParentId": "23691", "Score": "3" } } ]
{ "AcceptedAnswerId": "43956", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T10:00:04.230", "Id": "23691", "Score": "2", "Tags": [ "javascript", "jquery", "ajax", "cache" ], "Title": "Simple cache mechanism?" }
23691
<p>I have a Edit/Details form which has 4 user related fields. On click of Save, I save the edited fields to local storage (if supported) and display the same values in the Details view.</p> <p>Below is the code which does that;</p> <pre><code> var UserDataObj = { name:"John", email:"john@example.com", phone:"9999999999", desc:"some description" } /** * Check HTML5 Local Storage support */ function supports_html5_storage() { try { window.localStorage.setItem( 'checkLocalStorage', true ); return true; } catch ( error ) { return false; }; }; /** * Save form data to local storage */ function saveFormData() { if (supports_html5_storage()) { $(".formFieldUserData").each(function(){ UserDataObj[$(this).attr("name")] = $(this).val(); }); localStorage.setItem('UserDataObj', JSON.stringify(UserDataObj)); } } /** * Set field values based on local storage */ function setFormFieldValues() { if (supports_html5_storage()) { var retrievedUserDataObj = JSON.parse(localStorage.getItem('UserDataObj')); if(retrievedUserDataObj) { $(".formFieldUserData").each(function(){ var currentKey = $(this).attr("name"); var retrievedValue = retrievedUserDataObj[$(this).attr("name")] $("#"+currentKey).val(retrievedValue); $("#"+currentKey+"Txt").html(retrievedValue); }); } else { $(".formFieldUserData").each(function(){ var currentKey = $(this).attr("name"); var userDataObjValue = UserDataObj[$(this).attr("name")] $("#"+currentKey).val(userDataObjValue); $("#"+currentKey+"Txt").html(userDataObjValue); }); } } else { $(".formFieldUserData").each(function(){ var currentKey = $(this).attr("name"); if ($(this).val() != "") { var fieldValue = $(this).val(); $("#"+currentKey).val(fieldValue); $("#"+currentKey+"Txt").html(fieldValue); } else { var defaultuserDataObjValue = UserDataObj[$(this).attr("name")]; $("#"+currentKey).val(defaultuserDataObjValue); $("#"+currentKey+"Txt").html(defaultuserDataObjValue); } }) } } </code></pre> <p>My question is;</p> <ol> <li>This is a completely working code. But is there any further that I can do as far as best coding practices go.</li> <li>Also performance wise, can I do anything to improve the overall code?</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T11:53:43.330", "Id": "36532", "Score": "0", "body": "Note that this has been crossposted to [Stack Overflow](http://stackoverflow.com/questions/15321636/check-javascript-coding-practice-and-overall-performance) (where it is closed) and [Programmers](http://programmers.stackexchange.com/questions/190010/check-javascript-coding-practice-and-overall-performance) (where I think it is O/T)." } ]
[ { "body": "<ul>\n<li><p>You can start with how you code. Have them <a href=\"http://jsbeautifier.org/\" rel=\"nofollow\">indented properly</a> and checked by a <a href=\"http://www.jshint.com/\" rel=\"nofollow\">quality-check tool</a>. Code-review doesn't only deal with optimization, but also maintainability of your code and that includes making it readable.</p></li>\n<li><p>After running it in JSHint, I found some minor problems in your code. Most notable are missing semi-colons. Although semi-colons in line endings are optional in JS, it's still best practice to include them. You could also avoid code packer/compressor errors by actually putting them in. This avoids your lines from being connected to the next line.</p></li>\n<li><p>Use strict comparison as much as possible in JS. JS treats <a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Boolean#Description\" rel=\"nofollow\">\"falsy\" values</a> as <code>false</code>, which includes <code>null</code>, <code>undefined</code>, <code>0</code>, <code>false</code>, a blank string and <code>NaN</code>. For example, <code>`\"\" == false</code> is actually equal.</p></li>\n<li><p>Place your code in a namespace, or some inner-scope to avoid polluting the global scope.</p></li>\n</ul>\n\n<p>For code related stuff:</p>\n\n<pre><code>(function (ns, $) {\n \"use strict\"; //prevents \"bad practice\"\n\n //variables needed for localStorage test\n var storage, fail, uid;\n\n //For flexibility, it would be best if your code \n //wasn't build for a specific form only\n //instead, allow it to create instances and attach\n //to different forms with different default data\n function FormSave(selector, defaultValues) {\n this.defaultValues = defaultValues || {};\n this.dataName = selector;\n this.form = $(selector);\n this.userFields = $('.formFieldUserData', this.form);\n }\n\n //our save function\n FormSave.prototype.save = function () {\n\n var userData = {};\n\n //using the \"early return\" pattern to avoid further\n //code exectution if condition fails, and avoid\n //deep indentation\n if (!storage) {\n return;\n }\n\n //since each() assigns the current DOM element in\n //the collection as this, we can get name and value\n //directly from the DOM element, saving you function calls\n this.userFields.each(function () {\n userData[this.name] = this.value;\n });\n\n //set the items\n localStorage.setItem(this.dataName, JSON.stringify(userData));\n };\n\n //our setting function\n FormSave.prototype.set = function () {\n\n //cache the default values into this scope\n var defaultValues = this.defaultObject,\n retrievedValues;\n\n //if local storage is present, get and parse\n if (storage) {\n retrievedValues = JSON.parse(localStorage.getItem(this.dataName));\n }\n\n this.userFields.each(function () {\n\n //cache the current key\n var currentKey = this.name,\n //then the value to be used is:\n //if storage is present, use either the retrieved values or the default\n //if not, then use the present value or the default\n value = ((storage) ? retrievedValues[currentKey]: this.value) || defaultValues[currentKey];\n\n //for safe text insertion, use text() since it escapes the value first\n $(\"#\" + currentKey + \"Txt\").text(value);\n $(\"#\" + currentKey).val(value);\n });\n\n //our easy binding function exposed to our FormSave namespace\n ns.bind = function (selector) {\n return new FormSave(selector);\n };\n };\n\n //a quick test for localstorage\n //from: http://mathiasbynens.be/notes/localstorage-pattern\n try {\n uid = new Date();\n (storage = window.localStorage).setItem(uid, uid);\n fail = storage.getItem(uid) !== uid;\n storage.removeItem(uid);\n fail &amp;&amp; (storage = false);\n } catch (e) {}\n\n}(this.FormSave = this.FormSave || {}, jQuery));\n\n//usage:\n\n//bind this functionality to a form id'ed \"someForm\" with\n//the given default values\nvar someForm = FormSave.bind('#someForm', {\n name: 'John',\n email: 'john@example.com',\n phone: '9999999999',\n desc: 'some description'\n});\n\n//then with the given reference, call save and set\nsomeForm.save();\nsomeForm.set();\n</code></pre>\n\n<p>When packed, it's this small!</p>\n\n<pre><code>(function (ns, $) {\n \"use strict\";\n var storage, fail, uid;\n\n function FormSave(selector, defaultValues) {\n this.defaultValues = defaultValues || {};\n this.dataName = selector;\n this.form = $(selector);\n this.userFields = $('.formFieldUserData', this.form)\n }\n FormSave.prototype.save = function () {\n var userData = {};\n if (!storage) {\n return\n }\n this.userFields.each(function () {\n userData[this.name] = this.value\n });\n localStorage.setItem(this.dataName, JSON.stringify(userData))\n };\n FormSave.prototype.set = function () {\n var defaultValues = this.defaultObject,\n retrievedValues;\n if (storage) {\n retrievedValues = JSON.parse(localStorage.getItem(this.dataName))\n }\n this.userFields.each(function () {\n var currentKey = this.name,\n value = ((storage) ? retrievedValues[currentKey] : this.value) || defaultValues[currentKey];\n $(\"#\" + currentKey + \"Txt\").text(value);\n $(\"#\" + currentKey).val(value)\n });\n ns.bind = function (selector) {\n return new FormSave(selector)\n }\n };\n try {\n uid = new Date();\n (storage = window.localStorage).setItem(uid, uid);\n fail = storage.getItem(uid) !== uid;\n storage.removeItem(uid);\n fail &amp;&amp; (storage = false)\n } catch (e) {}\n}(this.FormSave = this.FormSave || {}, jQuery));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T14:45:33.693", "Id": "23695", "ParentId": "23693", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T11:30:51.510", "Id": "23693", "Score": "3", "Tags": [ "javascript", "jquery", "html", "html5" ], "Title": "Edit/Details form in JavaScript" }
23693
<p>The required output is stated just before the <code>main()</code> function. Is there a better way to achieve it? I feel like I am repeating code unnecessarily but am unable to find a better way to get the result. Not squeezing the code too much, like one liners, but reasonably using better logic.</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- #Time to play a guessing game. #Enter a number between 1 and 100: 62 #Too high. Try again: 32 #Too low. Try again: 51 #Too low. Try again: 56 #Congratulations! You got it in 4 guesses. import random def main(): return 0 if __name__ == '__main__': main() print("Time to play a guessing game.") val = random.randint(1, 100) guess = 0 count = 1 guess = input("\n\t\tEnter a number between 1 and 100: ") guess = int(guess) print("") print("randint is", val) print("") if (guess == val): print("\nCongratulations! You got it in", count, "guesses.") while(guess != val): if guess &gt; val: print("Too high. Try again:", guess) guess = input("\n\t\tEnter a number between 1 and 100: ") guess = int(guess) count = count + 1 if guess == val: print("\nCongratulations! You got it in", count, "guesses.") break elif guess &lt; val: print("Too low. Try again:", guess) guess = input("\n\t\tEnter a number between 1 and 100: ") guess = int(guess) count = count + 1 if guess == val: print("\nCongratulations! You got it in", count, "guesses.") break else: pass print("") </code></pre>
[]
[ { "body": "<ol>\n<li>The pythonic way to do <code>count = count + 1</code> is <code>count += 1</code></li>\n<li><p>You don't need to repeat the 'guess again' part of the game twice:</p>\n\n<pre><code>if guess &gt; val:\n print(\"Too high. Try again:\", guess) \nelif guess &lt; val:\n print(\"Too low. Try again:\", guess)\nguess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\ncount += 1\nif guess == val:\n print(\"\\nCongratulations! You got it in\", count, \"guesses.\")\n break\n</code></pre></li>\n<li><p>You don't need to add the extra <code>if</code> statement because if <code>guess != val</code>, then the loop with break anyway:</p>\n\n<pre><code>while guess != val:\n if guess &gt; val:\n print(\"Too high. Try again:\", guess) \n elif guess &lt; val:\n print(\"Too low. Try again:\", guess)\n guess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\n count += 1\nprint(\"Congratulations! You got it in\", count, \"guesses.\")\n</code></pre></li>\n<li><p>I think <code>print(\"randint is\", val)</code> was probably for testing purposes, but it's still in your code!</p></li>\n<li><p>If you execute your program outside the command module (I'm not quite sure what it's called), the program will close immediately after it's finished; it's always best to give the user the choice of when to quit, so insert this at the end of your code:</p>\n\n<pre><code>input(\"Press enter to quit\")\n</code></pre></li>\n<li><p>The first section is unneeded:</p>\n\n<pre><code>def main():`, `if __name__ == \"__main__\":\n</code></pre></li>\n<li><p>The first <code>if</code> statement is also unneeded:</p>\n\n<pre><code>if guess == val:\n</code></pre></li>\n<li><p>You don't need to define <code>guess = 0</code> the first time.</p></li>\n</ol>\n\n<p>So, all in all, my improvement of your code is:</p>\n\n<pre><code>import random\nprint(\"Time to play a guessing game.\")\nval = random.randint(1, 100)\ncount = 1 \nguess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\nwhile(guess != val): \n if guess &gt; val:\n print(\"Too high. Try again:\", guess) \n elif guess &lt; val:\n print(\"Too low. Try again:\", guess)\n guess = int(input(\"\\n\\t\\tEnter a number between 1 and 100: \"))\n count += 1\nprint(\"\\nCongratulations! You got it in \", count, \" guesses.\")\ninput(\"Press enter to quit.\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T01:01:52.480", "Id": "36567", "Score": "0", "body": "I'd use instead of `while guess != val:` is `elif guess == val` then break" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-27T06:14:20.910", "Id": "261599", "Score": "0", "body": "One minor thing: `while(guess != val):` can be changed to `while guess != val:`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T15:09:37.870", "Id": "23696", "ParentId": "23694", "Score": "10" } }, { "body": "<p>How about this:</p>\n\n<pre><code>import random\n\ndef main():\n print('Time to play a guessing game.')\n\n val = random.randint(1, 100)\n count = 0\n\n guess = int(input('\\n\\tEnter a number between 1 and 100: '))\n while True:\n count += 1\n if guess == val:\n print('\\nCongratulations! You got it in ', count, 'guesses.')\n break\n elif guess &gt; val:\n msg = 'Too high.'\n else:\n msg = 'Too low.'\n guess = int(input('{}\\tTry again: '.format(msg)))\n return 0\n\nmain()\n</code></pre>\n\n<p>Maybe you can draw a flow chart, which can help you get clearer control flow to avoid unnecessary repeating.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T04:01:03.217", "Id": "23713", "ParentId": "23694", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T14:43:48.083", "Id": "23694", "Score": "12", "Tags": [ "python", "game" ], "Title": "Guessing Game: computer generated number between 1 and 100 guessed by user" }
23694
<p>I've started to program a state machine on a PIC18F2550 microcontroller. In each state of my machine, there is a designated block of code that runs for a specific amount of real time, such as 20 or 30 seconds. To do this, I use a countdown timer that is decremented once every second. Depending on the state the machine is in, the value of countdown is used to control LEDs, beep speakers, put stuff on the LCD or to run some other dependent tasks (i.e. countdown is versatile; lots of different things at different times rely on it) Since these peripherals are far too slow to call in the interrupt, in my states I just turn the timer on and poll the countdown variable, then fire actions every second (or half second) based on that. This has worked almost perfectly so far.</p> <p>Understandably, by polling the variable and taking chunky amounts of time by writing to things like the LCD or speaker, I open myself up to being late to respond to the countdown variable when it's changed by the interrupt. Case in point: In one state of my machine I've got a flashing light that 'hiccups' every once in a while. </p> <p>Before I post a wall of code, the basic control flow of every state is summed up by this pseudocode:</p> <ol> <li>Update the LEDs</li> <li>Print the state to the LCD (which is daisy chained to the LED registers, so printing something to the LCD updates the LEDs too)</li> <li>Some states may then wait here, should the machine be manually (remotely) controlled. Remote control may cause it to branch out and go to a new state as indicated in a serial packet (changed within a high priority interrupt) </li> <li>If the machine is running automatically, or switches to automatic mode from manual mode, it loads and starts the countdown timer </li> <li>Inside the countdown loop, it frequently updates both the RTC and the countdown times on the LCD</li> <li>Events such as flashing an LED or beeping a speaker then fire every second or half second</li> <li>The timer runs out and is shut off within the interrupt; the loop exits. Update the screen again and figure out which state to go next. </li> </ol> <p>Here's an exerpt of my code. The hiccups occur in state 5: </p> <pre><code>#pragma interruptlow low_isr //Timers void low_isr(void){ if(INTCONbits.TMR0IF){ //Countdown timer update OvfT0++; if(OvfT0&lt;13){Tick = 0;} //For half second/flashing if(OvfT0&gt;13){Tick = 1;} if(OvfT0==25){ //1 second OvfT0=0; Countdown--; if(Countdown==0){ T0CONbits.TMR0ON = 0; } } TMR0H = 0x9F; TMR0L = 0xFF; //Preload counters with 40959 -&gt; 24576 ticks to overflow every 40ms INTCONbits.TMR0IF = 0; } if(PIR1bits.TMR1IF){ //RTC Update OvfT1++; if(OvfT1==25){ //25 overflows -&gt; 1 second OvfT1=0; RTCSec++; if(RTCSec==60){ RTCSec=0; RTCMin++; if(RTCMin==60){ RTCMin=0; RTCHour++; if(RTCHour==24){ RTCHour=0; } } } } TMR1H = 0x3F; //Preload counters with 16383 -&gt; 49152 ticks to overflow every 40ms TMR1L = 0xFF; PIR1bits.TMR1IF = 0; } } void statemachine(void){ while(1){ switch(State){ case 4: //NSC -- North/South Green long cycle (crossing) LEDReg1 = 0x64; LEDReg2 = 0x89; cmdlcd(0xC9); putslcd(st[State]); if(RemoteOp){ while((State==4) &amp;&amp; RemoteOp){idle();} if(State!=4){break;} } Countdown = LongCycle; T0CONbits.TMR0ON = 1; while(T0CONbits.TMR0ON){ Delay10KTCYx(10); updatetimes(); if((Countdown&gt;=15) &amp;&amp; Tick){ beephigh(); while(Tick){} } } updatetimes(); Delay10KTCYx(123); State = 5; case 5: //NSF -- North/South Green w/flashing crosswalk lights (falls in from state 4) LEDReg1 = 0x64; LEDReg2 = 0x89; cmdlcd(0xC9); putslcd(st[State]); Countdown = FlashCycle; T0CONbits.TMR0ON = 1; while(T0CONbits.TMR0ON){ Delay10KTCYx(10); updatetimes(); if(Tick){ LEDReg1 = 0xA4; } else{ LEDReg1 = 0x24; } } updatetimes(); State = 6; case 6: //NSY -- North/South Yellow LEDReg1 = 0x92; LEDReg2 = 0x89; cmdlcd(0xC9); putslcd(st[State]); if(RemoteOp){ while((State==6) &amp;&amp; RemoteOp){idle();} if(State!=6){break;} } Countdown = YellowCycle; T0CONbits.TMR0ON = 1; while(T0CONbits.TMR0ON){ Delay10KTCYx(10); updatetimes(); } updatetimes(); Delay10KTCYx(123); State = 7; case 7: //NSR -- North/South Red LEDReg1 = 0x89; LEDReg2 = 0x89; cmdlcd(0xC9); putslcd(st[State]); if(RemoteOp){ while((State==7) &amp;&amp; RemoteOp){idle();} if(State!=7){break;} } Countdown = RedCycle; T0CONbits.TMR0ON = 1; while(T0CONbits.TMR0ON){ Delay10KTCYx(10); updatetimes(); } updatetimes(); Delay10KTCYx(123); while(1){ //replace with future branching code idle(); } break; } } } </code></pre> <p>I'm guessing there's a "tighter" way to do all this, but right now it all works perfectly save for at least one hiccup when flashing the LED in state 5. There's probably a lot of optimization that could be made here, but my main focus is to just get something working first. </p> <p>I'd greatly appreciate any sort of help improving this code. </p> <p>Compiler is MPLAB/C18</p>
[]
[ { "body": "<h2>General</h2>\n\n<p>Difficult to read, don't you think? Code is normally a 'write-once,\n read-often' operation. Therefore it makes sense to make it easy to read,\n even if it takes longer to write.</p>\n\n<ul>\n<li><p><code>if</code>, <code>while</code> etc should be followed by a space and operators such as <code>=</code> of\n<code>==</code> should be surrounded by spaces.</p></li>\n<li><p>Functions start with the brace in column 0. Really.</p></li>\n<li><p>Spreading constants (13, 25, 9F/FF, etc) around your code is a bad idea.  It\n  makes modifying the code much more error-prone.  Even if you think you will\n  never need to modify them, it is better to define them in #defines at the\n  top of the relevant file or in a header.</p></li>\n</ul>\n\n<h2>In <code>low_isr</code></h2>\n\n<ul>\n<li><p>You could simplify this</p>\n\n<pre><code>if (OvfT0 &lt; 13) {Tick = 0;}\nif (OvfT0 &gt; 13) {Tick = 1;}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>Tick = (OvfT0 &gt; 13);\n</code></pre>\n\n<p>assuming that it doesn't matter what happens when OvfT0 == 13 which is not\nclear from your code.</p></li>\n<li><p>Your variables such as <code>INTCONbits.TMR0IF</code>, <code>OvfT0</code>, <code>TMR0H</code> etc are\npresumably pointers to registers; they are the sort of mnemonics beloved of\nhardware makers. However, you don't have to suffer such cryptic names - you\ncan use inline functions to abstract away the interface - inline to avoid a\ncall-overhead.</p>\n\n<pre><code>inline int timer_overflow(void) { return INTCONbits.TRM01F; }\ninline void timer_overflow_reset(void) { INTCONbits.TRM01F = 0; }\n\n//Preload counters ...\ninline void preload_timer(void) { TMR0H = ...; TMR0L = ...; }\n</code></pre></li>\n<li><p>your handling of the RTC values is unsafe. By writing three separate values\nfrom the ISR you guarantee that at some point, application level (ie. non-isr)\ncode is going to read one of the three values and then get interrupted by\nthis ISR; when the ISR returns the time has changed and it reads a corrupted\nvalue. To avoid this I suggest you have a single <code>RTCTime</code> value that holds\njust the seconds - make sure it is small enough to be readable with one\nmachine instruction (normally an <code>int</code> or <code>int32_t</code> should do fine). Then\ndo the conversion to hours /mins/secs at application level - read the value\n<strong>once</strong> from <code>RTCTime</code> and convert that value.</p></li>\n<li><p>make sure the values being written by the ISR are declared <code>volatile</code></p></li>\n<li><p>deeply indented code is normally wrong.</p></li>\n</ul>\n\n<h2>In <code>statemachine</code></h2>\n\n<ul>\n<li><p><code>state_machine</code> is easier to read</p></li>\n<li><p>switch should have a default case, even if you think you have covered all\nthe 'likely' cases. You probably haven't.</p></li>\n<li><p>this is pretty unreadable. You should probably separate each state into\nits own function.</p></li>\n<li><p>the cases all fall through without any comments...! This seems unnecessary,\nas it is all in a while loop anyway.</p></li>\n<li><p>it seems likely that you can factor-out some common code shared by all\nstates, eg:</p>\n\n<pre><code>LEDReg1 = 0x..;\nLEDReg2 = 0x..;\ncmdlcd(0xC9);\nputslcd(st[State]);\n...\nupdatetimes();\n</code></pre></li>\n<li><p>this code is repeated in three states with different state values. </p>\n\n<pre><code>if(RemoteOp){\n while((State==6) &amp;&amp; RemoteOp){idle();}\n if(State!=6){break;}\n}\n</code></pre>\n\n<p>presumably another thread or an ISR is changing <code>State</code> or <code>RemoteOp</code>,\notherwise this is an infinite loop. A function might be better:</p>\n\n<pre><code>static inline int remote_state_change(int current_state)\n{\n if (RemoteOp) {\n while ((State == current_state) &amp;&amp; RemoteOp) { idle(); }\n return State!=6;\n }\n return 0;\n}\n</code></pre>\n\n<p>And call with</p>\n\n<pre><code>if (remote_state_change(State)) {break;}\n</code></pre></li>\n</ul>\n\n<p>BTW, do you have any OS support (microkernel etc) or is this bare-metal?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T05:00:07.210", "Id": "36576", "Score": "0", "body": "Wow, thanks for going through my code so thoroughly. Here's some comments in response: I'll definitely go over the code and improve the whitespace. Nice catch in low_isr re: Ticks, but re: RTC I'm programming on 8-bit metal, so 24 bit ops add a lot of overhead for something that hasn't been a problem (so far). The full state machine is 32 states so I wanted to spare everyone the wall; those states in particular had the simplest branch logic. RemoteOp and State do change by ISR, so I'll add volatile. I pulled out the print statement to above the switch. I'll try the rest of your code tomorrow!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T13:04:29.970", "Id": "36586", "Score": "0", "body": "I should have considered that the processor might not have 32-bit regs. The time-reading problem will occur - it is not 'if', but 'when'. Whether it matters depends upon what you do with the time. The overhead you have already for setting H:M:S is probably similar to the cost of a 24-bit access, but more importantly, as it is 8-bit a 24-bit access would not be atomic anyway so you gain nothing by changing. Instead, use a simple application-level function that loops reading the H:M:S until it gets the same result twice." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T03:28:59.593", "Id": "23712", "ParentId": "23699", "Score": "1" } } ]
{ "AcceptedAnswerId": "23712", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T19:32:50.307", "Id": "23699", "Score": "1", "Tags": [ "optimization", "c", "synchronization" ], "Title": "Timing/Synchronization issues with interrupt-reliant code" }
23699
<p>This is in continuation to a question I asked <a href="https://stackoverflow.com/questions/15256966/deriving-a-group-or-a-set-from-a-map">here</a>. Given the total number of nodes (employees) and the adjacency list (friendship amongst employees), I need to find all the connected components.</p> <pre><code>public class Main { static HashMap&lt;String, Set&lt;String&gt;&gt; friendShips; public static void main(String[] args) throws IOException { BufferedReader in= new BufferedReader(new InputStreamReader(System.in)); String dataLine = in.readLine(); String[] lineParts = dataLine.split(" "); int employeeCount = Integer.parseInt(lineParts[0]); int friendShipCount = Integer.parseInt(lineParts[1]); friendShips = new HashMap&lt;String, Set&lt;String&gt;&gt;(); for (int i = 0; i &lt; friendShipCount; i++) { String friendShipLine = in.readLine(); String[] friendParts = friendShipLine.split(" "); mapFriends(friendParts[0], friendParts[1], friendShips); mapFriends(friendParts[1], friendParts[0], friendShips); } Set&lt;String&gt; employees = new HashSet&lt;String&gt;(); for (int i = 1; i &lt;= employeeCount; i++) { employees.add(Integer.toString(i)); } Vector&lt;Set&lt;String&gt;&gt; friendBuckets = bucketizeEmployees(employees); System.out.println(friendBuckets.size()); } public static void mapFriends(String friendA, String friendB, Map&lt;String, Set&lt;String&gt;&gt; friendsShipMap) { if (friendsShipMap.containsKey(friendA)) { friendsShipMap.get(friendA).add(friendB); } else { Set&lt;String&gt; friends = new HashSet&lt;String&gt;(); friends.add(friendB); friendsShipMap.put(friendA, friends); } } public static Vector&lt;Set&lt;String&gt;&gt; bucketizeEmployees(Set&lt;String&gt; employees) { Vector&lt;Set&lt;String&gt;&gt; friendBuckets = new Vector&lt;Set&lt;String&gt;&gt;(); while (!employees.isEmpty()) { String employee = getHeadElement(employees); Set&lt;String&gt; connectedEmployeesBucket = getConnectedFriends(employee); friendBuckets.add(connectedEmployeesBucket); employees.removeAll(connectedEmployeesBucket); } return friendBuckets; } private static Set&lt;String&gt; getConnectedFriends(String friend) { Set&lt;String&gt; connectedFriends = new HashSet&lt;String&gt;(); connectedFriends.add(friend); Set&lt;String&gt; queuedFriends = new LinkedHashSet&lt;String&gt;(); if (friendShips.get(friend) != null) { queuedFriends.addAll(friendShips.get(friend)); } while (!queuedFriends.isEmpty()) { String poppedFriend = getHeadElement(queuedFriends); connectedFriends.add(poppedFriend); if (friendShips.containsKey(poppedFriend)) for (String directFriend : friendShips.get(poppedFriend)) { if (!connectedFriends.contains(directFriend) &amp;&amp; !queuedFriends.contains(directFriend)) { queuedFriends.add(directFriend); } } } return connectedFriends; } private static String getHeadElement(Set&lt;String&gt; setFriends) { Iterator&lt;String&gt; iter = setFriends.iterator(); String head = iter.next(); iter.remove(); return head; } } </code></pre> <p>I have tested my code using the following script, the results of which I consume as sdtIn</p> <pre><code>#!/bin/bash echo "100000 100000" for i in {1..100000} do r1=$(( $RANDOM % 100000 )) r2=$(( $RANDOM % 100000 )) echo "$r1 $r2" done </code></pre> <p>While I was able to verify (for trivial inputs) that my answer is correct, when I try with huge inputs as with the above script, I see that the run takes long (~20s).</p> <p>Is there anything I can do better in my implementation ?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-16T10:20:57.193", "Id": "36974", "Score": "0", "body": "Use a profiler to profile the code and find out where you spent the time. It is hard to guess, because a lot is happening there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-22T12:02:29.547", "Id": "39265", "Score": "0", "body": "The code is pretty fast, the server JDK (using command line parameter -server) is 2 times faster on my PC (C2D E7200) 12sec vs 24sec." } ]
[ { "body": "<ol>\n<li><p>First of all, two things to read or search for: Cluster analysis (just a hint, I'm not an expert about that) and <a href=\"https://en.wikipedia.org/wiki/Linked:_The_New_Science_of_Networks\" rel=\"nofollow noreferrer\"><em>Linked: The New Science of Networks</em></a> by <em>Albert-László Barabási</em>. </p>\n\n<p>Barabási in his book shows that networks usually have some nodes which have a lot more connections than the others. The distribution is not the same in the real world as the sample shell script generates.</p></li>\n<li><p>The code is quite good, I like your variable and method names and separated methods. I wonder why haven't anyone reviewed it yet.</p></li>\n<li><blockquote>\n<pre><code>Vector&lt;Set&lt;String&gt;&gt; friendBuckets = bucketizeEmployees(employees);\n</code></pre>\n</blockquote>\n\n<p>I'd use a simple <code>List</code> or <code>ArrayList</code> here. <a href=\"https://stackoverflow.com/q/1386275/843804\">Vector is considered obsolete</a>.</p></li>\n<li><p>In the <code>getConnectedFriends</code> method the</p>\n\n<blockquote>\n<pre><code>Set&lt;String&gt; queuedFriends = new LinkedHashSet&lt;String&gt;();\n</code></pre>\n</blockquote>\n\n<p>could be a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html\" rel=\"nofollow noreferrer\">Queue</a>. It has a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html#poll%28%29\" rel=\"nofollow noreferrer\"><code>poll</code></a> method. As far as I tested it's faster than the currently used iterator-based remove.</p></li>\n<li><blockquote>\n<pre><code>public class Main {\n</code></pre>\n</blockquote>\n\n<p><code>Main</code> isn't a good class name. Everyone can have a <code>Main</code>. What's it purpose? Try to find a more descriptive name.</p></li>\n<li><blockquote>\n<pre><code>static HashMap&lt;String, Set&lt;String&gt;&gt; friendShips; \n</code></pre>\n</blockquote>\n\n<p><code>HashMap&lt;...&gt;</code> reference types should be simply <code>Map&lt;...&gt;</code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p>\n\n<p><a href=\"https://stackoverflow.com/questions/5484845/should-i-always-use-the-private-access-modifier-for-class-fields\">Should I always use the private access modifier for class fields?</a>; <em>Item 13</em> of <em>Effective Java 2nd Edition</em>: <em>Minimize the accessibility of classes and members</em>.</p></li>\n<li><blockquote>\n<pre><code> static HashMap&lt;String, Set&lt;String&gt;&gt; friendShips; \n</code></pre>\n</blockquote>\n\n<p>Instead of <code>Map&lt;String, Set&lt;String&gt;&gt;</code> you could use Guava's <code>Multimap</code> (<a href=\"https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multimap\" rel=\"nofollow noreferrer\">doc</a>, <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html\" rel=\"nofollow noreferrer\">javadoc</a>) which was designed exactly for that. It would reduce the size of the <code>mapFriends</code> method:</p>\n\n<pre><code>public static void mapFriends(final String friendA, final String friendB,\n final Multimap&lt;String, String&gt; friendsShipMap) {\n friendsShipMap.put(friendA, friendB);\n}\n</code></pre>\n\n<p>So, it could be removed.</p></li>\n<li><blockquote>\n<pre><code>public static Vector&lt;Set&lt;String&gt;&gt; bucketizeEmployees(Set&lt;String&gt; employees) {\n ...\n}\n</code></pre>\n</blockquote>\n\n<p>This method calls <code>getConnectedFriends(employee)</code>, which is the following:</p>\n\n<blockquote>\n<pre><code>private static Set&lt;String&gt; getConnectedFriends(String friend) {\n ...\n}\n</code></pre>\n</blockquote>\n\n<p>It's confusing: what is the difference between an employee and friend? Are they the same?</p></li>\n<li><blockquote>\n<pre><code>if (friendShips.get(friend) != null) {\n</code></pre>\n</blockquote>\n\n<p>The following is the same:</p>\n\n<pre><code>if (friendShips.containsKey(friend)) {\n</code></pre>\n\n<p>A <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow noreferrer\">guard clause</a> would be even better.</p>\n\n<pre><code>if (!friendShips.containsKey(friend)) {\n return connectedFriends;\n}\n</code></pre></li>\n<li><blockquote>\n<pre><code>if (!connectedFriends.contains(directFriend) &amp;&amp; !queuedFriends.contains(directFriend)) {\n queuedFriends.add(directFriend);\n}\n</code></pre>\n</blockquote>\n\n<p>The <code>!queuedFriends.contains(directFriend)</code> condition is unnecessary, it's a set which can't contain elements twice and adding an already added element to a <code>LinkedHashSet</code> doesn't modify anything. From the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashSet.html\" rel=\"nofollow noreferrer\">javadoc</a>:</p>\n\n<blockquote>\n <p>Note that insertion order is not affected if an element is re-inserted into the set.</p>\n</blockquote></li>\n<li><p>The following pattern occurs more than once in the code:</p>\n\n<pre><code>if (map.containsKey(key)) {\n String value = map.get(key);\n ...\n}\n...\n</code></pre>\n\n<p>It might be a microoptimization, but if you profile the code and the results shows it as a bottleneck the following structure is the same:</p>\n\n<pre><code>String value = map.get(key); \nif (value != null) {\n ...\n}\n...\n</code></pre></li>\n<li><p>A few <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow noreferrer\">guard clause</a> would help to make <code>getConnectedFriends</code> more flatten:</p>\n\n<pre><code>while (!queuedFriends.isEmpty()) {\n final String poppedFriend = getHeadElement(queuedFriends);\n connectedFriends.add(poppedFriend);\n if (!friendShips.containsKey(poppedFriend)) {\n continue;\n }\n for (final String directFriend: friendShips.get(poppedFriend)) {\n if (connectedFriends.contains(directFriend)) {\n continue;\n }\n queuedFriends.add(directFriend);\n }\n}\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-05T22:49:53.720", "Id": "43560", "ParentId": "23700", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T19:53:39.013", "Id": "23700", "Score": "3", "Tags": [ "java", "performance", "breadth-first-search", "graph" ], "Title": "BFS implementation to find connected components taking too long" }
23700
<p>Below is an implementation of Dijkstra's shortest path algorithm. It's input <code>graph</code> is represented as an association list of source nodes to assoc of target node and arc weight.</p> <p>My question is about the following, am I missing a way of simplifying <code>min-path</code> function used in reduce? Maybe the great and powerful <code>loop</code> could do <code>reduce</code>'s job? </p> <pre><code>(defun dijkstra (source target graph) (labels ((min-path (&amp;optional arc-1 arc-2) (let ((price-1 (cdr arc-1)) (price-2 (cdr arc-2))) (cond ((and (not (null arc-1)) (not (null arc-2))) (if (&lt; price-1 price-2) arc-1 arc-2) ) ((and (not (null arc-1)) (null (arc-2))) arc-1) ((and (not (null arc-2)) (null (arc-1))) arc-2)))) (get-best-path (visited) (reduce #'min-path (loop for pick in visited for start = (car pick) for cost = (cdr pick) append (loop for arc in (cdr (assoc start graph)) when (null (assoc (car arc) visited)) collect (cons (car arc) (+ cost (cdr arc)))))))) (loop named main-loop with visited = (list (cons source 0)) for best-arc = (get-best-path visited) when (not (null best-arc)) do (push best-arc visited) until (or (null best-arc) (eql (car best-arc) target)) finally (format t "Found shortest path from ~A to ~A: ~A~%" source target best-arc) (return-from main-loop (cdr best-arc))))) </code></pre> <p>I'm new to Lisp, and I would appreciate any advice, especially on bad Lisp habits and bad Lisp style in my code, thanks.</p> <p><em>UPD</em>: new version with review comments applied - no warnings, unlike the original version.</p> <pre><code>(defun dijkstra (source target graph) (labels ((min-path (&amp;optional arc-1 arc-2) (cond ((and arc-1 arc-2) (if (&lt; (cdr arc-1) (cdr arc-2)) arc-1 arc-2)) (arc-1 arc-1) (arc-2 arc-2) (t nil))) (get-best-path (visited) (reduce #'min-path (loop for pick in visited for start = (car pick) for cost = (cdr pick) append (loop for arc in (cdr (assoc start graph)) unless (assoc (car arc) visited) collect (cons (car arc) (+ cost (cdr arc)))))))) (loop with visited = (list (cons source 0)) for best-arc = (get-best-path visited) when best-arc do (push best-arc visited) until (or (null best-arc) (eql (car best-arc) target)) finally (return (cdr best-arc))))) </code></pre>
[]
[ { "body": "<p>First, <code>(not (null x))</code> is not very idiomatic; just use <code>x</code> instead.</p>\n\n<p>Next, you are not handling <em>all</em> the cased in your <code>cond</code> (and you obviously mean <code>(null arc-2)</code> and not <code>(null (arc-2))</code>). If fact, I would drop the <code>let</code> and use nested <code>if</code>s instead.</p>\n\n<p>Finally, to answer your original question: of course <code>loop</code> can do everything <code>reduce</code> can, but if your intent is clearer with the latter, use it!</p>\n\n<p>EDIT: <code>unless</code> is more idiomatic than <code>when (null ...)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T13:58:45.773", "Id": "36591", "Score": "0", "body": "Wow, thanks, the `(null (arc-2))` is an error that doesn't prevent the program from properly executing. Regarding *all* cases, it is \"merely\" a discipline matter right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T14:11:53.383", "Id": "36593", "Score": "0", "body": "If this error does not prevent proper execution, you are not testing all cases in your inputs. Checking all cases in `cond` is needed for clarity of your intent and error checking." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T21:16:09.627", "Id": "23703", "ParentId": "23701", "Score": "2" } } ]
{ "AcceptedAnswerId": "23703", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T20:09:36.720", "Id": "23701", "Score": "1", "Tags": [ "lisp", "common-lisp" ], "Title": "Proper use of reduce, nested loops" }
23701
<p>I need to connect different <code>Task</code> with a double linked list and different <code>Dependencies</code> which affect a calculation for which I need the values of both <code>Task</code>:</p> <pre><code>public class Task { private List&lt;Dependency&gt; parents = new ArrayList&lt;Dependency&gt;(); private List&lt;Dependency&gt; children = new ArrayList&lt;Dependency&gt;(); //Uses the parents values and calls `calculateForwards` of the children public void calculateForwards() { .. } //Uses the children values and calls `calculateBackwards` of the children public void calculateBackwards() { .. } } public interface Dependency { Task getTask(); void setForwards(Task t); void setBackwards(Task t); Dependency createCopy(Task t); } public class EA implements Dependency { private Task task; //............ @Override public void setForwards(Task t) { if (t.getEarlyStart() &lt; task.getEarlyFinish()) t.setEarlyStart(task.getEarlyFinish()); t.setEarlyFinish(t.getEarlyStart() + t.getDuration()); } @Override public void setBackwards(Task t) { if (t.getLatestFinish() &gt; task.getLatestStart()) t.setLatestFinish(task.getLatestStart()); t.setLatestStart(t.getLatestFinish() - t.getDuration()); } //............ } </code></pre> <p>For now dependencies are created with the <code>Task</code> it points to and added to the children list. Then a copy of the dependency is created that points to the original task and added to the parent list of the child:</p> <pre><code>public void addChild(Dependency r) { children.add(r); r.getTask().addParent(r.createCopy(this)); } private void addParent(Dependency r) { parents.add(r); } </code></pre> <p>As you can see this data structure does the job, but very ugly in my eyes. How can I solve this more elegantly?</p> <ul> <li><a href="https://gist.github.com/Savaron/fc3c6667c55b17981f68#file-task-java" rel="nofollow">Task.java</a>, </li> <li><a href="https://gist.github.com/Savaron/fc3c6667c55b17981f68#file-dependency-java" rel="nofollow">Dependency.java</a>, </li> <li><a href="https://gist.github.com/Savaron/fc3c6667c55b17981f68#file-ea-java" rel="nofollow">EA.java (implements Dependency)</a></li> </ul>
[]
[ { "body": "<p><code>Task</code> depends on <code>Dependency</code> (not very troubling in itself) :</p>\n\n<pre><code>public class Task {\n private List&lt;Dependency&gt; parents = new ArrayList&lt;Dependency&gt;();\n</code></pre>\n\n<p>Also <code>Dependency</code> depends on concrete class <code>Task</code> (somewhat more troubling):</p>\n\n<pre><code>public interface Dependency {\n Task getTask();\n</code></pre>\n\n<p>Although dependency cycles of size 2 are not intrinsically a problem, in this case interface <code>Dependency</code> is pretty much useless, [if we look at the implementation, which is a hybrid holder and wrapper for <code>Task</code>]. Too generic a name and getters and setters on the interface are also signs that this interface does not pull its weight.</p>\n\n<p>If the problem model is a graph it is expected that class that represents the node of that graph should be depend on itself. Dependency cycles of 1 is generally better than 2.</p>\n\n<h2>My Suggestion</h2>\n\n<p>The only methods that contain logic in the implementation of <code>Dependency</code> is <code>setBackwards</code> and <code>setForwards</code>. But when we read them we see that they manipulate the insides of <code>Task</code>, and therefore should be moved into that class. After the said move you can remove <code>Dependency</code> and <code>EA</code>, and directly use <code>Task</code> instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T09:53:31.427", "Id": "36582", "Score": "0", "body": "So I need to move the graph stuff into Dependency?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T10:50:52.167", "Id": "36583", "Score": "0", "body": "@Sven I appended my suggestion to the answer. I suggest you should get rid of `Dependency` and `EA`. As for moving graph stuff elsewhere, it seems reasonable. I imagine a `TaskNode` class, which *has a* `Task`, having links to other `TaskNode`s makes sense." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T08:30:30.450", "Id": "23726", "ParentId": "23702", "Score": "1" } } ]
{ "AcceptedAnswerId": "23726", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T20:49:20.797", "Id": "23702", "Score": "1", "Tags": [ "java", "linked-list" ], "Title": "Doubly linked list with different dependencies" }
23702
<p>I have 2 classes that should run a service when calling their <code>Start</code> method, but before it they should:</p> <ol> <li>Copy items to F folder</li> <li>Open S service in remote server if it's not opened already</li> <li>Run #SN service in remote server</li> </ol> <p>They differ in 1 &amp; 3 steps:</p> <ol> <li>In 1st step each one of them may copy different items depending on some parameters</li> <li>In 3rd step each one call different service name</li> </ol> <p>My question is should both of them derive from base class and each one will override 1 &amp; 3 steps OR minor overlap between the two classes is not a reason for inheritance?</p> <p>I'm more inclined to the second opinion and I think to do <code>Runner</code> class that has static methods <code>RunService1</code> &amp; <code>RunService2</code> and each one will copy items it should copy, open S service and run #S1/#S2 service.</p> <p>Here is example of separated class and using base class:</p> <p><strong>Run1</strong></p> <pre><code>class Run1 { private _src; private _dest; private _mode; public Run1(string src, string dest, int mode, int arg1, int arg2,...) { _src = src; _dest = dest; _mode = mode; } public void Run() { PrepareFolders(); OpenServer(); RunInternal(); } private void PrepareFolders() { // copy from src to dest _src = _dest // after the copying the new source is the destination // more copying specific folders to dest depending on mode } private void OpenServer() { var client = new WcfClient(); client.OpenServer(); } private void RunInternal() { var client = new WcfClient(); client.RunService1(arg1, arg2, arg3, ...); } } </code></pre> <p><strong>Run2</strong></p> <pre><code>class Run2 { private _src; private _dest; private _mode; public Run2(string src, string dest, int mode) { _src = src; _dest = dest; _mode = mode; } public void Run() { PrepareFolders(); if(!IfServerOpened()) { OpenServer(); } RunInternal(); } private void PrepareFolders() { // This copy the same as in Run1 _src = _dest // after the copying the new source is the destination // Some other copying specific to Run2 } private void OpenServer() { var client = new WcfClient(); client.OpenServer(); } private void RunInternal() { var client = new WcfClient(); client.RunService2(arg1, arg2); } } </code></pre> <p><strong>With base class:</strong></p> <pre><code>class Run1 : RunBase { ... } class Run2 : RunBase { ... } abstract class RunBase { protected string Source { get; private set; } public RunBase(string src, string dest) { ... } protected abstract PrepareFoldersInternal(); public void Run() { PrepareFolders(); if(!IfServerOpened()) { OpenServer(); } RunInternal(); } public void PrepareFolders() { // copy from src to dest _src = _dest // after the copying the new source is the destination Source = dest; PrepareFoldersInternal(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T23:41:10.850", "Id": "36562", "Score": "3", "body": "This is a bit abstract; would you mind posting the code of those classes? My first guess would be that if it can't be solved purely by passing in different parameters, step 1 (and possibly 3) should be performed by different objects that you pass in as dependencies (also going by the general rule of favoring composition over inheritance). But that would be much easier to say with some actual code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T15:37:12.010", "Id": "36603", "Score": "0", "body": "@GCATNM, Sorry, that I didn't specified my language and didn't included code. I updated my post and I'll be glad if you could take a look." } ]
[ { "body": "<p>This depends on the capabilities of your language.</p>\n\n<h3>Strategies, and higher order functions</h3>\n\n<p>If I were to design this, there would only be one class, with a <code>Start</code> method, and two properties <code>service</code> (which somehow specifies a service), and <code>selectItems</code> which is a function that returns a list of items to be copied. These would then be initialized in the constructor. In C#-like pseudocode</p>\n\n<pre><code>class Runner {\n private Service service;\n private delegate Items[] selectItems();\n // some constructor here\n public void Start() {\n // do actual stuff here ...\n }\n}\n\nvar runner1 = new Runner(some_service, awesome_item_selector);\nrunner1.Start();\n</code></pre>\n\n<p>As the object would only have one method, this is equivalent to using a higher-order function which returns a closure over the two properties. In Go-like pseudocode:</p>\n\n<pre><code>func Runner (service Service, selectItems func() []Item) func() {\n return func () {\n // do actual stuff here\n }\n}\n\nrunner1 := Runner(someService, someSelector)\nrunner1() // execute it\n</code></pre>\n\n<h3>Mixin' some traits</h3>\n\n<p>If you have a language that supports mixins/traits/roles, you could create a trait <code>Runner</code> that requires a <code>selectItems</code> method and a <code>service</code> property. The trait would then implement a <code>Start</code> method that uses those requirements. One would then create two classes <code>RunService1</code> and <code>RunService2</code> that uses the trait. In Perl/Moose-like Pseudocode:</p>\n\n<pre><code>role Runner {\n requires 'selectItems', 'service';\n method Start () {\n # do actual stuff here\n }\n}\n\nclass RunService1 with Runner {\n has service =&gt; (is =&gt; 'ro', default =&gt; 'some service');\n method selectItems () {\n # return list of items\n }\n}\n\nmy $run1 = RunService1-&gt;new();\n$run1-&gt;Start();\n</code></pre>\n\n<p>Is this starting to look overengineered? Me too. In fact, this has no advantages over the previous approach iff your language supports higher order functions or lambdas or function pointers or whatnot.</p>\n\n<h3>If you are stuck with a braindead language…</h3>\n\n<p>… you can fake traits by using abstract classes with the methods <code>service</code> and <code>selectItems</code> marked as virtual. The default implementation would then throw an error if executed. The child classes would override these methods, and thus suppress the errors.</p>\n\n<h3>Conclusion:</h3>\n\n<ol>\n<li>Your first option seems fairly sensible, if your language can't do better</li>\n<li>Your second solution would create a class that isn't easy to extend, has more than one task/concern, and is just plain procedural programming. </li>\n<li>Higher-order functions are awesome.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T15:36:55.507", "Id": "36602", "Score": "0", "body": "thank you for your answer. Sorry, that I didn't specified my language and didn't included code. I updated my post and I'll be glad if you could take a look." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T01:25:23.037", "Id": "23709", "ParentId": "23704", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T21:31:25.727", "Id": "23704", "Score": "-1", "Tags": [ "c#", "object-oriented", "design-patterns", "inheritance" ], "Title": "Should I use inheritance in my case?" }
23704
<p>I'm brand new to JavaScript and jQuery and I feel like there's probably a better way to do this. It seems that the way I designed it may not be very optimal once you get a thousand entries in the list but I do like the fact that it's a live search. </p> <p>Note: I tried changing the style of the <code>&lt;option&gt;</code>'s to <code>display:none</code> but that doesn't work in all browsers.</p> <p><a href="http://jsfiddle.net/x6cfF/3/" rel="nofollow">http://jsfiddle.net/x6cfF/3/</a></p> <pre><code>&lt;input type="search" id="SearchBox" /&gt; &lt;br /&gt; &lt;div class="scrollable" id="CustomerSelectDiv"&gt; &lt;select size=2 class="scrollableinside" id="CustomerSelect"&gt; &lt;option value=100&gt;test&lt;/option&gt; &lt;option value=101&gt;test1&lt;/option&gt; &lt;option value=102&gt;test2&lt;/option&gt; &lt;option value=103&gt;test3&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div style="display: none;"&gt; &lt;select id="CustomerSelectHidden"&gt;&lt;/select&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; window.onload=function() { var $options = $('#CustomerSelect option'); document.getElementById("SearchBox").onkeyup = function () { var $HiddenOptions = $('#CustomerSelectHidden option'); $HiddenOptions.each(function (index, value) { document.getElementById('CustomerSelect').appendChild(this); }); var search = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase(); var element = $options.filter(function () { var text = $(this).text().replace(/\s+/g, ' ').toLowerCase(); return !~text.indexOf(search); }).appendTo(document.getElementById('CustomerSelectHidden')); $('#CustomerSelect option').sort(Sort).appendTo('#CustomerSelect'); } } function Sort(a, b) { return (a.innerHTML &gt; b.innerHTML) ? 1 : -1; } &lt;/script&gt; </code></pre>
[]
[ { "body": "<p>First thing I notice is that you're actually not using jQuery all that much. The point of jQuery is really its convenience compared to the native DOM. You're foregoing that convenience in some places, and relying on jQuery in others. You can of course do it all directly using the DOM and skip jQuery, but you're not quite doing that either. My point is really just that you should decide one way or the other in order to keep the code consistent.</p>\n\n<p>Also, while it's not enforced, convention dictates that function names are <code>lowerCamelCase</code>. If you use <code>PascalCase</code> it implies that a function is a constructor. I.e. your <code>Sort</code> function should be just <code>sort</code>.</p>\n\n<p>However, the <code>sort</code> function is not necessary. Provided you always search in a \"master list\" of options, and those are already sorted, then the filtered options will retain that order.</p>\n\n<p>The hidden select element isn't necessary either; you can clone the full option list into memory, and filter it from there without having to store it in the document.</p>\n\n<p>In fact, by keeping a master list, you can \"prepare\" that list to make it faster to filter later.</p>\n\n<p><a href=\"http://jsfiddle.net/TrRMG/\">Here's a demo of my take</a> and here's the code:</p>\n\n<pre><code>$(function () {\n var customerSelect = $(\"#customer\"),\n searchField = $(\"#search\"),\n options = customerSelect.find(\"option\").clone(); // clone into memory\n\n // generic function to clean text\n function sanitize(string) {\n return $.trim(string).replace(/\\s+/g, ' ').toLowerCase();\n }\n\n // prepare the options by storing the\n // \"searchable\" name as data on the element\n options.each(function () {\n var option = $(this);\n option.data( \"sanitized\", sanitize(option.text()) );\n });\n\n // handle keyup\n searchField.on(\"keyup\", function (event) {\n var term = sanitize( $(this).val() ),\n matches;\n\n // just show all options, if there's no search term\n if( !term ) {\n customerSelect.empty().append(options.clone());\n return;\n }\n\n // otherwise, show the options that match\n matches = options.filter(function () {\n return $(this).data(\"sanitized\").indexOf(term) != -1;\n }).clone();\n customerSelect.empty().append(matches);\n });\n});\n</code></pre>\n\n<p>You could do a few more things, but I'll leave that as an exercise:</p>\n\n<ul>\n<li><p>If the search term contains the previous search term, you can filter the customer select directly, instead of filtering the entire \"master list\". I.e. if the last search was for \"foo\" and the next is for \"foobar\", you already have the results that match \"foo\", and only have to find a further subset that contains \"foobar\" rather than starting from the beginning.</p></li>\n<li><p>If you have a very long list, or you're retrieving the search results via ajax, it's beneficial to have a delay between searches. I.e. on keyup wait, say, 100ms before filtering the list, to see if the user's still typing.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T04:00:00.013", "Id": "36664", "Score": "0", "body": "Amazing! thank you for all the feed back and tips." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-14T14:54:50.917", "Id": "264856", "Score": "1", "body": "Just fyi, the demo link is broken." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-09-14T14:59:46.163", "Id": "264859", "Score": "0", "body": "@beporter Well, darn. Should make a stack snippet I suppose, but I must admit I'm not inclined to mess with a 3-year-old answer, so I'll probably just leave it be. Thanks for the heads-up regardless." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T01:12:58.777", "Id": "23708", "ParentId": "23706", "Score": "6" } }, { "body": "<p>Try this.</p>\n\n<pre><code>/**\n * Only shows options that contain a given text.\n * @author Larry Battle &lt;bateru.com/news&gt;\n * @method showOnlyOptionsSimilarToText\n * @param {String|jQuery Object} selectionEl - jQuery selector or jQuery object\n * @param {String} str - String to compare\n * @param {Boolean} isCaseSensitive - is case sensitive\n */\nvar showOnlyOptionsSimilarToText = function (selectionEl, str, isCaseSensitive) {\n if (isCaseSensitive)\n str = str.toLowerCase();\n // cache the jQuery object of the &lt;select&gt; element\n var $el = $(selectionEl);\n if (!$el.data(\"options\")) {\n // cache all the options inside the &lt;select&gt; element for easy recover\n $el.data(\"options\", $el.find(\"option\").clone());\n }\n var newOptions = $el.data(\"options\").filter(function () {\n var text = $(this).text();\n if (isCaseSensitive)\n text = text.toLowerCase();\n return text.match(str);\n });\n $el.empty().append(newOptions);\n};\n\n$(\"#SearchBox\").on(\"keyup\", function () {\n var userInput = $(\"#SearchBox\").val();\n showOnlyOptionsSimilarToText($(\"#CustomerSelect\"), userInput);\n});\n</code></pre>\n\n<p>Demo: <a href=\"http://jsfiddle.net/x6cfF/4/\" rel=\"nofollow\">http://jsfiddle.net/x6cfF/4/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-08T09:18:50.587", "Id": "372863", "Score": "0", "body": "Would add multiple +1 if I could, easy good working solution!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T01:41:38.800", "Id": "23710", "ParentId": "23706", "Score": "3" } } ]
{ "AcceptedAnswerId": "23708", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-10T23:03:58.883", "Id": "23706", "Score": "6", "Tags": [ "javascript", "beginner", "jquery", "html" ], "Title": "Better way to filter select list" }
23706
<p>Had some free time this weekend and I hacked together a small Brainfuck interpreter, with the sole intention of explaining PHP's flavour of OO to a friend. This is a bit over-engineered on purpose, and performance wasn't really considered (or I wouldn't have written this in PHP in the first place). </p> <p>Thoughts? Criticisms? Cookies? </p> <p>I'm more interested on comments on the design, but as with any review, everything is fair game. The code is a bit much, so I removed comments, some whitespace and an interface or two. You can check out the full code and tests on <a href="https://github.com/yrizos/brainfart">github</a>.</p> <p><strong>Example</strong></p> <pre><code>$source = "5,2,10,1!!&gt;&gt;,[&gt;&gt;,]&lt;&lt;[[-&lt;+&lt;]&gt;[&gt;[&gt;&gt;]&lt;[.[-]&lt;[[&gt;&gt;+&lt;&lt;-]&lt;]&gt;&gt;]&gt;]&lt;&lt;]"; $bf = new \Brainfart\Brainfart(); $output = $bf-&gt;run($source); </code></pre> <p><code>$output</code> will be: </p> <pre><code>array (size=4) 0 =&gt; int 1 1 =&gt; int 2 2 =&gt; int 5 3 =&gt; int 10 </code></pre> <p><br/></p> <h1>The interpreter</h1> <pre><code>namespace Brainfart; use Brainfart\VM\Output; use Brainfart\Parser\Parser; use Brainfart\VM\VM; class Brainfart { private $optimize = true; private $vm; private $parser; private $output; public function __construct($loopLimit = 100, $optimize = true) { $this-&gt;vm = new VM(array(), $loopLimit); $this-&gt;parser = new Parser(); $this-&gt;setOptimize($optimize); } public function setOptimize($optimize = true) { $this-&gt;optimize = ($optimize === true); return $this; } public function run($source, $input = "", $fetchMode = Output::FETCH_ARRAY) { $this-&gt;parser-&gt;loadSource($source); if ($this-&gt;parser-&gt;getFlag("string_output") === true) $fetchMode = Output::FETCH_STRING; $appLoop = $this-&gt;parser-&gt;parse($this-&gt;optimize); $appInput = $this-&gt;parser-&gt;getInput(); if (!empty($appInput)) $input = $appInput; $this-&gt;vm-&gt;init($input); $appLoop-&gt;execute($this-&gt;vm); return $this-&gt;vm-&gt;getOutput()-&gt;fetch($fetchMode); } } </code></pre> <p><br /></p> <h1>The Virtual Machine</h1> <p><strong>VM</strong></p> <pre><code>namespace Brainfart\VM; class VM { private $input; private $output; private $memory; private $loopLimit = 0; public function __construct($input = array(), $loopLimit = 0) { $this-&gt;init($input, $loopLimit); } public function init($input = array(), $loopLimit = 0) { $this-&gt;input = new Input($input); $this-&gt;output = new Output(); $this-&gt;memory = new Memory(); $this-&gt;setLoopLimit($loopLimit); return $this; } public function getInput() { return $this-&gt;input; } public function getOutput() { return $this-&gt;output; } public function getMemory() { return $this-&gt;memory; } public function setLoopLimit($loopLimit = 100) { $this-&gt;loopLimit = is_numeric($loopLimit) &amp;&amp; $loopLimit &gt; 0 ? (int) $loopLimit : 0; return $this; } public function getLoopLimit() { return $this-&gt;loopLimit; } } </code></pre> <p><strong>Memory</strong></p> <pre><code>namespace Brainfart\VM; class Memory { private $memory = array(); private $pointer = 0; public function move($value) { $this-&gt;pointer += is_numeric($value) ? (int) $value : 0; return $this; } public function fetch() { return isset($this-&gt;memory[$this-&gt;pointer]) ? $this-&gt;memory[$this-&gt;pointer] : 0; } public function store($value) { $this-&gt;memory[$this-&gt;pointer] = $this-&gt;fetch() + (is_numeric($value) ? (int) $value : 0); return $this; } } </code></pre> <p><strong>Input</strong></p> <pre><code>namespace Brainfart\VM; class Input { private $input = array(); public function __construct($input) { $this-&gt;store($input); } public function store($input) { if (is_scalar($input)) $input = str_split(trim($input)); if (!is_array($input)) throw new \InvalidArgumentException(); foreach ($input as $key =&gt; $value) $input[$key] = is_numeric($value) ? (int) $value : ord($value); $this-&gt;input = $input; return $this; } public function fetch() { return !(empty($this-&gt;input)) ? array_shift($this-&gt;input) : 0; } } </code></pre> <p><strong>Output</strong></p> <pre><code>namespace Brainfart\VM; class Output { const FETCH_ARRAY = 0; const FETCH_STRING = 1; private $output = array(); public function store($value) { $this-&gt;output[] = $value; return $this; } public function fetch($fetchMode = self::FETCH_ARRAY) { return ($fetchMode === self::FETCH_STRING) ? implode("", array_map("chr", $this-&gt;output)) : $this-&gt;output; } } </code></pre> <p><br/></p> <h1>Virtual Machine Operations</h1> <p><strong>ChangeOperation</strong></p> <pre><code>namespace Brainfart\Operations; use Brainfart\VM\VM; class ChangeOperation implements OperationInterface, MutableInterface { use MutableTrait; public function execute(VM $vm) { $vm-&gt;getMemory()-&gt;store($this-&gt;getValue()); } } </code></pre> <p><strong>InputOperation</strong></p> <pre><code>namespace Brainfart\Operations; use Brainfart\VM\VM; class InputOperation implements OperationInterface { public function execute(VM $vm) { $vm-&gt;getMemory()-&gt;store($vm-&gt;getInput()-&gt;fetch()); } } </code></pre> <p><strong>LoopOperation</strong></p> <pre><code>namespace Brainfart\Operations; use Brainfart\VM\VM; class LoopOperation implements OperationInterface { private $master = false; private $operations = array(); public function __construct(array $operations, $master = false) { $this-&gt;setOperations($operations)-&gt;setMaster($master); } public function setOperations(array $operations) { $this-&gt;operations = $operations; return $this; } public function getOperations() { return $this-&gt;operations; } public function setMaster($master) { $this-&gt;master = ($master === true); return $this; } public function getMaster() { return $this-&gt;master; } public function execute(VM $vm) { $operations = $this-&gt;getOperations(); $limit = $vm-&gt;getLoopLimit(); $i = 0; while ( $this-&gt;getMaster() // master loop is the whole app, runs regardless of memory value || ($vm-&gt;getMemory()-&gt;fetch() != 0) ) { foreach ($operations as $operation) $operation-&gt;execute($vm); if ($this-&gt;getMaster()) break; $i++; if ($limit &gt; 0 &amp;&amp; $limit &lt; $i) throw new \RuntimeException("Limit of {$limit} operations per loop reached."); } } } </code></pre> <p><strong>MoveOperation</strong></p> <pre><code>namespace Brainfart\Operations; use Brainfart\VM\VM; class MoveOperation implements OperationInterface, MutableInterface { use MutableTrait; public function execute(VM $vm) { $vm-&gt;getMemory()-&gt;move($this-&gt;getValue()); } } </code></pre> <p><strong>OutputOperation</strong></p> <pre><code>namespace Brainfart\Operations; use Brainfart\VM\VM; class OutputOperation implements OperationInterface { public function execute(VM $vm) { $vm-&gt;getOutput()-&gt;store($vm-&gt;getMemory()-&gt;fetch()); } } </code></pre> <p><strong>SleepOperation</strong></p> <p>This is how you turn a good joke into a bad one.</p> <pre><code>namespace Brainfart\Operations; use Brainfart\VM\VM; class SleepOperation implements OperationInterface { public function execute(VM $vm) { sleep($vm-&gt;getMemory()-&gt;fetch()); } } </code></pre> <p><strong>MutableTrait</strong></p> <pre><code>namespace Brainfart\Operations; trait MutableTrait { private $value; public function __construct($value) { $this-&gt;setValue($value); } public function setValue($value) { $this-&gt;value = is_numeric($value) ? (int) $value : 0; return $this; } public function getValue() { return $this-&gt;value; } public function combine(MutableInterface $operation) { $class = get_class($this); if ($operation instanceof $class) { $this-&gt;setValue($this-&gt;getValue() + $operation-&gt;getValue()); return $this; } return false; } } </code></pre> <p><br/></p> <h1>The Parser</h1> <p><strong>Loader</strong></p> <pre><code>namespace Brainfart\Parser; class Loader { private $input; private $source = ""; private $flags = array(); public function __construct($source = null) { if (!is_null($source)) $this-&gt;loadSource($source); $this-&gt;setFlag("no_optimization", false)-&gt;setFlag("string_output", false); } public function loadSource($source) { if (is_file($source)) $source = @ file_get_contents($source); if (!is_string($source)) throw new \InvalidArgumentException(); $source = $this-&gt;prepare($source); $source = $this-&gt;skintoad($source); $source = $this-&gt;cleanup($source); return $this-&gt;source = $source; } public function getSource() { return $this-&gt;source; } public function getInput() { return $this-&gt;input; } public function getFlag($flag = null) { if (is_null($flag) || !is_scalar($flag)) return $this-&gt;flags; $flag = strtolower(trim($flag)); return isset($this-&gt;flags[$flag]) ? $this-&gt;flags[$flag] : null; } protected function setFlag($flag, $value = null) { $flag = (!is_scalar($flag)) ? "unknown" : strtolower(trim($flag)); if (!is_null($value)) $value = ($value === true); $this-&gt;flags[$flag] = $value; return $this; } public function setInput($input) { if (!is_scalar($input)) throw new \InvalidArgumentException(); $input = (string) $input; $input = trim($input, ", "); $input = explode(",", $input); $input = array_map("trim", $input); $this-&gt;input = $input; return $this; } private function prepare($source) { $flags = array("@@" =&gt; "no_optimization", "$$" =&gt; "string_output"); foreach ($flags as $operator =&gt; $flag) { if (strpos($source, $operator) !== false) { $this-&gt;setFlag($flag, true); $source = str_replace($operator, "", $source); } } $pos = strpos($source, "!!"); if ($pos !== false) { $input = substr($source, 0, $pos); $source = substr($source, $pos + 2); $this-&gt;setInput($input); } return preg_replace('/\s+/', "", strtolower($source)); } private function skintoad($source) { if (!preg_match_all('/:(.*?);/', $source, $matches)) return $source; foreach ($matches[0] as $match) { $source = str_replace($match, "", $source); $match = trim($match, ":;"); if (preg_match('/^[a-zA-Z0-9_]*/', $match, $identifier)) { $identifier = $identifier[0]; $sequence = str_replace($identifier, "", $match); $source = str_replace($identifier, $sequence, $source); } } return $source; } private function cleanup($source) { return preg_replace('/[^&lt;|&gt;|\-|\+|\.|\~|\,|\]|\[]/', "", $source); } } </code></pre> <p><strong>Parser</strong></p> <pre><code>namespace Brainfart\Parser; use Brainfart\Operations\LoopOperation; use Brainfart\Operations\SleepOperation; use Brainfart\Operations\ChangeOperation; use Brainfart\Operations\MoveOperation; use Brainfart\Operations\InputOperation; use Brainfart\Operations\OutputOperation; use Brainfart\Operations\MutableInterface; class Parser extends Loader { private $operations; public function parse($optimize = true) { if ($this-&gt;getFlag("no_optimization") === true) $optimize = false; $operations = $this-&gt;tokenize($this-&gt;getSource(), $optimize); return $this-&gt;operations = new LoopOperation($operations, true); } public function getOperations() { return $this-&gt;operations; } private function tokenize($source, $optimize) { $result = array(); $optimize = $optimize === true; $length = strlen($source); for ($i = 0; $i &lt; $length; $i++) { $token = isset($source[$i]) ? $source[$i] : false; if (!$token) break; if ($token == "[") { $loopEnd = $this-&gt;findLoopEnd(substr($source, $i + 1)); if (!$loopEnd) throw new \LogicException("Neverending loop."); $loopSource = substr($source, $i + 1, $loopEnd); $loopTokens = $this-&gt;tokenize($loopSource, $optimize); $operation = new LoopOperation($loopTokens); $i += $loopEnd + 1; } else { $operation = $this-&gt;getOperation($token); if (!$operation) continue; if ($optimize &amp;&amp; ($operation instanceof MutableInterface)) { $index = count($result) - 1; $previous = isset($result[$index]) ? $result[$index] : false; $combined = ($previous instanceof MutableInterface) ? $previous-&gt;combine($operation) : false; if ($combined) { $result[$index] = $combined; continue; } } } $result[] = $operation; } return $result; } private function findLoopEnd($source) { $posCloseBracket = strpos($source, "]"); $posOpenBracket = strpos($source, "["); if ($posOpenBracket === false || $posCloseBracket &lt; $posOpenBracket) return $posCloseBracket; $source[$posOpenBracket] = $source[$posCloseBracket] = "_"; return $this-&gt;findLoopEnd($source); } private function getOperation($token) { $operation = false; switch ($token) { case "&gt;": $operation = new MoveOperation(1); break; case "&lt;": $operation = new MoveOperation(-1); break; case "+": $operation = new ChangeOperation(1); break; case "-": $operation = new ChangeOperation(-1); break; case ".": $operation = new OutputOperation(); break; case ",": $operation = new InputOperation(); break; case "~": $operation = new SleepOperation(); } return $operation; } } </code></pre>
[]
[ { "body": "<p>So for starters, make the operations lazy-loaded (yeah big surprise, Haskeller says make it lazy)</p>\n\n<p>As such:</p>\n\n<pre><code>class LoopOperation implements OperationInterface {\n\n private $master = false;\n private $operations = array();\n\n public function __construct(array $operations, $master = false) {\n\n $this-&gt;setOperations($operations)-&gt;setMaster($master);\n }\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>class LoopOperation implements OperationInterface {\n\n public $master = false;\n public $operations = array();\n</code></pre>\n\n<p>Then you either add operations to the public array as you interpret them, or create an addOperation method, either way you need to be able to construct the LoopOperation and then as parsing continues add individual operations to it.</p>\n\n<p>Then here's some parser combinators with an error monad for ya (I don't know PHP so bear with me):</p>\n\n<pre><code>abstract class M\n{\n abstract public function then($f); // Formally this is 'bind', the f is the function to bind to the action\n\n abstract public function otherwise($f); // Formally this would be an application of an `alternative` or monoid\n\n public $a; // The a is for 'action'\n}\n\nclass Success extends M\n{\n public function __construct($a) {\n $this-&gt;a = $a;\n }\n\n public function then($f) {\n return $f($this-&gt;a);\n }\n\n public function otherwise($f) {\n return $this;\n }\n}\n\nclass Failure extends M\n{\n public function __construct($a) {\n $this-&gt;a = $a;\n }\n\n public function then($f) {\n return $this;\n }\n\n public function otherwise($f) {\n return new Success($this-&gt;a)-&gt;then($f);\n }\n}\n\npublic function pop($a) {\n return new Success(substr($a, 1));\n}\n\npublic function charIs($char) {\n return function($a) use($char) {\n if ($a[0] == $char) {\n return new Success($a);\n }\n\n return new Failure($a);\n }\n}\n\npublic function charExists($char) {\n return function($a) use($char) {\n if (strpos($a, $char) === false) {\n return new Failure($a);\n }\n\n return new Success($a);\n }\n}\n\n\npublic function addLoopOperation($operation) {\n return function($a) user ($operation) {\n $operation-&gt;addOperation(strpos($a, 0, 1));\n return new Success($a);\n }\n}\n\npublic function throwException($ex) {\n return function($a) use ($ex) {\n throw $ex;\n }\n}\n\npublic function addLoop($operation = new LoopOperation()) {\n return function($a) use (&amp;$operation) {\n return new Success($a)\n -&gt;then(charExists(\"]\"))-&gt;otherwise(throwException(new LogicException(\"Neverending loop.\"))\n -&gt;then(addLoopOperation($operation))\n -&gt;then(pop)\n -&gt;then(charIs(\"]\"))-&gt;then(pop)-&gt;otherwise(addLoop($operation));\n }\n\n // Because it's recursed the way it is, it will continue adding operations until it hits the char \"]\"\n}\n</code></pre>\n\n<p>Study closely and you'll realize the loop operation object where all the operations are added, is lost after the loop interpretation is complete, for this reason I would suggest rather than the way I'm threading the source through all the functions, actually create a structure that has source, and VM, so the functions can parse the source and push operations onto the VM as they go, the resulting code would give you ability to write things like:</p>\n\n<pre><code>while(true)\n new Success($someStructure)-&gt;then(charIs(\"[\"))-&gt;then(addLoop())-&gt;otherwise(processOperation)-&gt;then(executeOperations);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-14T05:46:01.200", "Id": "28454", "ParentId": "23707", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T00:47:40.747", "Id": "23707", "Score": "21", "Tags": [ "php", "object-oriented", "php5", "brainfuck" ], "Title": "Thoughts on my brain fart interpreter?" }
23707
<p><a href="http://en.wikipedia.org/wiki/Data_validation" rel="nofollow">Validation</a> is the process of checking data to make sure they meet the specifications which have been set for them. Typically, validation is used in checking user-input data, and in verifying data before storage.</p> <p>Examples of this include verifying that the characters in a phone number are numeric, and checking that a state abbreviation is exactly two letters.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T06:38:00.027", "Id": "23714", "Score": "0", "Tags": null, "Title": null }
23714
Validation is used to check data to make sure it fits whatever required specifications are set for it.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T06:38:00.027", "Id": "23715", "Score": "0", "Tags": null, "Title": null }
23715
Declaration is the part of the subprogram (procedure or function) which provides the protocol(header), but not the body of the subprogram.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T06:38:36.143", "Id": "23717", "Score": "0", "Tags": null, "Title": null }
23717
<p>The Tk toolkit is a GUI toolkit that is designed to be used from dynamic languages. It was developed originally by John Ousterhout for use with Tcl, but has subsequently been evolved to be supported with many other languages (notably Perl, Python and Ruby).</p> <p>Tk is a native toolkit on Windows and Mac OS X. On other Unix-based platforms, it is built directly on top of X11, and by default emulates the look traditionally associated with Motif (though this is configurable). It is recommended that newer applications use widgets from the Ttk set (where appropriate) as these use a theming engine that is more suitable for handling modern look-and-feels.</p> <p>One of the key features of Tk is that its behaviors are defined almost entirely through scripting (plus a powerful event binding mechanism). This gives user code great flexibility to redefine what is happening without writing new low-level programs. The low-level drawing engine is written in C and takes care to postpone actual drawing activity until an appropriate moment (typically after all pending GUI events are processed) making Tk feel extremely responsive to user activity.</p> <p>General reference links:</p> <ul> <li><a href="http://www.tcl.tk/man/tcl8.5/TkCmd/contents.htm" rel="nofollow">Tk 8.5 reference documentation</a></li> <li><a href="http://www.tkdocs.com/" rel="nofollow">Tk tutorial and higher-level documentation</a> – <em>Includes documentation for multiple languages.</em></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T06:39:50.617", "Id": "23718", "Score": "0", "Tags": null, "Title": null }
23718
The Tk toolkit is a scripted GUI toolkit that is designed to be used from dynamic languages (initially Tcl, but also Perl and Python).
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T06:39:50.617", "Id": "23719", "Score": "0", "Tags": null, "Title": null }
23719
<p>A directory is a named collection of related files or other folders that can be retrieved, moved, and otherwise manipulated as one entity.</p> <p>Directory is also an alias for the more popular term <code>folder</code>.</p> <p>The folder term is chosen to be consistent with the metaphor that the user interface is a desktop. In some OS operating systems, the term directory is used rather than folder.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T06:41:41.460", "Id": "23720", "Score": "0", "Tags": null, "Title": null }
23720
Directories is an alias for folders. Use this tag for questions about creating, managing, using, and deleting folders.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T06:41:41.460", "Id": "23721", "Score": "0", "Tags": null, "Title": null }
23721
<p><strong>In mathematics</strong>, a graph is an abstract representation of a set of objects where pairs of the objects can be connected by links. The interconnected objects are represented by mathematical abstractions called vertices, and the links that connect pairs of vertices are called edges. A graph is said <em>undirected</em> if the edges have no orientation. A graph is said <em>directed</em> if the edges are oriented. A graph is said <em>weighted</em> if there is a map from the set of the edges into a numeric set. Typically, a graph is depicted in diagrammatic form as a set of dots for the vertices, joined by lines or curves for the edges. </p> <p><strong>In computer science</strong>, a graph is an abstract data structure that is meant to implement the graph and hypergraph concepts from mathematics.</p> <p>A graph data structure consists mainly of a finite (and possibly mutable) set of ordered pairs, called <em>edges</em> or <em>arcs</em>, of certain entities called <em>nodes</em> or <em>vertices</em>. As in mathematics, an edge <code>(x,y)</code> is said to point or go from <code>x</code> to <code>y</code>. The nodes may be part of the graph structure, or may be external entities represented by integer indices or references.</p> <p>References: <a href="http://en.wikipedia.org/wiki/Graph" rel="nofollow">Wikipedia</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T07:08:24.780", "Id": "23722", "Score": "0", "Tags": null, "Title": null }
23722
A graph is an abstract representation of objects (vertices) connected by links (edges). For questions about plotting data graphically, use the [data-visualization] tag instead.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T07:08:24.780", "Id": "23723", "Score": "0", "Tags": null, "Title": null }
23723
<p>This piece of code I have written works, but I don't think its the best solution.</p> <p>What I am doing is check if a certain radio is checked if it is show this div if else show this div if this radio is checked etc.</p> <p>Can someone point me in the right direction on this one? I would love to know how to write less do more. </p> <pre><code>$(document).ready(function () { $('.Form').hide(); $('input').click(function () { &lt;!--check if its One--&gt; if ($('input[value=informed]:checked').length) { $('#ContactFormOne').show(); $("#ContactFormTwo, #ContactFormThree, #ContactFormFour, #ContactFormFive, #ContactSix'").hide(); &lt;!--check if its Two--&gt; } else if ($('input[value=release]:checked').length) { $('#ContactFormTwo').show(); $("#ContactFormOne, #ContactFormThree, #ContactFormFour, #ContactFormFive, #ContactSix'").hide(); &lt;!--check if its Three--&gt; } else if ($('input[value=intake]:checked').length) { $('#ContactFormThree').show(); $("#ContactFormTwo, #ContactFormOne, #ContactFormFour, #ContactFormFive, #ContactSix'").hide(); &lt;!--check if its Four--&gt; } else if ($('input[value=checklist]:checked').length) { $('#ContactFormFour').show(); $("#ContactFormTwo, #ContactFormOne, #ContactFormThree, #ContactFormFive, #ContactSix'").hide(); &lt;!--check if its Fiver--&gt; } else if ($('input[value=health]:checked').length) { $('#ContactFormFive').show(); $("#ContactFormTwo, #ContactFormOne, #ContactFormThree, #ContactFormFour, #ContactSix'").hide(); } }) }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T08:18:35.457", "Id": "36580", "Score": "0", "body": "Why not use the value passed as an `id` for the form elements?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T08:29:31.963", "Id": "36581", "Score": "0", "body": "How could i use the selector (this) to set up the code above to only use one if statement. So the if statement knows which input value was clicked and shows div with the relative hook and hide all the other divs." } ]
[ { "body": "<p>Though your conditions are fine, I'd suggest you for a radical change in the code.</p>\n\n<ol>\n<li>Change the <code>id</code>s as follows:\n<ul>\n<li><code>ContactFormOne</code> to <code>informed</code></li>\n<li><code>ContactFormTwo</code> to <code>release</code></li>\n<li><code>ContactFormThree</code> to <code>intake</code></li>\n<li><code>ContactFormFour</code> to <code>checklist</code></li>\n<li><code>ContactFormFive</code> to <code>health</code></li>\n</ul></li>\n<li>The code will get a lot shorter now.</li>\n</ol>\n\n<p>The code will be:</p>\n\n<pre><code>$(document).ready(function () {\n $('.Form').hide();\n $('input').on( 'change', function () {\n &lt;!--check if its One--&gt;\n var ValUe = $(this).val();\n $('.Form').hide(); //Replace the '.Form' selector with the element that is containing your contact forms.\n $('#' + ValUe).show();\n })\n});\n</code></pre>\n\n<p>where, I'm assuming you have jQuery 1.9.1.</p>\n\n<hr>\n\n<p>For a better answer, please include your HTML in the question too.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T08:37:25.730", "Id": "23727", "ParentId": "23724", "Score": "3" } } ]
{ "AcceptedAnswerId": "23727", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T08:08:29.507", "Id": "23724", "Score": "3", "Tags": [ "javascript", "jquery", "form" ], "Title": "Show one form that corresponds to the selected radio button" }
23724
<p>The output is a random sequence, and the input is the sum of the sequence.</p> <p>My solution is generating a random number <em>rand_num</em> from (0, sum_seq) at first, then draw another number randomly from (0, sum_seq - rand_num). By the way, all random numbers are integers.</p> <pre><code>import random rand_list = [] # Random sequences buffer def generater_random_list(num) : rand_num = random.randint(0, num) rand_list.append(rand_num) if num - rand_num == 0 : return 0 else : return generater_random_list(num - rand_num) </code></pre> <p>It seems strange to create a buffer out of the function, so how can I improve it?</p>
[]
[ { "body": "<h1>Using a recursive approach -</h1>\n\n<hr>\n\n<pre><code>from random import randint\n\ndef sequence(n):\n\n a = []\n\n def f(n):\n m = randint(1, n)\n if n &gt; m:\n a.append(str(m))\n return f(n - m)\n else:\n a.append(str(n))\n return n\n\n f(n)\n return ' + '.join(a) + ' = %d' % n\n</code></pre>\n\n<hr>\n\n<h3>Test code:</h3>\n\n<pre><code>for i in xrange(10):\n print sequence(20)\n</code></pre>\n\n<hr>\n\n<h3>Output:</h3>\n\n<pre><code>7 + 11 + 2 = 20\n14 + 4 + 1 + 1 = 20\n5 + 10 + 3 + 2 = 20\n1 + 17 + 1 + 1 = 20\n1 + 5 + 13 + 1 = 20\n3 + 12 + 2 + 3 = 20\n17 + 2 + 1 = 20\n18 + 2 = 20\n3 + 12 + 3 + 2 = 20\n18 + 1 + 1 = 20\n</code></pre>\n\n<hr>\n\n<h1>Using iterative approach -</h1>\n\n<hr>\n\n<pre><code>from random import randint\n\ndef sequence(n):\n\n a, m, c = [], randint(1, n), n \n while n &gt; m &gt; 0:\n a.append(str(m))\n n -= m\n m = randint(0, n)\n if n: a += [str(n)]\n return ' + '.join(a) + ' = %d' % c\n</code></pre>\n\n<hr>\n\n<h3>Test code:</h3>\n\n<pre><code>for i in xrange(10):\n print sequence(20)\n</code></pre>\n\n<hr>\n\n<h3>Ouput:</h3>\n\n<pre><code>19 + 1 = 20\n2 + 15 + 3 = 20\n2 + 3 + 12 + 3 = 20\n19 + 1 = 20\n2 + 10 + 2 + 6 = 20\n6 + 3 + 9 + 1 + 1 = 20\n14 + 2 + 3 + 1 = 20\n3 + 7 + 4 + 4 + 2 = 20\n9 + 7 + 3 + 1 = 20\n3 + 17 = 20\n</code></pre>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T11:54:47.407", "Id": "36584", "Score": "0", "body": "I didn't include `0`s, as I thought it was not a _sum_, and the output looks prettier without `0`s" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T11:43:50.353", "Id": "23729", "ParentId": "23728", "Score": "1" } }, { "body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>The function stores its results in the global variable <code>rand_list</code> and always returns 0. This is a poor design of interface for two reasons. First, if you call <code>generater_random_list</code> twice, <code>rand_list</code> now contains the concatenation of the first and second lists:</p>\n\n<pre><code>&gt;&gt;&gt; generater_random_list(10)\n0\n&gt;&gt;&gt; rand_list\n[2, 1, 5, 1, 0, 1]\n&gt;&gt;&gt; generater_random_list(10)\n0\n&gt;&gt;&gt; rand_list\n[2, 1, 5, 1, 0, 1, 9, 1]\n</code></pre>\n\n<p>(The caller could set <code>rand_list = []</code> before the second call to <code>generater_random_list</code>, but it would be really annoying to have to keep remembering to do that.)</p>\n\n<p>And second, what's the point of returning 0? That's no use to anyone. Python allows you just to write <code>return</code> as a shorthand for <code>return None</code> if you really have nothing worth returning, but here you do have something to return, namely the list of random numbers you just constructed.</p></li>\n<li><p>There's no docstring. What does this function do and how do you call it?</p></li>\n<li><p>You could choose a better name for the function than <code>generater_random_list</code>. (i) \"Generator\" is spelled with an \"o\". (ii) If you're going to name a function after its action, use the imperative form of the verb. (So use <code>sort</code> or <code>multiply</code>, rather than <code>sorter</code> or <code>multiplier</code>.) (iii) \"Generator\" has a specialized meaning in Python (referring to a <a href=\"http://docs.python.org/2/tutorial/classes.html#generators\" rel=\"noreferrer\">generator</a>), so best not to use it unless that's what you mean.</p></li>\n<li><p>The <a href=\"http://www.python.org/dev/peps/pep-0008/#pet-peeves\" rel=\"noreferrer\">Python style guide (PEP8)</a> says, \"Avoid extraneous whitespace immediately before a comma, semicolon, or colon.\"</p></li>\n<li><p>When you're writing a function that produces a sequence of items, it's usually a good idea in Python to make it into a <a href=\"http://docs.python.org/2/tutorial/classes.html#generators\" rel=\"noreferrer\">generator function</a> that yields the items one by one (rather than a normal function that builds and returns a list of all the items). It's often convenient to process these items one by one, and a generator function allows you to do this without having to construct an intermediate list in memory. (And if you need a list, it's trivial to build one, by passing your generator to the function <code>list</code>.)</p></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<pre><code>def random_ints_with_sum(n):\n \"\"\"\n Generate non-negative random integers summing to `n`.\n \"\"\"\n while n &gt; 0:\n r = random.randint(0, n)\n yield r\n n -= r\n</code></pre>\n\n<p>And here are some example calls:</p>\n\n<pre><code>&gt;&gt;&gt; list(random_ints_with_sum(10))\n[9, 1]\n&gt;&gt;&gt; list(random_ints_with_sum(10))\n[10]\n&gt;&gt;&gt; list(random_ints_with_sum(10))\n[0, 2, 8]\n</code></pre>\n\n<h3>3. Comments on your design</h3>\n\n<ol>\n<li><p>Do you really mean to include 0 among the random integers? This suggests that you would be happy with</p>\n\n<pre><code>&gt;&gt;&gt; list(random_ints_with_sum(1))\n[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]\n</code></pre>\n\n<p>and similar outputs. You don't say what you are using this function for, so I can't tell if this is right or wrong, but it looks well dodgy to me.</p></li>\n<li><p>Even with 0 excluded, your implementation samples its range with a lot of bias. For example, the number 4 has eight ordered partitions into positive integers:</p>\n\n<pre><code>4 3, 1 2, 2 2, 1, 1 1, 3 1, 2, 1 1, 1, 2 1, 1, 1, 1\n</code></pre>\n\n<p>but your algorithm doesn't sample these partitions evenly. Here's a test program that calls <code>random_ints_with_sum(4)</code> a million times, and counts the number of times each result was generated:</p>\n\n<pre><code>&gt;&gt;&gt; from collections import Counter\n&gt;&gt;&gt; Counter(tuple(random_ints_with_sum(4)) for _ in xrange(10 ** 6))\n</code></pre>\n\n<p>Here are the results:</p>\n\n<pre><code>Partition Count\n----------- ------\n4 249997\n3, 1 250047\n2, 2 124579\n2, 1, 1 125113\n1, 3 83425\n1, 2, 1 83190\n1, 1, 2 41875\n1, 1, 1, 1 41774\n</code></pre>\n\n<p>If the partitions had been generated uniformly, each would have appeared about 125,000 times in the results. You can see that shorter partitions are generated more frequently, and longer partitions less frequently than in the uniform distribution.</p>\n\n<p>Again, since you don't explain what your function is for, I can't tell whether this kind of bias is important or not.</p></li>\n</ol>\n\n<h3>4. Sampling partitions uniformly</h3>\n\n<p>Supposing that you wanted to sample the space of ordered integer partitions uniformly, how could you implement it?</p>\n\n<p>First we have to know how to count ordered integer partitions. And to do that, there's a neat combinatorial observation. Consider a group of objects waiting to be partitioned:</p>\n\n<p><img src=\"https://i.stack.imgur.com/OuDoM.png\" alt=\"Four objects with three locations for partition\"></p>\n\n<p>If there are <em>n</em> objects, there are <em>n</em> − 1 locations where you could insert a partition (indicated by the dotted lines). For example, if we insert partitions at the first and the third locations, we get the partition 1, 2, 1:</p>\n\n<p><img src=\"https://i.stack.imgur.com/2Omfm.png\" alt=\"Four objects partitioned as 1, 2, 1\"></p>\n\n<p>Each subset of locations corresponds to a different ordered partition, and each ordered partition corresponds to a different subset of locations. This means that we can choose an ordered partition uniformly by choosing a subset of locations uniformly. There are 2<sup><em>n</em> − 1</sup> subsets of the <em>n</em> − 1 locations (for example, 4 objects have 2<sup>3</sup> = 8 ordered partitions, as noted above), and we can choose one of these subsets uniformly by putting each location into the subset with probability ½.</p>\n\n<p>Here's a revised function that implements the new algorithm:</p>\n\n<pre><code>def random_ints_with_sum(n):\n \"\"\"\n Generate positive random integers summing to `n`, sampled\n uniformly from the ordered integer partitions of `n`.\n \"\"\"\n p = 0\n for _ in xrange(n - 1):\n p += 1\n if random.randrange(2):\n yield p\n p = 0\n yield p + 1\n</code></pre>\n\n<p>And here's an example distribution after a million calls to the revised function:</p>\n\n<pre><code>Partition Count\n----------- ------\n4, 125042\n3, 1 124848\n2, 2 125189\n2, 1, 1 125126\n1, 3 124861\n1, 2, 1 125152\n1, 1, 2 124248\n1, 1, 1, 1 125534\n</code></pre>\n\n<p>You'll see that this is very close to uniform.</p>\n\n<p>Again, I should emphasize that since I don't know what your function is going to be used for, I don't know whether changing it so that it samples uniformly from the ordered integer partitions is the right thing to do. But if it is, now you know how to do it.</p>\n\n<p>(Who would have thought there would be so much to write about a six-line function?)</p>\n\n<h3>5. Chinese restaurant process</h3>\n\n<p>You updated your question to say that you are trying to simulate a <a href=\"http://en.wikipedia.org/wiki/Chinese_restaurant_process\" rel=\"noreferrer\">Chinese restaurant process</a>. I have to say that I can't relate the code in your question to this process, which has nothing to do with numbers that sum to a particular total. So I'm puzzled! Maybe you can say more about how the code you posted relates to this process?</p>\n\n<p>Anyway, if you want to generate a sample from this distribution, the easiest thing to do is to simulate the process directly:</p>\n\n<pre><code>def chinese_restaurant_partition(n):\n \"\"\"\n Return a random partition of the numbers from 1 to n generated by\n the Chinese restaurant process.\n \"\"\"\n partition = [] # list of sets\n assignment = [] # set each number is assigned to\n for i in xrange(n):\n r = random.randrange(i + 1)\n if r &lt; i:\n # assign i + 1 to existing block\n block = assignment[r]\n else:\n # create new block\n block = set()\n partition.append(block)\n block.add(i + 1)\n assignment.append(block)\n return partition\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>&gt;&gt;&gt; chinese_restaurant_partition(4)\n[set([1]), set([2, 4]), set([3])]\n</code></pre>\n\n<p>This distribution looks like this (again, after generating a million samples):</p>\n\n<pre><code>Partition Count\n---------- ------\n1234 249231\n134, 2 83453\n124, 3 82664\n123, 4 83569\n1, 234 83161\n14, 23 42126\n13, 24 41688\n12, 34 41726\n14, 2, 3 41891\n13, 2, 4 41569\n12, 3, 4 42022\n1, 24, 3 41522\n1, 23, 4 41719\n1, 2, 34 41867\n1, 2, 3, 4 41792\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T12:22:32.547", "Id": "23731", "ParentId": "23728", "Score": "13" } } ]
{ "AcceptedAnswerId": "23731", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T08:45:56.317", "Id": "23728", "Score": "7", "Tags": [ "python", "random" ], "Title": "Generating random sequences while keeping sum fixed" }
23728
<p>I was playing with some of the wonderful new C++11 features and tried to reimplement a function <code>reversed</code> that would behave just like the one in Python to allow reverse iteration on bidirectional iterables.</p> <p>And to clarify since I'm been told that I was unclear, that <code>reverse</code> function would be used in range-based for loops. Also, I define an iterator as whatever satisfies the functions <code>std::begin</code> and <code>std::end</code> (<code>ForwardIterator</code> concept). I don't think I've got to explain what a bidirectional iterator is... :D</p> <p>Here's my code:</p> <pre><code>template&lt;typename BidirectionalIterable&gt; class ReversedObject { private: BidirectionalIterable&amp; _iter; ReversedObject(BidirectionalIterable&amp;&amp; iter): _iter(iter) {} public: using value_type = typename std::decay&lt;decltype(*std::begin(_iter))&gt;::type; using difference_type = std::ptrdiff_t; using reference = value_type&amp;; using pointer = value_type*; using iterator = typename std::remove_reference&lt;decltype(itertools::rbegin(_iter))&gt;::type; using const_iterator = typename std::remove_reference&lt;decltype(itertools::rbegin(_iter))&gt;::type; using reverse_iterator = decltype(std::begin(_iter)); using const_reverse_iterator = decltype(std::begin(_iter)); using iterator_category = typename std::iterator_traits&lt;iterator&gt;::iterator_category; // Iterator functions auto begin() -&gt; iterator { return itertools::rbegin(_iter); } auto begin() const -&gt; const_iterator { return itertools::rbegin(_iter); } auto cbegin() const -&gt; const_iterator { return itertools::rbegin(_iter); } auto end() -&gt; iterator { return itertools::rend(_iter); } auto end() const -&gt; const_iterator { return itertools::rend(_iter); } auto cend() const -&gt; const_iterator { return itertools::rend(_iter); } // Reverse iterator functions auto rbegin() -&gt; reverse_iterator { return std::begin(_iter); } auto rbegin() const -&gt; const_reverse_iterator { return std::begin(_iter); } auto crbegin() const -&gt; const_reverse_iterator { return std::begin(_iter); } auto rend() -&gt; reverse_iterator { return std::end(_iter); } auto rend() const -&gt; const_reverse_iterator { return std::end(_iter); } auto crend() const -&gt; const_reverse_iterator { return std::end(_iter); } friend auto reversed&lt;&gt;(BidirectionalIterable&amp;&amp; iter) -&gt; ReversedObject&lt;BidirectionalIterable&gt;; }; template&lt;typename BidirectionalIterable&gt; inline auto reversed(BidirectionalIterable&amp;&amp; iter) -&gt; ReversedObject&lt;BidirectionalIterable&gt; { return { std::forward&lt;BidirectionalIterable&gt;(iter) }; } </code></pre> <hr> <p>In order for that code to work, I had to write the global functions <code>rbegin</code> and <code>rend</code> with specializations for fixed-size arrays. Since c++14, these functions can be replaced by the standard functions <a href="http://en.cppreference.com/w/cpp/iterator/rbegin" rel="nofollow"><code>std::rbegin</code></a> and <a href="http://en.cppreference.com/w/cpp/iterator/rend" rel="nofollow"><code>std::rend</code></a>.</p> <pre><code>template&lt;typename T&gt; auto rbegin(T&amp; iter) -&gt; decltype(iter.rbegin()) { return iter.rbegin(); } template&lt;typename T&gt; auto rbegin(const T&amp; iter) -&gt; decltype(iter.crbegin()) { return iter.crbegin(); } template&lt;typename T, std::size_t N&gt; auto rbegin(T (&amp;array)[N]) -&gt; std::reverse_iterator&lt;T*&gt; { return std::reverse_iterator&lt;T*&gt;(std::end(array)); } template&lt;typename T&gt; auto rend(T&amp; iter) -&gt; decltype(iter.rend()) { return iter.rend(); } template&lt;typename T&gt; auto rend(const T&amp; iter) -&gt; decltype(iter.crend()) { return iter.crend(); } template&lt;typename T, std::size_t N&gt; auto rend(T (&amp;array)[N]) -&gt; std::reverse_iterator&lt;T*&gt; { return std::reverse_iterator&lt;T*&gt;(std::begin(array));; } </code></pre> <p>Is there any way I could improve this construct's design? :)</p> <hr> <p>Example of use case of the class:</p> <pre><code>int array[] = { 1, 2, 3, 4, 5 }; std::vector&lt;int&gt; vec = { 6, 7, 8, 9, 123 }; // Reverse iteration with fixed-size arrays for (int i: reversed(array)) { std::cout &lt;&lt; i &lt;&lt; std::endl; } // Reverse iteration with standard containers for (auto&amp; i: reversed(vec)) { i *= 5; std::cout &lt;&lt; i &lt;&lt; std::endl; } // Reverse iteration with initilizer_list for (const char* str: reversed({"one", "two", "three"})) { std::cout &lt;&lt; str &lt;&lt; std::endl; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T16:28:48.880", "Id": "36614", "Score": "0", "body": "Is an 'iterable' a container usually? Everywhere you use `iter` is tremendously confusing because that usually means *iterator* not *iterable* (container)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T16:31:40.860", "Id": "36616", "Score": "0", "body": "What's the point of this class? If you plug in `std::vector` for instance you just get a subset of the functionality that `std::vector` gave you in the first place? Is it for pseudo-*concepts* purposes? But if so, maybe accepting a `begin` and `end` and using SFINAE and `iterator_traits` to disallow the method unless the iterator is bidirectional is a better option" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T18:50:02.927", "Id": "36635", "Score": "0", "body": "@Dave I expressed the purpose in the introduction: find a simple way to use reverse iteration on iterables on C++11 foreach loops. Nothing to do with concepts or anything. I just liked how simple it was in Python and tried to mimick it in C++11." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T22:13:20.783", "Id": "36654", "Score": "0", "body": "You never mentioned foreach loops. I don't know how it is in Python. I also don't entirely know what you mean by iterable. I mostly get it. See my first comment. Now that you have mentioned C++11 range based for loops (presumably what you were referring to), check out the proposal for a `std::range`. It entirely covers your use case here. I would link it, but I don't feel particularly inclined to help *too* much after that response..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T00:52:48.930", "Id": "36658", "Score": "0", "body": "@Dave Well, that's true that I may have forgotten to mention the foreach loop, but `reversed` was introduced in Python mostly for that loop (see PEP 322). I would have defined an iterable object by whichever object that could be used with the functions `std::begin` and `std::end` (at least forward iterable that is, see `iterator_concept` for more details). I already knew about `std::range`, but it's still not in the standard and I would simply like for my class to be usesable with the components that already exist in N3485^^" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T01:02:32.020", "Id": "36659", "Score": "0", "body": "So implement std::range yourself or download the library being developed by the authors. It's more useful than this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T01:37:36.703", "Id": "36661", "Score": "0", "body": "Also: http://www.boost.org/doc/libs/1_53_0/libs/range/doc/html/range/reference/adaptors/reference/reversed.html" } ]
[ { "body": "<p>Overall I like this helper. Most potential complaints are due to evaluating how well it would handle something it wasn't intended to support. Here are some of my thoughts from examining its implementation.</p>\n\n<p>This code goes out of its way to define a lot of names for types that are not used directly by the consuming code (<code>value_type</code>, <code>difference_type</code>, etc.), nor by my understanding of the mechanisms of range-based for. Yet it doesn't offer an explicit overload for <code>std::begin</code> and friends.</p>\n\n<p>There's no specialization for <code>reversed(reversed(container))</code>. While this is probably fine because it's unlikely to come up, and likely to be inlined down to the original container, I almost expected to see something like this explicitly cover this case:</p>\n\n<pre><code>template&lt;typename BidirectionalIterable&gt;\ninline auto reversed(ReversedObject&lt;BidirectionalIterable&gt;&amp;&amp; iter)\n -&gt; BidirectionalIterable\n{\n return { std::forward&lt;BidirectionalIterable&gt;(iter._iter) };\n}\n</code></pre>\n\n<p>As other commenters have said, calling it <code>iter</code> in a c++ world is a bit confusing. Then again calling it <code>iter</code> in python would be stomping on the builtin. So I would recommend renaming it <code>iterable</code> or <code>container</code>.</p>\n\n<p>It would be interesting to try to reveal more of the underlying container per Dave's comment about a subset of a vector's functionality. If this is only ever used directly in a range-based for loop, that's not too important. But if someone starts saving reversed containers (it could be interesting to have a vector that effectively has a <code>push_front</code> instead of a <code>push_back</code>), it would become frustrating to lack other methods. Could an approach that derives from the reversed container do the trick? Hmm, probably not; this would typically result in copying the full data structure, <code>operator[]</code> would have to be adjusted, and <code>data()</code> would fall apart. But that thought about copying brings up another point. The name <code>ReversedObject</code> is misleading; it's more like a <code>ReversedView</code>.</p>\n\n<p>I do like the fact that trying to reverse something that doesn't have reverse iterators will fail at compile time, even if its iterators are not invoked. The following gave me clear compilation errors:</p>\n\n<pre><code>struct NonReversible {};\nauto a = NonReversible();\nauto b = reversed(a); // clear errors pointing here\n</code></pre>\n\n<p>I don't like the <code>itertools</code> items as much. If we could just jump ahead to C++14, that'd be fine. Outside that, my first inclination is that I'd rather see this specialization done as a partial specialization of the <code>ReversedObject</code> class. But it's more reusable the way you did it, and the way C++ is going, so it's hard to justify my reaction.</p>\n\n<p>Thanks for the interesting code to review. It makes me want to try to write a <code>zip</code> for range-based for loops. (Even though it's <a href=\"https://stackoverflow.com/questions/8511035/sequence-zip-function-for-c11\">already been done</a> too.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T21:35:43.277", "Id": "57668", "Score": "0", "body": "At first, it was only intended to be used in a range-based `for` loop. Therefore, I think you're right, I can delete `value_type` and its friends. I will also rename `iter` to `iterable`, you're right :)\nI'll also delete the `itertools` stuff and use C++14, I did not realize that I left that in place..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-16T19:23:57.453", "Id": "276710", "Score": "0", "body": "fwiw, I disagree with explicitly covering `reversed(reversed(t))` - `reversed` should almost always produce a zero overhead layer (totally optimized out out of existence) so it doesn't matter. Plus, who would write that?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-17T16:46:28.877", "Id": "35539", "ParentId": "23734", "Score": "3" } } ]
{ "AcceptedAnswerId": "35539", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T14:09:20.377", "Id": "23734", "Score": "8", "Tags": [ "python", "c++", "c++11", "iterator", "reinventing-the-wheel" ], "Title": "Python reversed in C++11" }
23734
<p>I need to refactor this code, targeted to Google Chrome (current+) to make it manageable going forward.</p> <p><a href="http://jsbin.com/unazig/1/" rel="nofollow">Here</a> is a working JSBin of the idea.</p> <p>The messiness comes from determining the accurate number of lines of text, and the real heights of elements. I know I am passing this information around <em>too much</em>, without enough structure, and recalculating too many things. I also know it is messy, especially inside <code>scal_el</code> and <code>run_scan</code>.</p> <pre><code>function scan_el(el_fin_callback,el,mask,sub_mask,real_height,real_width,push,lines,line) { line = line || 0; if(line &gt;= lines) { el_fin_callback(); return; // scan finished } var current_line = real_height*line; var line_os = $(el).offset(); line_os.top += current_line; if(lines &gt; 1) { $(mask)[0].style.height = real_height+'px'; } $(sub_mask).css( { 'height' : $(el).height()-real_height-current_line } ); $(mask).offset(line_os); line_os.top += real_height; var length = Math.ceil($(el).text().length*real_width)+push; if(lines &gt; 1) { length = $(el).width(); } $(sub_mask).offset(line_os); function next_line() { // callback after scan complete scan_el(el_fin_callback,el,mask,sub_mask,real_height,real_width,push,lines,line+1); } run_line_scan(length,mask,next_line); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T15:20:16.887", "Id": "36600", "Score": "0", "body": "I think you'd be better off figuring out how to parse the HTML-layout into a big fat pre-blob of text, and running the scan on that, character-by-character. Each character is a single span, I suppose, with visibility changed as required. This would give you dynamic and flexible layout, with an easier method of performing the display. \"Easier\" assuming you can translate to the big fat text-blob in the first place." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T15:27:08.257", "Id": "36601", "Score": "0", "body": "In the link above, the display seems wonky in FF19 (it doesn't work at all in IE9). However, when I switch to the edit mode @ http://jsbin.com/unazig/1/edit THEN it seems to display okay, in an abbreviated right-bar." } ]
[ { "body": "<p>There are only two things I can think of.</p>\n\n<h3>Sometimes it's best to pass objects when there are more than 4 parameters for a method call.</h3>\n\n<p>Instead of this</p>\n\n<pre><code>function scan_el(el_fin_callback, el, mask, sub_mask, real_height, real_width, push, lines, line) {\n</code></pre>\n\n<p>Try this.</p>\n\n<pre><code>function scan_el(el_fin_callback, els, metrics, lines, line) {\n</code></pre>\n\n<p><code>els</code> and <code>metrics</code> would look something like this.</p>\n\n<pre><code>els = {\n el : jQuery,\n mask : jQuery,\n submask : jQuery\n};\nmetrics = {\n real_width : Number,\n real_height : Number,\n push : Number\n}\n</code></pre>\n\n<h3>Try to make functions no longer than 8-12 lines.</h3>\n\n<p>You could extract the <code>real_*</code> variables into a function and return a object instead of a list of variables.</p>\n\n<pre><code>function getRealMetrics(el){\n // doesn't work completely\n var real = {};\n real.box = window.getComputedStyle(el);\n real.width = parseFloat(real.box.width);\n real.height = parseFloat(real.box.height);\n real.el = el.getBoundingClientRect();\n real.el_style = window.getComputedStyle(el);\n real.el_padding = parseFloat(real.el_style.padding);\n real.el_padding_left = parseFloat(real.el_style.paddingLeft);\n real.el_margin_left = parseFloat(real.el_style.marginLeft);\n real.el_align = real.el_style.textAlign;\n\n if (!isNaN(real.el_padding)) {\n real.el_height -= real.el_padding * 2.0;\n }\n var lines = Math.ceil(real.el_height / real.height);\n if (lines &gt; 1) {\n length = real.el.width;\n }\n real.el_push = real.el_margin_left + real.el_padding_left + (real.el.width - length) / 2.0;\n if (real.el_align !== 'center') {\n real.el_push = real.el_margin_left + real.el_padding;\n }\n return result;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T17:12:58.917", "Id": "23746", "ParentId": "23735", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T14:14:00.793", "Id": "23735", "Score": "5", "Tags": [ "javascript", "jquery", "animation" ], "Title": "Retrocomputing scanline function" }
23735
<p>This is the code:</p> <pre><code>public DateTime GibSomeStartDate(IEnumerable&lt;int&gt; partnerNumbers, DateTime startTime) { return (from contract in this.databaseContext.Contract where partnerNumbers.Contains(contract.Pnr) &amp;&amp; contract.SomeDateTime &gt;= startTime select contract.SomeDateTime).Min(); } </code></pre> <p><code>databaseContext</code> Instance is child of <code>Entity Framework</code> <code>DbContext</code></p> <p>My refactorings objectives:</p> <ul> <li><p>make it compact</p></li> <li><p>check if <code>from where select</code> finds nothing. In this<br> situation <code>Min()</code> will cause an Excetion </p></li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T14:56:03.907", "Id": "36597", "Score": "0", "body": "I wasnt sure whether this question for this site or fot http://programmers.stackexchange.com If I have post it on the false one - migrate it please. Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T14:59:57.957", "Id": "36598", "Score": "1", "body": "Well, what should the function return if `partnerNumbers` is empty?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T15:08:36.470", "Id": "36599", "Score": "0", "body": "@Leonid partnerNumbers cannot be empty" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T16:14:20.433", "Id": "36609", "Score": "0", "body": "thank you for your answers - have upvoted all of you )) I ll mark the one I find the best next days." } ]
[ { "body": "<p>I'd do it like this:</p>\n\n<pre><code>public DateTime GibSomeStartDate(IEnumerable&lt;int&gt; partnerNumbers, DateTime startTime)\n{\n return this.databaseContext.Contract\n .Where(c =&gt; c.SomeDateTime &gt;= startTime &amp;&amp; partnerNumbers.Contains(c.Pnr))\n .Min(c =&gt; (DateTime?)c.SomeDateTime) ?? DateTime.MinValue;\n}\n</code></pre>\n\n<p><strong>Edit:</strong> Stole the <code>(DateTime?)</code> idea from Jesse C. Slicer's answer, but didn't modify the function signature. You can also return <code>DateTime.MaxValue</code> if that is more useful to you, or you can go with his idea of returning <code>DateTime?</code>, in which case you don't need that at all. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T07:33:30.367", "Id": "36666", "Score": "0", "body": "it doesnt work. \"System.NotSupportedException: Unable to create a null constant value of type 'System.Collections.Generic.IEnumerable`\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T07:35:42.033", "Id": "36667", "Score": "0", "body": "It doesnt work cause of condition in my answer: \"check if from where select finds nothing. In this\nsituation Min() will cause an Excetion\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T14:17:38.670", "Id": "36679", "Score": "0", "body": "@MikroDel - Wait... you *want* it to throw the exception? Why do you need to refactor it, then?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T15:14:23.667", "Id": "36683", "Score": "0", "body": "the Exception was cause I have wrong parameter ) Your answer is good" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T18:42:21.120", "Id": "36701", "Score": "0", "body": "It might be worth considering swapping the order of the date comparison and the contains check inside the where clause, particularly if `partnerNumbers` is expected to be a large collection." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T13:53:55.103", "Id": "36749", "Score": "0", "body": "@DanLyons - Good suggestion. Edited." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T15:26:28.770", "Id": "23737", "ParentId": "23736", "Score": "3" } }, { "body": "<p>Not compact but it will not cause an exception:</p>\n\n<pre><code>public DateTime GibSomeStartDate(IEnumerable&lt;int&gt; partnerNumbers, DateTime startTime)\n{\n return (from contract in this.databaseContext.Contract\n where partnerNumbers.Contains(contract.Pnr) &amp;&amp; contract.SomeDateTime &gt;= startTime\n orderby contract.SomeDateTime descending\n select contract.SomeDateTime).FirstOrDefault(); //default(DateTime)\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T16:24:52.597", "Id": "36613", "Score": "0", "body": "This might be slower than a good old Min." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T18:33:23.450", "Id": "36634", "Score": "0", "body": "Yes it might be, but if you have an index on that table with columns Pnr and SomeDateTime it can be far good enough." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T15:27:33.200", "Id": "23738", "ParentId": "23736", "Score": "2" } }, { "body": "<p>This can be accomplished with a slight modification to your method signature and an extension method:</p>\n\n<p>Here, the signature now can return <code>null</code> if there are no records selected:</p>\n\n<pre><code>public DateTime? GibSomeStartDate(IEnumerable&lt;int&gt; partnerNumbers, DateTime startTime)\n{\n return (from contract in this.databaseContext.Contract\n where partnerNumbers.Contains(contract.Pnr) &amp;&amp; contract.SomeDateTime &gt;= startTime\n select contract.SomeDateTime).SafeMin(someDateTime =&gt; (DateTime?)someDateTime);\n}\n</code></pre>\n\n<p>This extension method will trap <code>Min</code>'s exception and return <code>null</code> instead:</p>\n\n<pre><code>public static U? SafeMin&lt;T, U&gt;(this IEnumerable&lt;T&gt; source, Func&lt;T, U?&gt; selector) where U : struct\n{\n try\n {\n return source.Min(selector);\n }\n catch\n {\n return null;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T15:38:36.323", "Id": "36604", "Score": "1", "body": "I like the idea of changing the signature, but I don't like the extension method. Better to not throw an exception in the first place than to throw and catch one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T15:52:13.373", "Id": "36607", "Score": "1", "body": "I'd agree in the case that the exception occurs frequently. But if it's a super-rare occurrence (the `where` always filters to at least one item), then there's no harm, no foul. In the other case, you're always having to do a conditional check, which may be expensive over the long haul." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T16:07:28.117", "Id": "36608", "Score": "0", "body": "you'll have to download all the dates to client in order to find the minimum value. And having a try/catch as a control flow is not a good approach. Use `DefaultIfEmpty` instead" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T16:24:47.473", "Id": "36612", "Score": "0", "body": "Not sure if I understand completely as I don't know how it (download all dates to the client) would be different from using the regular `Min` supplied by LINQ. Are you saying that rather Peter Kiss' solution, which doesn't use `Min` is the right way to go for performance's sake?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T06:43:52.350", "Id": "36665", "Score": "1", "body": "Throwing an exception is a heavy cost stuff, try: return source.Any() ? source.Min(selector) : null; but you still have to download all dates as almaz said." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T15:30:41.753", "Id": "23739", "ParentId": "23736", "Score": "5" } } ]
{ "AcceptedAnswerId": "23737", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T14:49:59.357", "Id": "23736", "Score": "3", "Tags": [ "c#", "linq" ], "Title": "Rewrite from .. where .. select to more compact one" }
23736
<p>This method assigns the value of a specified column in a <code>DataRow</code> to specified property in an object. </p> <p>I have 3 conditionals handling exceptions, and I want these conditions to throw exceptions. </p> <p>The final condition just allows the use of a conversion method if it exists. Is there a better way to test for and throw the exceptions?</p> <pre><code>public class ColumnToPropertyMap&lt;colType, propType&gt; { public string ColumnName { get; private set; } public string PropertyName { get; private set; } private Func&lt;colType, propType&gt; conversion; public virtual void Map&lt;T&gt;(T obj, DataRow row) { if (!row.Table.Columns.Contains(this.ColumnName)) { throw new ArgumentException( String.Format(@"Column ""{0}"" does not exist in the row.", this.ColumnName)); } PropertyInfo property = obj.GetType().GetProperty(this.PropertyName); if (property == null) { throw new ArgumentException(String.Format(@"Property ""{0}"" does not exist for object.", this.PropertyName)); } var value = row.IsNull(this.ColumnName) ? row[this.ColumnName].GetDefaultValue(typeof(colType)) : row[this.ColumnName]; if (conversion == null &amp;&amp; property.PropertyType != row.Table.Columns[this.ColumnName].DataType) { throw new InvalidCastException( string.Format(@"Mapping for {0} to {1} failed. Unable to convert {2} to {3}.", this.ColumnName, this.PropertyName, value.GetType(), property.PropertyType)); } if (conversion != null) { value = conversion((colType)value); } property.SetValue(obj, value, null); } } </code></pre> <p>Incorporating @Leonid and @SmartLemons comments/answers into consideration, I changed it to this:</p> <pre><code> public virtual void Map&lt;T&gt;(T obj, DataRow row) { PropertyInfo property = obj.GetType().GetProperty(this.PropertyName); ValidateArguments(property, row); var value = row.IsNull(this.ColumnName) ? row[this.ColumnName].GetDefaultValue(typeof(colType)) : row[this.ColumnName]; if (conversion != null) { value = conversion((colType)value); } property.SetValue(obj, value, null); } private void ValidateArguments(PropertyInfo property, DataRow row) { if (!row.Table.Columns.Contains(this.ColumnName)) { throw new ArgumentException( String.Format(@"Column ""{0}"" does not exist in the row.", this.ColumnName)); } if (property == null) { throw new ArgumentException(String.Format(@"Property ""{0}"" does not exist for object.", this.PropertyName)); } if (conversion == null &amp;&amp; property.PropertyType != row.Table.Columns[this.ColumnName].DataType) { throw new InvalidCastException( string.Format(@"Mapping for {0} to {1} failed. Unable to convert {2} to {3}.", this.ColumnName, this.PropertyName, row.Table.Columns[this.ColumnName].DataType.Name, property.PropertyType)); } } </code></pre> <p>Takes the argument validation out of the method and makes the intent of the <code>Map</code> method clearer.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T19:28:51.313", "Id": "36643", "Score": "0", "body": "What do you not like about your approach?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T19:33:08.177", "Id": "36644", "Score": "0", "body": "It's not that I don't like it, I was more wondering if someone had a better, or different way. The multiple ifs seem slightly unwieldy, but I didn't see another way to go about it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T19:45:42.393", "Id": "36645", "Score": "2", "body": "The first if could be its own method. The line that creates a property and checks it could be itself a private property. The following if can also be its own method. You cannot skip the logic, but you can cut it into smaller chunks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T20:22:48.257", "Id": "36646", "Score": "0", "body": "I had considered creating a private PropertyInfo property for the class, but that would require passing in either the obj that is having the properties mapped, or the PropertyInfo object as part of the constructor, and I wanted to keep the constructor as simple as possible. (Right now, it's just `public ColumnToPropertyMap(string columnName, string propertyName){}`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T21:10:16.330", "Id": "36651", "Score": "0", "body": "@Leonid You should put your second comment as an answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T03:25:20.077", "Id": "36725", "Score": "0", "body": "I agree. @Leonid has valid comments that would clean this up. Otherwise, move formats and long strings to Settings properties that are descriptive and read well. I know that doesn't help with the `if-block` logic, but it greatly improves readability. ;)" } ]
[ { "body": "<p>Your code is as simple as it can get... but if you are wanting to clean up the method then you could do something like this to make it look nicer. </p>\n\n<pre><code>public string ColumnName { get; private set; }\n public string PropertyName { get; private set; }\n private Func&lt;colType, propType&gt; conversion;\n\n public virtual void Map&lt;T&gt;(T obj, DataRow row)\n {\n Conditions.Check1(row, this.ColumnName).argerror(String.Format(@\"Column \"\"{0}\"\" does not exist in the row.\", this.ColumnName));\n PropertyInfo property = obj.GetType().GetProperty(this.PropertyName);\n Conditions.Check2(property).argerror(String.Format(@\"Property \"\"{0}\"\" does not exist for object.\", this.PropertyName));\n var value = row.IsNull(this.ColumnName) ? row[this.ColumnName].GetDefaultValue(typeof(colType)) : row[this.ColumnName];\n Conditions.Check3(conversion, property, row, this.ColumnName).casterror(string.Format(@\"Mapping for {0} to {1} failed. Unable to convert {2} to {3}.\", this.ColumnName, this.PropertyName, value.GetType(), property.PropertyType));\n if (conversion != null)\n {\n value = conversion((colType)value);\n }\n property.SetValue(obj, value, null);\n }\n\n public static class Conditions\n {\n public class Error\n {\n private bool error = false;\n public bool isError { get {return error;}}\n\n public Error(bool r)\n {\n error = r;\n }\n public bool argerror(string message)\n {\n if (error)\n throw new ArgumentException(message);\n return error;\n }\n public bool casterror(string message)\n {\n if (error)\n throw new InvalidCastException(message);\n return error;\n }\n\n }\n public static Error Check1(dynamic a, string cn)\n {\n return new Error(a.Table.Columns.Contains(cn));\n }\n public static Error Check2(dynamic a)\n {\n return new Error(a == null);\n }\n public static Error Check3(dynamic a, dynamic b, dynamic c, string cn)\n {\n return new Error(a == null &amp;&amp; b.PropertyType != c.Table.Columns[cn].DataType);\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T10:05:20.290", "Id": "23830", "ParentId": "23742", "Score": "2" } } ]
{ "AcceptedAnswerId": "23830", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T16:12:25.307", "Id": "23742", "Score": "4", "Tags": [ "c#", "exception-handling" ], "Title": "Is there a better way to test for the exception conditions?" }
23742
<p>I am very new to GUI programming, and I'm pretty sure I'm doing it wrong. Please take a look at my code, and suggest some changes. I feel it's way too complicated for what it's actually doing. </p> <p>For example, here is my main class:</p> <pre><code>''' Written by blacksheep March 4, 2013 ''' ################# # IMPORTS # ################# from Tkinter import * from ship_model import Ship, ShipLoader import time from grid_model import GridModel from ship_ai import ShipAI from ship_placement_panel import ShipPlacementPanel from ship_grid import ShipGrid from ship_war_panel import ShipWarPanel from ship_panel import ShipPanel from player_controller import PlayerController ################# # MAIN CLASS # ################# class Game(Frame): '''Top-level Frame managing top-level events. Interact directly with user.''' ############ geometry ############### X_PADDING = 25 Y_PADDING = 25 SHIP_PANEL_WIDTH = 150 ##################################### ########### states ################## PLACING = 0 PLAYING = 1 GAME_OVER = 2 ##################################### ############ players ################ AI_PLAYER = 0 HUMAN_PLAYER = 1 ##################################### def __init__(self, master): '''Create the UI for a game of battleship.''' Frame.__init__(self, master) self._create_ui() # these are 'controller' elements that should really be in another class self.ai = ShipAI(self._their_grid._model, self._my_grid._model) self.reset() def _create_ui(self): '''Create all UI elements for the game.''' self._add_grids() self._add_staging_panel() self._add_ship_panels() self._make_buttons() # here 50 is an estimate for the size of the button self.config(height=self.Y_PADDING * 3 + self._my_grid.size + 50) self.set_all_bgs("white", self) def _add_staging_panel(self): '''Create the placement/ship staging panel.''' self._my_grid_frame._staging_panel = ShipPlacementPanel(self) self._my_grid_frame._staging_panel.place( x=self.X_PADDING * 2 + self.SHIP_PANEL_WIDTH + self._my_grid.size, y=self.Y_PADDING ) def set_all_bgs(self, color, parent): '''Set all the backgrounds of the child widgets to a certain color.''' parent.config(background=color) for child in parent.winfo_children(): self.set_all_bgs(color, child) def _add_ship_panels(self): '''Add a list of ships to select from, for adding. Note that staging area must be added FIRST''' ############################## ShipPanel ######################## self._my_grid_frame._ship_panel = ShipPanel(self) self._my_grid_frame._ship_panel.place(x=self.X_PADDING, y=self.Y_PADDING * 4) for ship in Ship.SHORT_NAMES: self._my_grid_frame._ship_panel._ship_buttons[ship].config(command=self._stage_current_ship) self.unselect_ship() ################################################################## ###################### ShipWarPanel ############################## self._my_grid_frame._ship_war_panel = ShipWarPanel(self) self._my_grid_frame._ship_war_panel.place(x=self.X_PADDING, y=self.Y_PADDING * 2) ################################################################## ###################### ShipWarPanel for Adversary ################ self._their_grid_frame._ship_panel = ShipPanel(self) self._their_grid_frame._ship_panel.place(x=self._my_grid.size * 2 + self.X_PADDING * 3 + self.SHIP_PANEL_WIDTH, y=self.Y_PADDING * 4) ################################################################## def unselect_ship(self): '''Deselect all ships in the placement and staging GUIs.''' self._my_grid_frame._ship_panel._ship_var.set(10) self._my_grid_frame._staging_panel.reset() def _stage_current_ship(self): '''Stage the currently selected ship.''' if self.get_current_ship() is not None: # the x and y coordinates don't matter in this case # stage the ship vertically by default s = Ship(0, 0, self.get_current_ship(), True) self._my_grid_frame._staging_panel.add_ship(s) def _hide_frame(self, frame): '''Since you can't hide a frame per se, 'unpack' the frame's child widgets. WARNING: this removes all packing directions for children''' frame.lower() for child in frame.winfo_children(): child.pack_forget() def process_state(self): '''Simple state controller to enable and disable certain widgets depending on the state. For now, there are 2 states: - 0: ship placement - 1: playing battleship with opponent ''' if self._state == self.PLACING: self.config(width=self.X_PADDING * 3 + self._my_grid.size + self.SHIP_PANEL_WIDTH + self._my_grid_frame._staging_panel.CANVAS_WIDTH) # show staging panel self._my_grid_frame._staging_panel.pack_ui() self._my_grid_frame._staging_panel.lift(aboveThis=self._their_grid_frame) # enable placement self._my_grid_frame._autoplace_button.config(state=NORMAL) self._play_game_button.config(state=DISABLED) self._hide_frame(self._their_grid_frame) self._hide_frame(self._my_grid_frame._ship_war_panel) self._my_grid_frame._ship_panel.lift(aboveThis=self._my_grid_frame._ship_war_panel) # allow the AI to place ships self.ai.place_ships() elif self._state == self.PLAYING: self.config(width=self.X_PADDING * 4 + self._my_grid.size * 2 + self.SHIP_PANEL_WIDTH * 3) self._my_grid._model.finalize() self._their_grid._model.finalize() self._hide_frame(self._my_grid_frame._staging_panel) self._their_grid.config(state=NORMAL) self._their_grid.enable() for ship in Ship.SHORT_NAMES: self._their_grid_frame._ship_panel.set_placed(ship) self._play_game_button.config(state=DISABLED) # disable placement self._my_grid_frame._autoplace_button.config(state=DISABLED) self.unselect_ship() self._my_grid_frame._ship_war_panel.pack_ui() self._my_grid_frame._ship_war_panel.lift(aboveThis=self._my_grid_frame._ship_panel) # show opponent's grid self._their_grid_frame.lift(aboveThis=self._my_grid_frame._staging_panel) self._their_grid_label.pack() self._their_grid.pack(side=LEFT, pady=20) elif self._state == self.GAME_OVER: # disable everything except for the reset button self._their_grid.disable() self.master.title("Battleship (Game Over)") self.show_game_over_popup() print "GAME OVER" print "The %s player won" % self.get_winning_player() def show_game_over_popup(self): '''Show a popup with a dialog saying the game is over, and showing the winning player.''' popup = Toplevel(self) popup.title("Game Over") f = Frame(popup, width=500) #f.pack_propagate(0) f.pack() if self._winner == self.HUMAN_PLAYER: msg = Message(f, text="You win!") else: msg = Message(f, text="Game over. You lose.") msg.pack() b = Button(f, text="OK", command=popup.destroy) b.pack() def get_winning_player(self): '''Return textual representation of winning player.''' return { self.HUMAN_PLAYER: "human", self.AI_PLAYER : "ai" } [self._winner] def _process_ai_shot(self): '''Get the shot from the AI. Process the given shot by the AI. Return the result of the shot''' shot = self.ai.get_shot() tag_id = self._my_grid._get_tile_name(*shot) id = self._my_grid.find_withtag(tag_id)[0] result = self._my_grid.process_shot(id) if result == Ship.HIT or result == Ship.SUNK: self._set_ship_hit(self._my_grid._model.get_ship_at(*shot)) if result == Ship.SUNK: self._set_ship_sunk(self._my_grid._model.get_sunk_ship(*shot).get_short_name()) if self._my_grid._model.all_sunk(): self._winner = self.AI_PLAYER # update the AI with the shot's result self.ai.set_shot_result(result) return result def _shot(self, event): '''Process a shooting event. event should be the Tkinter event triggered by tag_bind This is a callback function.''' id = self._their_grid.find_withtag(CURRENT)[0] # here we can safely process the shot result = self._their_grid.process_shot(id) # disable square regardless of result= self._their_grid.itemconfig(id, state=DISABLED) shot = self._their_grid._tiles[id] if result == Ship.SUNK: ship = self._their_grid._model.get_sunk_ship(*shot) self._their_grid_frame._ship_panel.set_sunk(ship.get_short_name()) if self._their_grid._model.all_sunk(): self._winner = self.HUMAN_PLAYER if result != Ship.HIT and result != Ship.SUNK: # disable opponent's grid during their turn result = Ship.NULL self._their_grid.disable() while result != Ship.MISS and self._winner is None: result = self._process_ai_shot() # re-enable their grid self._their_grid.enable() if self._winner is not None: self._state = self.GAME_OVER self.process_state() def _add_grid_events(self): '''Add events to the grids.''' self._their_grid.tag_bind("tile", "&lt;Button-1&gt;", self._shot) def _add_grids(self): '''Create UI containers for the player grids.''' self._my_grid_frame = PlayerController(self) self._my_grid_frame.place(x=self.X_PADDING + self.SHIP_PANEL_WIDTH, y=self.Y_PADDING) l1 = Label(self._my_grid_frame, text="Your Grid") l1.pack() self._my_grid = ShipGrid(self._my_grid_frame, True) self._my_grid.pack(side=LEFT, pady=20) self._their_grid_frame = PlayerController(self) self._their_grid_frame.place(x=self._my_grid.size + self.X_PADDING * 2 + self.SHIP_PANEL_WIDTH, y=self.Y_PADDING) self._their_grid_label = Label(self._their_grid_frame, text="Opponent's Grid") self._their_grid_label.pack() self._their_grid = ShipGrid(self._their_grid_frame, False) self._their_grid.pack(side=LEFT, pady=20) self._add_grid_events() def reset(self): '''New game!''' self.master.title("Battleship") self._winner = None # reset both grids self._my_grid.reset() self._their_grid.reset() # reset selected ship self.unselect_ship() # reset staging area self._my_grid_frame._staging_panel.reset() # reset AI self.ai.reset() # reset indicators on ships in panels self._my_grid_frame._ship_war_panel.reset() for ship, button in self._my_grid_frame._ship_panel._ship_buttons.iteritems(): button.config(foreground="black") self.ai.read_stat_model("stat") self._set_ships = {ship : False for ship in Ship.SIZES.keys()} for x, y in self._my_grid.get_tiles(): self.reset_closure(x, y) self._state = self.PLACING self.process_state() def reset_closure(self, x, y): '''Add a placement event to the given tile. TODO this is badly named''' tag_id = self._my_grid._get_tile_name(x, y) c = self.get_add_ship_callback() f = lambda event: self.add_staged_ship(x, y, c) self._my_grid.tag_bind(tag_id, "&lt;Button-1&gt;", f) def add_staged_ship(self, x, y, callback): '''Take the stage from the staging area, and place it on the board at position (x, y). After ship has been placed, execute the function &lt;callback&gt;.''' s = self._my_grid_frame._staging_panel.get_staged_ship() if s is not None: self._my_grid.add_ship(x, y, s.get_short_name(), s.is_vertical(), callback) def get_add_ship_callback(self): '''Return the callback function for adding a ship.''' return lambda: self.ship_set(self.get_current_ship()) def _set_ship_sunk(self, ship): '''This is a callback, to be called when a ship has been sunk. TODO for now only called when one of MY ships is sunk. UI shows that the given ship has been sunk.''' self._my_grid_frame._ship_panel.set_sunk(ship) def _set_ship_hit(self, ship): '''This is a callback, to be called when a ship has been hit. TODO for now only called when one of MY ships is hit. UI shows that the given ship has been hit.''' self._my_grid_frame._ship_war_panel.update(ship) def ship_set(self, ship): '''This is a callback, to be called when a ship has been placed. UI shows that the given ship has been placed.''' self._set_ships[ship] = True self._my_grid_frame._ship_panel.set_placed(ship) if all(self._set_ships.values()): self._play_game_button.config(state=NORMAL) def get_current_ship(self): '''Return the current ship.''' return self._my_grid_frame._ship_panel.get_current_ship() def play_game(self): '''Process the event to stop placement and start playing the game. ''' #TODO sanity check self._state = self.PLAYING self.process_state() def auto_place(self): '''Automatically place the ships according to a preset configuration. This should only be enabled in debugging mode.''' ships = ShipLoader.read("sample_ship_config.txt") for ship in ships: self._my_grid_frame._ship_panel._ship_buttons[ship._type].invoke() self._my_grid.add_ship(*ship.coords(), ship=ship._type, vertical=ship._vertical=="v", callback=self.get_add_ship_callback()) self.unselect_ship() def _make_buttons(self): '''Create action buttons at the bottom.''' button_row = self._my_grid.size + self.Y_PADDING + 40 button_frame = Frame(self) button_frame.place(x=self._my_grid.size - self.X_PADDING, y=button_row) reset_button = Button(button_frame, text="Reset", command=self.reset) reset_button.pack(side=LEFT, padx=5, pady=5) self._play_game_button = Button(button_frame, text="Play", command=self.play_game) self._play_game_button.pack(side=LEFT, padx=5, pady=5) self._my_grid_frame._autoplace_button = Button(button_frame, text="Auto-place ships", command=self.auto_place) self._my_grid_frame._autoplace_button.pack(side=LEFT, padx=5, pady=5) if __name__ == "__main__": app = Tk() app.title("Battleship") game = Game(app) #game.lift(aboveThis=root) #game.pack() game.pack(fill=BOTH, expand=1) app.mainloop() pass </code></pre> <p>It may be hard to read without the custom classes. If anyone asks, I can post some here, but all of them are in my repo. According to the FAQ, I am not allowed to just post the link to the repo without a code snippet, but <a href="https://github.com/13-under-the-ladder/pyBattleShip" rel="nofollow">Here is a link to the full code in my GitHub repo</a>. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T17:14:24.843", "Id": "36620", "Score": "2", "body": "As per the FAQ, we require that you post code in the question. We understand that the code may be too long to do this, but you should then pick a particular portion of the code you'd like reviewed and post it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T17:19:31.157", "Id": "36623", "Score": "0", "body": "Clearly I violate the FAQ of this Exchange, but I don't know where else to post this code. I was hoping other people would take a look at all of my code, and tell me how to improve it. I have several files worth of UI code. There is no particular place that I can point to and say \"this is the problem\", because the code works. It's just long and doesn't look pretty." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T17:25:49.660", "Id": "36624", "Score": "2", "body": "Just pick one part of the code that looks ugly and post that. You can leave your link up there and somebody may look at the rest of the code, but you must at least post a portion of your code in the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T17:30:51.517", "Id": "36626", "Score": "0", "body": "OK, I'll do that. But if I wanted a peer-review of my whole project, where could I go?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T17:33:22.347", "Id": "36627", "Score": "1", "body": "I am aware of no place that would do that. However, there is a good chance that the comments on one piece of your code would apply to the rest of it, so I don't know that that would be more helpful." } ]
[ { "body": "<h3>1. Suitability for inspection</h3>\n\n<p>Tom Gilb and Dorothy Graham (in their book <em>Software Inspection</em>) recommend that you inspect code in batches of about 250 lines. They observe that in practice, as the batch size increases, the quality of the inspection (in terms of number of defects discovered per line of code) falls, because people have limited powers of concentration.</p>\n\n<p>(Consider, for example, how much work was involved in reviewing <a href=\"https://codereview.stackexchange.com/q/23728/11728\">this 10-line program</a>.)</p>\n\n<p>So it's not realistic for you to ask us to review all 1,800+ lines of your game at once.</p>\n\n<p>It's also important for the author of the code to go through the inspection process themselves, prior to requesting inspection by others. Gilb and Graham write:</p>\n\n<blockquote>\n <p>If you would like your own work to be inspected, start thinking about any improvements which you may be able to make <em>before</em> your document is ready to be checked. Have you yourself checked it [against the complete set of rules that apply to your work]? You should make sure that your document is as good as you can reasonably make it <em>before</em> it is submitted.</p>\n</blockquote>\n\n<p>With this advice in mind, I note that your code contains incomplete <code>TODO</code> items: <code>play_game</code> needs a \"sanity check\", <code>reset_closure</code> \"is badly named\" and <code>_set_ship_sunk</code> is \"for now only called when one of MY ships is sunk\". Also, there are comments like \"these are 'controller' elements that should really be in another class\" and \"here 50 is an estimate for the size of the button\" that indicate that you know the code is not complete or correct.</p>\n\n<p>My conclusion is that your code is not yet ready for inspection. I would suggest that you go through and fix all the problems that you know about and then re-submit it for inspection when you are ready.</p>\n\n<h3>2. Play testing</h3>\n\n<p>I played the game and I observed:</p>\n\n<ol>\n<li><p>On the first screen, it's not clear what I should do. It turns out that I have to put my ships on the board and then press \"Play\". Perhaps an instruction would be good.</p></li>\n<li><p>The interface for placing the ships seems rather awkward. The natural way to manipulate the ships would be to drag them around with the mouse.</p></li>\n<li><p>I would expect some kind of randomness from \"Auto-place ships\", but every time I press it I get the same layout.</p></li>\n<li><p>There's no outline around the ships, so when they abut in the grid, you can't tell which square belongs to which ship.</p></li>\n<li><p>On the second screen, it's not clear what I have to do. It turns out that I have to click in the opponent's grid to fire a shot. Perhaps an instruction would be good.</p></li>\n<li><p>It's not clear what the buttons on the right or the ship diagrams on the left mean. Perhaps some kind of title is needed? It turns out that the buttons on the right indicate which ships I have sunk. So why are they implemented as buttons?</p></li>\n<li><p>The opponent seems to get multiple shots to my one. At the end of the game, I have made 12 shots (no hits), but my opponent has made 28 shots (17 hits). It looks as though one gets a free shot after a hit. This seems rather surprising: it's not in the <a href=\"http://www.hasbro.com/common/instruct/battleship.pdf\" rel=\"nofollow noreferrer\">Hasbro rules</a>, for example.</p></li>\n<li><p>When you win or lose, a notification box pops up in the corner of the screen saying \"You win!\" or \"Game over. You lose.\" It would be better to draw this message in the main game window where the player cannot miss it. Also, this window does not disappear when you press \"Reset\" so that after several game you may find that you have several of these windows stacked up in the corner.</p></li>\n<li><p>Why have \"Play\" and \"Auto-place ships\" buttons visible during the game when these are always disabled? Why not remove them?</p></li>\n<li><p>Minor drawing infelicities: the main window has a lot of extra whitespace at the right; the box on the left is missing its right-hand edge; the \"Minesweeper\" touches the bottom edge of the box; the margins around the grids seem uneven because there are letters and numbers only on the top and left (put these on the bottom and right too, or remove them since they play no role in the game); the buttons at the bottom are not centred in the window.</p></li>\n</ol>\n\n<p><img src=\"https://i.stack.imgur.com/UT9uV.png\" alt=\"Screenshot\"></p>\n\n<h3>3. Choice of GUI toolkit</h3>\n\n<p>The <a href=\"http://wiki.python.org/moin/GuiProgramming\" rel=\"nofollow noreferrer\">Python wiki</a> has a comparison of Python GUI toolkits. I'm not an expert on this subject, but the key point in favour of Tkinter is that it's built into Python so that there are going to be no difficulties installing or maintaining it.</p>\n\n<p>The downside is that Tkinter is designed for building mostly-static desktop-style user interfaces. This is fine for turn-based board games like Battleships, but my guess is that as you try to incorporate more dynamic elements into the game, Tkinter's static interface model will become a bit of a constraint. If you find yourself in this situation, you might look at <a href=\"http://www.pygame.org/\" rel=\"nofollow noreferrer\">PyGame</a>.</p>\n\n<h3>4. Comments on your code</h3>\n\n<ol>\n<li><p>The organization of functions could be improved. Your <code>Game</code> class claims to be the \"top-level\" class managing the whole game, but in fact it has 27 methods, and these are full of fiddly details about layout of GUI elements. I would think seriously about reorganizing this class. Note that there's no need for the <code>Game</code> class to be a Tkinter <code>Frame</code> object. You could make the top-level <code>Frame</code> into another object that's a member of the <code>Game</code> class. I'd suggest an initial refactoring like this:</p>\n\n<pre><code>class Game(object):\n \"\"\"\n Battleships game. Maintains the game state and manages the\n interaction with the player and the AI.\n \"\"\"\n def __init__(self, app):\n self.frame = MainFrame(app)\n\nclass MainFrame(Frame):\n \"\"\"\n Top-level window for the Battleships game.\n \"\"\"\n</code></pre>\n\n<p>This would still leave quite a lot of methods in each of these classes, so you'd want to think about further refactoring.</p></li>\n<li><p>In <code>_add_grids</code> the code for creating the two grids is similar. It would be nice to parameterize this: for example instead of having <code>_my_grid</code> and <code>_their_grid</code>, have <code>_player_grid[HUMAN_PLAYER]</code> and <code>_player_grid[AI_PLAYER]</code>. Then it should be possible to refactor some of this duplicated code into loops over the <code>_player_grid</code> array.</p>\n\n<p>Similar remarks apply to <code>_my_grid_frame</code> and <code>_their_grid_frame</code>.</p>\n\n<p>This suggests that you might consider a futher refactoring step: have an abstract <code>Player</code> class (with concrete <code>AIPlayer</code> and <code>HumanPlayer</code> subclasses) which has <code>grid</code> and a <code>grid_frame</code> members.</p></li>\n<li><p>If you look at <code>_process_ai_shot</code> and <code>_process_human_shot</code> you'll see that although these share a couple of lines of code, these are quite different operations. It's normally good practice to implement a game in such a way that player actions are processed in exactly the same way as AI actions. This reduces the amount of code, and ensure that the same rules are being applied to the player and AI. (Obviously the results of the action may be <em>presented</em> in different ways to the player depending on whose action it is.)</p></li>\n<li><p>You use a lot of \"private\" names (starting with underscores). This would be important if you were writing code with a public interface (for example, a general-purpose library), but here all the code is yours: there's no distinction between public and private interface. So it's probably not worthwhile spending the effort to make this distinction. In any case, the distinction does not seem to be applied systematically: for example, <code>set_all_bgs</code>, <code>process_state</code>, <code>show_game_over_popup</code>, <code>get_winning_player</code>, <code>reset_closure</code>, <code>add_staged_ship</code>, <code>get_add_ship_callback</code> (among other methods) are called only from methods on the <code>Game</code> class, but lack the initial underscore.</p></li>\n<li><p>You have docstrings for your methods (good!), but they are sometimes a bit cryptic, and sometimes fail to explain the role of the arguments, what the function does, or what result is returned. For example:</p>\n\n<pre><code>def _process_human_shot(self, id):\n '''Given the shot from the human player, react to it.\n Return the result.'''\n</code></pre>\n\n<p>The questions that this docstring leaves unanswered are:</p>\n\n<ol>\n<li>What is the role of the argument <code>id</code>? (I think it's the Tk handle for the square that was shot.)</li>\n<li>In what way does the method \"react to it\"? (It disables the square, sinks ships on that square, and updates the game over condition.)</li>\n<li>What kind of result is returned? (It's one of the enumerated values <code>Ship.MISS</code>, <code>Ship.HIT</code>, <code>Ship.SUNK</code>.)</li>\n</ol></li>\n<li><p>In the constructor for your <code>Game</code> class, you call the constructor for the superclass <code>Frame</code> directly:</p>\n\n<pre><code>Frame.__init__(self, master)\n</code></pre>\n\n<p>This looks odd to programmers like me who are used to modern Python's <a href=\"http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes\" rel=\"nofollow noreferrer\">new-style classes</a>, so I would put a comment:</p>\n\n<pre><code># Can't use super() since tkinter.Frame is an old-style class.\nFrame.__init__(self, master)\n</code></pre></li>\n<li><p>Your mechanism for implementing callback functions is over-complicated. Instead of writing a method that returns a callback:</p>\n\n<pre><code>def get_add_ship_callback(self):\n '''Return the callback function for adding a ship.'''\n\n return lambda: self.ship_set(self.get_current_ship())\n</code></pre>\n\n<p>you can write the callback directly as a method:</p>\n\n<pre><code>def add_current_ship(self):\n '''Place current ship.'''\n self.ship_set(self.get_current_ship())\n</code></pre>\n\n<p>and then use a \"<a href=\"http://docs.python.org/2/tutorial/classes.html#method-objects\" rel=\"nofollow noreferrer\">method object</a>\" as the callback: </p>\n\n<pre><code>c = self.add_current_ship\n</code></pre></li>\n<li><p>It's slightly outside the scope for this review, but I think that some of the trouble you have to go to with these callbacks is caused by the fact that you don't have objects representing tiles in the grids.</p>\n\n<p>Suppose for example that a <code>Grid</code> object contains a bunch of <code>Tile</code> objects. The grid's <code>get_tiles</code> method generates the tile objects (instead of coordinate pairs, as now). Each <code>Tile</code> object could have methods giving the grid it belongs to, its coordinates, which ship (if any) is placed on that tile, and a callback function for handling mouse clicks. This would simplify a lot of the tile-handling code. (Anywhere you currently have a <code>grid, x, y</code> triple you could have a <code>Tile</code> object instead.)</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T13:06:15.670", "Id": "36677", "Score": "0", "body": "Thank you very much for taking the time to review my code and play the game. This is my first TKinter project that I have brought to completion, so I am very unconfident in my design decisions. I am not sure if I am even using TKinter 'correctly', or if TKinter is the right library for this project. I will definitely take your advice on all the points. If I implemented your suggestions and wanted more feedback, how would you recommend I would do that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T13:46:28.430", "Id": "36678", "Score": "0", "body": "Post a new question here on Code Review, with a link back to this question, saying that you've fixed such-and-such problems and now are ready for a new round of review. If you want feedback on particular questions like choice of GUI kit, make sure to ask them in your question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T14:28:29.920", "Id": "36681", "Score": "0", "body": "Also, it's worth waiting a day or two before accepting an answer: there's more chance that someone else will come along and offer a second opinion if you leave the question open for a bit." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T11:27:05.223", "Id": "23782", "ParentId": "23743", "Score": "6" } } ]
{ "AcceptedAnswerId": "23782", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T16:38:52.723", "Id": "23743", "Score": "2", "Tags": [ "python", "tkinter", "battleship" ], "Title": "Battleship in Python TKinter" }
23743
<p>I have a class, which stores an <code>enum</code> to track if my object is modified, newly created, or no change. If the object is modified, I have additional booleans for each field that is modified.</p> <p>For instance,</p> <pre><code>public enum status { NoChange, Created, Modified } private bool? name; private bool? address; ... private bool? numberOfDonkeysPurchased; </code></pre> <p>So the idea is that if the status is modified, then the nullable bools will be either true or false, depending on if these fields are changed. </p> <p>If the status is not modified, then the nullable bools will be null.</p> <p>The problem with this is that I have a couple of these fields that I want to check (say 10). Is it valid to create a nullable bool for each field that I am checking, knowing that I maybe be storing a lot of nulls? Or is that not a concern?</p> <p>Is there a better way to store this?</p> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T17:42:48.210", "Id": "36628", "Score": "0", "body": "Are you manually adding a new `bool?` each time you add a new property? Or are you using something to auto-generate your code? In the former case, this looks like very painful code to modify..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T17:52:23.410", "Id": "36629", "Score": "0", "body": "@Bobson Yes, a new `bool?` will need to be added for each new property." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T18:03:15.490", "Id": "36631", "Score": "2", "body": "You might want to look into an observable dictionary. You can also generate your bools automatically using a T4 template." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T18:09:07.537", "Id": "36632", "Score": "1", "body": "@Leonid - Yeah, that's where I was going. Auto-generated code would be much easier to do this for." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T18:23:54.007", "Id": "36633", "Score": "0", "body": "Actually, what does `NoChange` mean? Has not changed since the last time I looked at it? This is subjective to a consumer. What if you have multiple consumers? Why not just sore the created time and modified time that is associated with every value, and keep track of it that way. You can use a dict for that. Alternatively, borrow some ideas from git or Clojure - make your objects immutable and track every change by storing a new value in a LinkedList along with who made a change and when. That way you can have all of the diffs. There is more than one way to implement this; it depends on usage." } ]
[ { "body": "<p>I would suggest that you use a Dictionary, with the property as the key and the bool as the value. e.g.</p>\n\n<pre><code>Dictionary&lt;string, bool?&gt; myProperties = new Dictionary&lt;string, bool?&gt;();\n</code></pre>\n\n<p>Use reflection to get all the properties from your object. Then you dont have any work when properties gets added/removed.</p>\n\n<p>You can initialise your dictionary with reflection like this:</p>\n\n<pre><code>foreach (PropertyInfo propertyInfo in myObject.GetType().GetProperties()) {\n myProperties.Add(propertyInfo.Name, false);\n}\n</code></pre>\n\n<p>Or you can even only add those that are not null.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T19:12:11.700", "Id": "36639", "Score": "0", "body": "+1 - This is what I had in mind, but I've been too busy today to write up. Only thing I'd add would be an `PropertyChanged(string propname)` function to called from each property's setter to automatically update the dictionary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T12:07:41.017", "Id": "36676", "Score": "0", "body": "The only downside to this is that if you create 100 instances of that object, you are running that reflection code 100 times." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T13:20:03.883", "Id": "36746", "Score": "0", "body": "@TrevorPilley: if running the reflection code with each new instance is a concern, it can be optimized by adding a static Set which gets initialized once with the property names. Then each instance only needs to load the map with the field names in the set (and no need to do further reflection on the properties)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T18:55:37.300", "Id": "23749", "ParentId": "23745", "Score": "4" } }, { "body": "<p>You could use <code>INotifyPropertyChanged</code> which would also mean that your object can be databound easily. Something like this may be suitable:</p>\n\n<pre><code>public abstract class ChangeTrackingObject : INotifyPropertyChanged\n{\n private readonly HashSet&lt;string&gt; changedProperties = new HashSet&lt;string&gt;();\n\n protected ChangeTrackingObject()\n {\n }\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n public IEnumerable&lt;string&gt; ChangedProperties\n {\n get\n {\n return this.changedProperties;\n }\n }\n\n public bool PropertyWasChanged(string member)\n {\n return this.changedProperties.Contains(member);\n }\n\n protected virtual void OnPropertyChanged([CallerMemberName] string member = \"\")\n {\n this.changedProperties.Add(member);\n\n var propertyChanged = this.PropertyChanged;\n if (propertyChanged != null)\n {\n propertyChanged(this, new PropertyChangedEventArgs(member));\n }\n }\n}\n</code></pre>\n\n<p>The <code>[CallerMemberName]</code> is new in C#5 which does some compile time magic to put the correct string in place.\nUsing a <code>HashSet&lt;string&gt;</code> instead of <code>List&lt;string&gt;</code> ensures that we get unique values only and no duplicates without having to call <code>List&lt;T&gt;.Contains()</code></p>\n\n<pre><code>public class Thing : ChangeTrackingObject\n{\n private string address;\n private string name;\n private int numberOfDonkeysPurchased;\n\n public string Address\n {\n get\n {\n return address;\n }\n set\n {\n address = value;\n this.OnPropertyChanged();\n }\n }\n\n public string Name\n {\n get\n {\n return name;\n }\n set\n {\n name = value;\n this.OnPropertyChanged();\n }\n }\n\n public int NumberOfDonkeysPurchased\n {\n get\n {\n return numberOfDonkeysPurchased;\n }\n set\n {\n numberOfDonkeysPurchased = value;\n this.OnPropertyChanged();\n }\n }\n}\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>var thing = new Thing();\n\nSystem.Console.WriteLine(\"NumberOfDonkeysPurchased Changed? \" + thing.PropertyWasChanged(\"NumberOfDonkeysPurchased\"));\nthing.NumberOfDonkeysPurchased = 5;\nSystem.Console.WriteLine(\"NumberOfDonkeysPurchased Changed? \" + thing.PropertyWasChanged(\"NumberOfDonkeysPurchased\"));\n\nSystem.Console.WriteLine(\"Changed Properties\");\nthing.ChangedProperties.ToList().ForEach(System.Console.WriteLine);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T08:43:18.720", "Id": "36731", "Score": "0", "body": "I'd move the responsibility for change tracking to some other object that subscribes to `NotifyProperyChanged`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T08:46:46.293", "Id": "36733", "Score": "0", "body": "That is something that would be easy to do if you wanted." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T12:14:50.730", "Id": "23786", "ParentId": "23745", "Score": "4" } }, { "body": "<p>Alternatively, you could use a bitmask via a Flags enum:</p>\n\n<pre><code>[Flags]\npublic enum Changes\n{\n None = 0x000,\n Name = 0x001,\n Address = 0x002,\n ...\n NumberOfDonkeysPurchased = 0x100,\n ...\n}\n</code></pre>\n\n<p>Then, you merely update the appropriate flags as you call setters:</p>\n\n<pre><code>public string Name\n{\n get { return name; }\n set\n {\n name = value;\n changes |= Changes.Name;\n }\n}\n</code></pre>\n\n<p>Checking for changes is just a matter of comparing <code>changes</code> with <code>Change.None</code>.</p>\n\n<p><em>Note: this will be preferable to a collections object if you are transmitting your data between a client and a server, since the bitmask will be stored as a single int or long.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T22:01:26.677", "Id": "36705", "Score": "0", "body": "The downside is maintaining the enum when new properties are added/renamed but a neat idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T18:16:35.673", "Id": "36774", "Score": "0", "body": "@TrevorPilley - That's no worse than adding a new `bool` when new properties are added." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T22:13:53.927", "Id": "36803", "Score": "0", "body": "@Bobson that's true, it is still an additional maintenance task (especially if it's across multiple objects) unless you have some clever T4 skills and it's practical to use templates" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T18:30:28.917", "Id": "36950", "Score": "0", "body": "Care should be taken when passing this from one platform to another as the bit order may differ." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T18:18:03.990", "Id": "23804", "ParentId": "23745", "Score": "4" } } ]
{ "AcceptedAnswerId": "23804", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T16:45:36.030", "Id": "23745", "Score": "6", "Tags": [ "c#" ], "Title": "Better Alternative For Storing Multiple Booleans?" }
23745
<p>I've made my first simple game in HTML5. Unfortunately, it runs so slowly. But there are only few rectangles! On my PC, frame rate is between 20 and 25. I expected something like 60-70 but no 20! You can see this game here: <a href="http://mygames.jcom.pl/" rel="nofollow">http://mygames.jcom.pl/</a> (and you can see code by clicking Ctrl+Shift+C in Chrome). What can I do to speed up my game? Why my (so simple) game doesn't run as smoothly as another (bigger and prettier) games in HTML5?</p> <pre><code>var gameCanvas = document.getElementById('gameCanvas'); var ctx = gameCanvas.getContext("2d"); var mapa = loadFromFile("level1"); var gracz = new Obiekt("square", 40, 40); var blokczarny = new Obiekt("square", 80, 80); var FPS = 0; var gameWidth = gameCanvas.width; var gameHeight = gameCanvas.height; var gameTranslationX = 0; var gameTranslationY = 0; // Handle keyboard controls var keysDown = {}; var graczData = { posOnScreenX: gameWidth / 2, posOnScreenY: gameHeight / 2, fallSpd: 300, runSpd: 300, jumpSpd: 600, fell: true, resetjumpSpd: 600, isJumping: false, yWhenStartedJump: 0, kierunek: 1 }; addEventListener("keydown", function(e) { keysDown[e.keyCode] = true; }, false); addEventListener("keyup", function(e) { delete keysDown[e.keyCode]; }, false); var reset = function() { gracz.y = 0; gracz.x = 0; ctx.setTransform(1, 0, 0, 1, graczData.posOnScreenX, graczData.posOnScreenY); }; // Update game objects var update = function(modifier) { this.zmianaX = 0; this.zmianaY = 0; if (38 in keysDown &amp;&amp; !graczData.isJumping &amp;&amp; graczData.fell) {// Player holding up graczData.isJumping = true; } if (40 in keysDown) {// Player holding down } if (37 in keysDown) {// Player holding left } if (39 in keysDown) {// Player holding right } //ochrona przed "wejsciem w sciane" X var newMapPosX = getPositionOnMap(gracz.x + this.zmianaX, gracz.y, blokczarny); if (mapa[newMapPosX[1]][newMapPosX[0]] == 0) { gracz.x += this.zmianaX; } //spadanie if (getTypeOfTile(gracz.x, gracz.y + (graczData.fallSpd * modifier), blokczarny, mapa) == 0) { gracz.y += graczData.fallSpd * modifier; } else { graczData.fell = true; } //skakanie if (getTypeOfTile(gracz.x, gracz.y - (graczData.fallSpd * modifier), blokczarny, mapa) == 0 &amp;&amp; graczData.isJumping) { gracz.y -= graczData.jumpSpd * modifier; graczData.jumpSpd -= 500 * modifier; graczData.fell = false; if (graczData.jumpSpd &lt; 0) { graczData.jumpSpd = graczData.resetjumpSpd; graczData.isJumping = false; } } //bieganie if (getTypeOfTile(gracz.x + (graczData.runSpd * modifier * graczData.kierunek), gracz.y, blokczarny, mapa) == 0) { gracz.x += graczData.runSpd * modifier * graczData.kierunek; } else { graczData.kierunek *= -1; } //document.write("GraczY: " + gracz.y + "GraczX: " +gracz.x); }; var clear = function() { ctx.fillStyle = "rgb(255, 255, 255)"; //ctx.beginPath(); ctx.rect(0, 0, gameCanvas.width, gameCanvas.height); //ctx.closePath(); ctx.fill(); } var oldgracz = { x: 0, y: 0 } var render = function() { ctx.translate(-(gracz.x - oldgracz.x), -(gracz.y - oldgracz.y)); gameTranslationX = gracz.x - graczData.posOnScreenX; gameTranslationY = gracz.y - graczData.posOnScreenY; clear(); console.log("FPS" + FPS); ctx.fillStyle = "rgb(255, 0, 0)"; gracz.draw(ctx); ctx.fillStyle = "rgb(0, 0, 0)"; drawMap(mapa, blokczarny, ctx); oldgracz.x = gracz.x; oldgracz.y = gracz.y; } // The main game loop var main = function() { var now = Date.now(); var delta = now - then; FPS = 1000 / delta; update(delta / 1000); render(); then = now; }; // Let's play this game! reset(); var then = Date.now(); setInterval(main, 100); </code></pre>
[]
[ { "body": "<p>I believe your issue is related to the setInterval, you should at least try not to use it; instead use requestAnimationFrame.</p>\n\n<p>for example here is a link:\n<a href=\"http://paulirish.com/2011/requestanimationframe-for-smart-animating/\" rel=\"nofollow\">http://paulirish.com/2011/requestanimationframe-for-smart-animating/</a></p>\n\n<p>GL!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T18:54:07.133", "Id": "23748", "ParentId": "23747", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T18:32:49.770", "Id": "23747", "Score": "2", "Tags": [ "javascript", "optimization", "html5" ], "Title": "Game runs very slowly - optimization" }
23747
<p>Is there a cleaner way to write:</p> <pre><code>def b_fname if mdes_version_is_after?(3.0) result = c_fname else result = response_for("#{birth_baby_name_prefix}.BABY_FNAME") end if result.empty? result = 'your baby' end result end </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-04T20:22:55.707", "Id": "215080", "Score": "0", "body": "To explain the downvote: could please add more information about the purpose of your code?" } ]
[ { "body": "<p>The following version uses the ternary operator, which avoids one assignment:</p>\n\n<pre><code>def b_fname\n if mdes_version_is_after?(3.0)\n result = c_fname\n else\n result = response_for(\"#{birth_baby_name_prefix}.BABY_FNAME\")\n end\n\n result.empty? ? 'your baby' : result\nend\n</code></pre>\n\n<p>You can also do the following if you don't like the ternary operator:</p>\n\n<pre><code>def b_fname\n if mdes_version_is_after?(3.0)\n result = c_fname\n else\n result = response_for(\"#{birth_baby_name_prefix}.BABY_FNAME\")\n end\n\n if result.empty?\n 'your baby'\n else\n result\n end\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T22:01:00.200", "Id": "23753", "ParentId": "23751", "Score": "1" } }, { "body": "<p>Some notes:</p>\n\n<ul>\n<li>In Ruby <code>if</code> conditionals can be used also as expressions, not only statements.</li>\n<li>Don't change/rebind the value of existing variables, create a new one (<a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">FP in Ruby</a>).</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>def b_fname\n name = if mdes_version_is_after?(3.0)\n c_fname\n else\n response_for(\"#{birth_baby_name_prefix}.BABY_FNAME\")\n end\n name.empty? ? 'your baby' : name\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T22:36:19.637", "Id": "23755", "ParentId": "23751", "Score": "4" } }, { "body": "<p>I'd also consider changing some variable/function names. <code>b_fname</code>, <code>mdes</code>, and <code>c_fname</code> are not super descriptive. It's a few extra keystrokes, but the readability is well worth it, IMO.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T16:25:31.063", "Id": "36772", "Score": "0", "body": "Although I agree with your sentiment, those names are prescribed from the an outside source, we have no control over those particular names." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T19:35:19.213", "Id": "36787", "Score": "0", "body": "Ah, gotcha. Carry on, then!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T13:27:41.460", "Id": "23839", "ParentId": "23751", "Score": "2" } }, { "body": "<p>Though I would probably do away with the variable named result, this would be a clean way to do this. In other words, regarding the variable assignment, don't conditionally assign a variable through all conditional paths. Just assign it the result of the condition one time.</p>\n\n<pre><code>def b_fname\n result = if mdes_version_is_after?(3.0)\n c_fname\n else\n response_for(\"#{birth_baby_name_prefix}.BABY_FNAME\")\n end\n result or 'your baby'\nend\n</code></pre>\n\n<p>I think I might prefer this version though, in some ways</p>\n\n<pre><code>def b_fname\n if mdes_version_is_after?(3.0)\n c_fname\n else\n response_for(\"#{birth_baby_name_prefix}.BABY_FNAME\")\n end || 'your baby'\nend \n</code></pre>\n\n<p>But without an <code>if..else</code></p>\n\n<pre><code>def b_fname\n mdes_version_is_after?(3.0) &amp;&amp; c_fname ||\n response_for(\"#{birth_baby_name_prefix}.BABY_FNAME\") ||\n 'your baby'\nend\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-20T09:58:49.827", "Id": "24147", "ParentId": "23751", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T20:39:01.967", "Id": "23751", "Score": "-1", "Tags": [ "ruby" ], "Title": "Getting a name, with fallback behavior" }
23751
<p>What I want to do is; without leaving the chain, execute some custom/external code (and continue) within the chain. Otherwise; in a deep chain, I will have to re-query for the DOM element to get back where I've left.</p> <p>The method below allows to execute custom code inside a jQuery chain synchronously or asynchronously.</p> <pre class="lang-js prettyprint-override"><code>//Execute code inside a jQuery chain $.fn.do = function (callback, async) { if (typeof callback === 'function') { if (async === true) { this.queue(function() { callback($(this)); $(this).dequeue(); }); } else { callback(this); } } return this; }; </code></pre> <p>Simplified Usage Example:</p> <pre class="lang-js prettyprint-override"><code>var results = {}; $('#some-elem') .css({ //modify some styles here }) .do(function($elem) { //do some calculations.. tests here.. //save them to results object }, false) //synchronous .css({ //re-set the styles back to their initial state }); </code></pre> <p>This could be a longer chain where you could need to enter the <code>do()</code> method multiple times.</p> <p>So; </p> <ul> <li>Do you think the approach above is legitimate?</li> <li>Would you suggest an alternate? Why?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T00:28:09.997", "Id": "36657", "Score": "0", "body": "I'm not sure about the necessity of `.queue()` here - why are you adding a function to the default `fx` queue (will be queued after animations when there are pending animations) if this version of the method is asynchronous? You can probably get rid of that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T01:04:33.073", "Id": "36716", "Score": "0", "body": "@FabrícioMatté This can be used for many purposes (an external operation or a related operation set to occur after some animation that may need the gathered data inside the `do()` method) so I'm allowing for both async and immediate execution. (I'm also passing the corresponding jQuery element as an argument.) Does it make sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T01:29:59.710", "Id": "36717", "Score": "0", "body": "I guess. Let me see, in your example code, the last `.css()` should wait until `do()` calls `dequeue()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T02:13:04.923", "Id": "36718", "Score": "0", "body": "The example above is completely synchronous since `.css()` method is executed immediately and `.do()` is called with `false` param. And essentially, `do(func, true)` (async) is only a shorhand for `queue()` which will execute when it's his turn in the queue. You might say that I'm only extending the `.queue()` method with a sync execution capability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T02:15:19.270", "Id": "36719", "Score": "0", "body": "If your intent is to extend `queue` then this looks perfectly fine. I may take another look tomorrow but there isn't much code to cut out without losing a lot of readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T02:15:23.797", "Id": "36720", "Score": "0", "body": "Maybe I should change the signature to `$.fn.do(callback, addToQueue);` so it's more clear." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T02:17:03.263", "Id": "36721", "Score": "0", "body": "Yes, that will be helpful for future readers, both here and in the real world applications that you may use it. I'd personally add a third optional `whichQueue` parameter which may be useful in future, but depends on your use cases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T02:21:41.853", "Id": "36722", "Score": "0", "body": "Currently this is called \"for\" the corresponding element (when async is `true`) such as `this.queue()`. Do you mean I could use that `whichQueue` param? Maybe `target` is better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T02:23:00.590", "Id": "36723", "Score": "0", "body": "i.e.: `target = typeof(target) === 'undefined' ? this : target;` and then `target.queue(...)`. Do you mean this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T03:09:00.420", "Id": "36724", "Score": "0", "body": "No, I meant `whichQueue` as the `queueName` parameter for [`$.fn.queue`](http://api.jquery.com/queue/), so you'd be able to create your own queues instead of just dumping it all on the default `fx` queue. `=]`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-18T15:37:29.943", "Id": "52595", "Score": "0", "body": "Have you looked at my answer?" } ]
[ { "body": "<p>I guess this plugin could be useful, however I think you can drop the async part since it's not any harder to call <code>queue</code> directly.</p>\n\n<p>Also, I am not a huge fan of error swallowing or ignoring invalid calls since it makes the code harder to debug. If there's a call to <code>do</code> without providing a callback, you should let the developer be notified.</p>\n\n<p>I also like to allow defining the <code>this</code> value for the callback function so that you do not need to use <code>$.proxy</code> for that purpose.</p>\n\n<p>Finally I allowed to return a value from the callback to change the target object for the rest of the chain. However I am not so sure about this feature since it could harm code comprehension but I am leaving it there as an idea.</p>\n\n<p>Basically it would be as simple as:</p>\n\n<pre><code>!function($) {\n $.fn.do = function (callback, thisArg) {\n if (typeof callback !== 'function') {\n throw new TypeError(\"the 'callback' argument must be of type 'function'\");\n }\n\n return callback.call(thisArg || this, this) || this;\n };\n}(jQuery);\n</code></pre>\n\n<p><em>Note: I've defined the plugin within an IIFE so that it still works if <code>$.noConflict()</code> was used.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-20T15:13:22.603", "Id": "52721", "Score": "0", "body": "+1 for `thisArg`. Though, I wouldn't modify the returned object since this is for keeping the chain. Sure you can call `queue()' easily; `async` acts like a shortcut there. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-14T07:06:32.763", "Id": "32666", "ParentId": "23752", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T21:28:56.770", "Id": "23752", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "$.fn.do() method: Execute other code within a jQuery chain" }
23752
<p>The code already works, but I just want tips for improving.</p> <pre><code>import javax.swing.JOptionPane; import java.text.DecimalFormat; public class Calculator { public static void main(String[] args) { double initialPrice = 0.00; double commissionRate = 0; double discountRate = 0; initialPrice = Double.parseDouble(JOptionPane.showInputDialog(null, "What is the initial price total of the sale?")); commissionRate = Double.parseDouble(JOptionPane.showInputDialog(null, "What is the percentage amount of the sales commission? \nFor example for 20%, type 20.")); discountRate = Double.parseDouble(JOptionPane.showInputDialog(null, "What is the customer's discount rate? \nFor example for a 15% discount, type 15.")); JOptionPane.showMessageDialog(null, "The final cost to the customer is \n$" + computeFinalPrice(initialPrice, commissionRate, discountRate) + "."); } public static String computeFinalPrice (double initialPrice, double commissionRate, double discountRate) { double finalPrice; DecimalFormat d = new DecimalFormat("0.00"); finalPrice = (initialPrice*(commissionRate+100)*.01)*((100-discountRate)*.01); return (d.format(finalPrice)); } </code></pre>
[]
[ { "body": "<p>Interesting, consider the following:</p>\n\n<ul>\n<li><p>For extra DRYness, you could have created a helper function to get a double</p>\n\n<pre><code>private double getDouble( String msg )\n</code></pre></li>\n<li><p><code>computeFinalPrice</code> should probably be private</p></li>\n<li>If you wanted <code>computeFinalPrice</code> to be re-usable, then it probably makes more sense to return a double and keep it public</li>\n<li>A company would probably rather compute commission after discount, otherwise sales people will get really excited about giving 99% discounts ;)</li>\n<li>Either you initialize doubles with zeroes like in main() or you don't like in computeFinalPrice.</li>\n<li>As mentioned by another reviewer, consider Long instead of Double, as Doubles can have rounding issues.</li>\n<li><p>I would write</p>\n\n<pre><code>finalPrice = (initialPrice*(commissionRate+100)*.01)*((100-discountRate)*.01); \n</code></pre>\n\n<p>as</p>\n\n<pre><code>`finalPrice = initialPrice*(commissionRate+100)*.01*(100-discountRate)*.01;` \n</code></pre>\n\n<p>if I felt like messing with the code reviewer I might even</p>\n\n<pre><code>`finalPrice = initialPrice*(commissionRate+100)*(100-discountRate)*.0001;` \n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T23:32:36.537", "Id": "36656", "Score": "0", "body": "Good point about making it private. It's for class, so I'm locked into applying the discount after the commission. I agree it makes little sense from a business perspective." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T23:23:33.000", "Id": "23757", "ParentId": "23756", "Score": "1" } }, { "body": "<p>Just a quick note: Don't use floating point variables where you may need exact results:</p>\n\n<ul>\n<li><em>Effective Java, 2nd Edition, Item 48: Avoid float and double if exact answers are required</em></li>\n<li><a href=\"https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency\">Why not use Double or Float to represent currency?</a></li>\n</ul>\n\n<p>Fortunately Java has <a href=\"http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html\" rel=\"nofollow noreferrer\"><code>BigDecimal</code></a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T02:09:10.163", "Id": "36663", "Score": "0", "body": "I'm only a week into my first class so I'm still learning the ropes. I looked into BigDecimal after a few google searches. Since the program only takes a singular input for the output and only compounds once, I figured that the accuracy wouldn't matter too much. However, point taken. I'll school myself up on BigDecimal and use it from now on. Thanks for the feedback!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T00:58:06.963", "Id": "23760", "ParentId": "23756", "Score": "2" } } ]
{ "AcceptedAnswerId": "23757", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T23:07:22.777", "Id": "23756", "Score": "1", "Tags": [ "java", "finance" ], "Title": "Calculating price after sales commission and discount" }
23756
<p>This is a method that calls a web service, it uploads an audio file and fetches metadata back.</p> <p>While the advantage is that there is only one method to call there are a few concerns about it :</p> <ul> <li>There is some UI-related code (upload progress)</li> <li>Some audio-related code (format detection)</li> <li>Web-service related code (first purpose)</li> </ul> <p>In the end, while it tries to be smart, it's completely tied to a particular audio library, it will report progress anyway and well, it doesn't only upload ...</p> <p>How would you apply separation of concerns to this current method ?</p> <ul> <li>Would transforming the <em>fileFormat</em> to a parameter be acceptable ?</li> <li>What about <em>handler</em>, how can it be used without being tied to the upload process ?</li> </ul> <p>I'm not necessarily asking for code, directions to some documentation on the subject is fine too.</p> <pre><code>public class TrackUpload { public async Task&lt;string&gt; Upload(string apiKey, string path, ProgressEventHandler handler) { if (apiKey == null) throw new ArgumentNullException("apiKey"); if (path == null) throw new ArgumentNullException("path"); using (var stream = new ReadOnlyFileStream(path)) { if (handler != null) { stream.ProgressChanging += handler; } string fileFormat = TrackFormatDetector.Detect(path); if (fileFormat == null) { throw new InvalidAudioFormatException(); } var dataContent = new MultipartFormDataContent(); dataContent.Add(new StringContent(apiKey), "api_key"); dataContent.Add(new StringContent(fileFormat), "filetype"); dataContent.Add(new StreamContent(stream), "track"); var client = new HttpClient(); client.DefaultRequestHeaders.UserAgent.Add( new ProductInfoHeaderValue(new ProductHeaderValue("xxxx", "1.0"))); HttpResponseMessage response = await client.PostAsync(@"http://developer.echonest.com/api/v4/track/upload", dataContent); response.EnsureSuccessStatusCode(); HttpContent content = response.Content; if (handler != null) { stream.ProgressChanging -= handler; } using (var reader = new StreamReader(await content.ReadAsStreamAsync())) { string s = await reader.ReadToEndAsync(); return s; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-10T08:19:36.373", "Id": "504933", "Score": "1", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<ul>\n<li>You <em>should</em> move <code>fileFormat</code> to parameters, this method is doing too much</li>\n<li>Use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.iprogress-1?view=net-5.0\" rel=\"nofollow noreferrer\"><code>IProgress&lt;T&gt;</code></a> instead of <code>handler</code> to properly report progress back to the UI thread (see <a href=\"https://devblogs.microsoft.com/dotnet/async-in-4-5-enabling-progress-and-cancellation-in-async-apis/\" rel=\"nofollow noreferrer\">Enabling Progress and Cancellation in Async APIs</a> for examples).</li>\n<li>Add <code>CancellationToken</code> parameter if necessary</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-03-12T07:28:09.623", "Id": "23771", "ParentId": "23758", "Score": "3" } } ]
{ "AcceptedAnswerId": "23771", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-11T23:56:54.313", "Id": "23758", "Score": "1", "Tags": [ "c#", "design-patterns" ], "Title": "Appropriate separation of concerns for this case?" }
23758
<p>I am trying to write a Python script that download an image from a webpage. On the webpage (I am using NASA's picture of the day page), a new picture is posted everyday, with different file names. After download, set the image as desktop. </p> <p>My solutions was to parse the HTML using <code>HTMLParser</code>, looking for "jpg", and write the path and file name of the image to an attribute (named as "output", see code below) of the HTML parser object.</p> <p>The code works, but I am just looking for comments and advice. I am new to Python and OOP (this is my first real python script ever), so I am not sure if this is how it is generally done.</p> <pre><code>import urllib2 import ctypes from HTMLParser import HTMLParser # Grab image url response = urllib2.urlopen('http://apod.nasa.gov/apod/astropix.html') html = response.read() class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, print it. if name == "href": if value[len(value)-3:len(value)]=="jpg": #print value self.output=value parser = MyHTMLParser() parser.feed(html) imgurl='http://apod.nasa.gov/apod/'+parser.output print imgurl # Save the file img = urllib2.urlopen(imgurl) localFile = open('desktop.jpg', 'wb') localFile.write(img.read()) localFile.close() # set to desktop(windows method) SPI_SETDESKWALLPAPER = 20 ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, "desktop.jpg" , 0) </code></pre>
[]
[ { "body": "<pre><code># Save the file\nimg = urllib2.urlopen(imgurl)\nlocalFile = open('desktop.jpg', 'wb')\nlocalFile.write(img.read())\nlocalFile.close()\n</code></pre>\n\n<p>For opening file it's recommend to do:</p>\n\n<pre><code>with open('desktop.jpg','wb') as localFile:\n localFile.write(img.read())\n</code></pre>\n\n<p>Which will make sure the file closes regardless.</p>\n\n<p>Also, urllib.urlretrieve does this for you. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T01:27:02.603", "Id": "23761", "ParentId": "23759", "Score": "2" } }, { "body": "<p>Instead of <code>value[len(value)-3:len(value)]==\"jpg\"</code> you can use</p>\n\n<pre><code>value.endswith(\"jpg\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T07:47:56.873", "Id": "23773", "ParentId": "23759", "Score": "1" } }, { "body": "<p>I think your class <code>MyHTMLParser</code> is not necessary. We can use a function instead of a class.</p>\n\n<p>If you know what is <code>Regular Expression</code> you can using code below:</p>\n\n<pre><code>import re\n\ndef getImageLocation():\n with urllib2.urlopen('http://apod.nasa.gov/apod/astropix.html') as h:\n # (?&lt;=...) means \"Matches if the current position in the string \n # is preceded by a match for ... \n # that ends at the current position.\"\n loc = re.search('(?&lt;=IMG SRC=\")image/\\d+/[\\w\\d_]+.jpg', a).group())\n return 'http://apod.nasa.gov/apod/' + loc\n</code></pre>\n\n<p>Regular Expression Syntax: <a href=\"http://docs.python.org/3/library/re.html#regular-expression-syntax\" rel=\"nofollow\">http://docs.python.org/3/library/re.html#regular-expression-syntax</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T08:44:52.970", "Id": "23827", "ParentId": "23759", "Score": "1" } }, { "body": "<p>1) Have you considered searching for the img tag and just using the href from that for the desktop image?</p>\n\n<p>Other than that, your code seems fine</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T13:53:59.123", "Id": "23843", "ParentId": "23759", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T00:08:39.580", "Id": "23759", "Score": "4", "Tags": [ "python", "beginner", "parsing", "windows", "web-scraping" ], "Title": "Download an image from a webpage" }
23759
<h1>Background</h1> <p>A subclass of <code>java.util.Properties</code> attempts to recursively resolve configured properties:</p> <pre><code>prop_a=Prop A is ${prop_b} prop_b=Prop B is ${prop_c} prop_c=Prop C. </code></pre> <p>After reading the file, <code>prop_a</code> should be <code>Prop A is Prop B is Prop C</code>.</p> <h1>Property Reference Semantics</h1> <p>Nest properties are not allowed, making the following invalid:</p> <pre><code>${property_name_a ${property_name_b}} </code></pre> <p>A valid property is:</p> <pre><code>name=Text for ${property_a}, followed by ${property_b}. </code></pre> <h1>Source Code</h1> <p>Code that handles parsing:</p> <pre><code>/** * This will throw an IllegalArgumentException if there are mismatched * braces. * * @param s - The string with zero or more ${} references to resolve. * @return The value of the string, with all substituted values made. */ public String resolve( String s ) { StringBuffer sb = new StringBuffer( 256 ); Stack&lt;StringBuffer&gt; stack = new Stack&lt;StringBuffer&gt;(); int len = s.length(); for( int i = 0; i &lt; len; i++ ) { char c = s.charAt( i ); switch( c ) { case '$': { if( i + 1 &lt; len &amp;&amp; s.charAt( i + 1 ) == '{' ) { stack.push( sb ); sb = new StringBuffer( 256 ); i++; } break; } case '}': { if( stack.isEmpty() ) { throw new IllegalArgumentException( "unexpected '}'" ); } String name = sb.toString(); sb = stack.pop(); sb.append( super.getProperty( name, null ) ); break; } default: { sb.append( c ); break; } } } if( !stack.isEmpty() ) { throw new IllegalArgumentException( "missing '}'" ); } return sb.toString(); } </code></pre> <h1>Question</h1> <p>How would you simplify the code and detect/avoid infinite recursion?</p>
[]
[ { "body": "<ul>\n<li><p>You say \"recursively resolve\", but in fact <code>resolve</code> is not recursive. It returns <code>Prop A is Prop B is ${prop_c}</code> instead of <code>Prop A is Prop B is Prop C</code>, if you call it with <code>Prop A is ${prop_b}</code>. If you call it with <code>prop_a</code>, as advertised, it returns <code>prop_a</code>.</p></li>\n<li><p>You allow nested <code>${}</code> in you syntax. What is your semantics of it?</p></li>\n<li><p>Do you have any test cases for this. The bug and Unclear semantics of nested parens for instance, strongly indicate you should have. </p></li>\n<li><p>Since you access the super class through its public interface, namely the the singe call to the <code>super.getProperty</code> you could instead pass the properties as a parameter. It will improve usability. Then you can make the static, if you wish. Since the method does not refer to any instance members otherwise.</p></li>\n<li><p><code>StringBuffer</code> and <code>Stack</code> have built in synchronization, whose overhead you can avoid by using <code>StringBuilder</code> and <code>ArrayList</code>.</p></li>\n</ul>\n\n<p>Here is the test code to save others some effort:</p>\n\n<pre><code>import java.util.Properties;\nimport java.util.Stack;\n\n\npublic class Main {\n public static String resolve(Properties props, String s ) {\n StringBuffer sb = new StringBuffer( 256 );\n Stack&lt;StringBuffer&gt; stack = new Stack&lt;StringBuffer&gt;();\n int len = s.length();\n\n for( int i = 0; i &lt; len; i++ ) {\n char c = s.charAt( i );\n\n switch( c ) {\n case '$': {\n if( i + 1 &lt; len &amp;&amp; s.charAt( i + 1 ) == '{' ) {\n stack.push( sb );\n sb = new StringBuffer( 256 );\n i++;\n }\n break;\n }\n\n case '}': {\n if( stack.isEmpty() ) {\n throw new IllegalArgumentException( \"unexpected '}'\" );\n }\n\n String name = sb.toString();\n\n sb = stack.pop();\n sb.append( props.get(name) );\n break;\n }\n\n default: {\n sb.append( c );\n break;\n }\n }\n }\n\n if( !stack.isEmpty() ) {\n throw new IllegalArgumentException( \"missing '}'\" );\n }\n\n return sb.toString();\n }\n\n public static void main(String[] args) {\n Properties props = new Properties();\n\n props.setProperty(\"prop_a\", \"Prop A is ${prop_b}\"); \n props.setProperty(\"prop_b\", \"Prop B is ${prop_c}\"); \n props.setProperty(\"prop_c\", \"Prop C.\");\n\n System.out.println(resolve(props, \"Prop A is ${prop_b}\"));\n System.out.println(resolve(props, \"prop_a\"));\n System.out.println(resolve(props, \"${prop_a}\"));\n System.out.println(resolve(props, \"${${prop_b}}\"));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-01T06:05:38.057", "Id": "279558", "Score": "0", "body": "A bug exists in both of our implementations: `${prop_a} {0}` should resolve successfully." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T08:27:28.710", "Id": "23775", "ParentId": "23762", "Score": "2" } } ]
{ "AcceptedAnswerId": "23775", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T02:11:40.270", "Id": "23762", "Score": "1", "Tags": [ "java", "recursion", "properties" ], "Title": "Recursive java.util.Properties references" }
23762
<p>I want to know the correct way to finish up this code at the bottom. I'm thinking there has to be a better way to grab content from one section of your site and displaying it somewhere else with animation attached to it. The Code below seems like it can do better. I post the entire code below, but you might be able to understand what i'm trying to accomplish just by reading this few lines of code. I left comments to help</p> <pre><code>// Find what input field was clicked var formVaule = $('input[value="' + ValUe + '"]'); // Find the content and store it. var k = formVaule.next().text(); // Display H2 tag with the content that was stored $('#' + ValUe).html('&lt;h2&gt;' + k + '&lt;/h2&gt;'); // Animated the h2 tag with a background color $('#' + ValUe).find('h2').animate({ backgroundColor: "#40822B" }, 100, // Call a callback function with the attention of removing the background. function() { $('#' + ValUe).find('h2').animate({ backgroundColor: "white"}, 500); }); </code></pre> <p>Full code Below</p> <pre><code>&lt;form&gt; &lt;input type="radio" name="form" value="informed"/&gt; &lt;span&gt;INFORMED CONSENT&lt;/span&gt;&lt;br /&gt; &lt;input type="radio" name="form" value="release"/&gt; &lt;span&gt;RELEASE OF INFORMATION&lt;/span&gt;&lt;br /&gt; &lt;input type="radio" name="form" value="intake"/&gt; &lt;span&gt;INTAKE FORM&lt;/span&gt;&lt;br /&gt; &lt;input type="radio" name="form" value="checklist"/&gt; &lt;span&gt;CHECKLIST OF CONCERNS (CHILD &amp; ADOLESCENT AND ADULT)&lt;/span&gt;&lt;br /&gt; &lt;input type="radio" name="form" value="health"/&gt; &lt;span&gt;HEALTH INFORMATION PRIVACY FORM&lt;/span&gt;&lt;br /&gt; &lt;/form&gt; &lt;div id="informed" class="Form"&gt;1&lt;/div&gt; &lt;div id="release" class="Form"&gt;2&lt;/div&gt; &lt;div id="intake" class="Form"&gt;3&lt;/div&gt; &lt;div id="checklist" class="Form"&gt;4&lt;/div&gt; &lt;div id="health" class="Form"&gt;5&lt;/div&gt; &lt;div id="ContactFormSix" class="Form"&gt;6&lt;/div&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/jquery-ui.min.js"&gt;&lt;/script&gt; &lt;script&gt; var myForm = new Array("INFORMED CONSENT","RELEASE OF INFORMATION","INTAKE FORM"); $(document).ready(function () { $('input').on( 'change', function () { //check var ValUe = $(this).val(); $('.Form').hide(); $('#' + ValUe).show(); //Find the value of the input that was clicked var formVaule = $('input[value="' + ValUe + '"]'); //Grab the value of the input that was clicked and find the next element and retreive the text var k = formVaule.next().text(); //Prepend the elemnts text $('#' + ValUe).html('&lt;h2&gt;' + k + '&lt;/h2&gt;'); $('#' + ValUe).find('h2').animate({ backgroundColor: "#40822B" }, 100, function() { $('#' + ValUe).find('h2').animate({ backgroundColor: "white"}, 500); }); }); }); &lt;/script&gt; </code></pre>
[]
[ { "body": "<p>At first, you are requesting the element <code># + ValUe</code> 4 times. That means jQuery need to search to the entire DOM 4 times to get an element. Cache the value of this element and use that cache variable:</p>\n\n<pre><code>var elem = $('#' + ValUe);\n\nelem.html(...);\n\nelem.find(...);\n</code></pre>\n\n<p><code>$(this)</code> inside the callback of the <code>.animate</code> method refers to the animated element, you don't need to use <code>$('#' + ValUe).find('h2')</code> again, just use <code>$(this)</code>.</p>\n\n<p>You use <code>formVaule</code> once, just use that constructor instead of saving it to a variable.</p>\n\n<p>To complete correct code:</p>\n\n<pre><code>var k = $('input[value=\"' + ValUe + '\"]').next().text();\nvar elem = $('#' + ValUe);\n\n// Display H2 tag with the content that was stored \nelem.html('&lt;h2&gt;' + k + '&lt;/h2&gt;');\n\n// Animated the h2 tag with a background color\nelem.find('h2').animate({ backgroundColor: \"#40822B\" }, 100, function() {\n // Call a callback function with the attention of removing the background.\n\n $(this).animate({ backgroundColor: \"white\"}, 500);\n\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T22:31:57.840", "Id": "23806", "ParentId": "23766", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T05:51:21.490", "Id": "23766", "Score": "1", "Tags": [ "javascript", "jquery", "html", "jquery-ui" ], "Title": "Grab Text storing it in a var then adding html method and adding animation to it" }
23766
<p>I have the following SQL structure (simplified for brevity):</p> <pre><code>TABLE [Posts] [Id] INT NOT NULL IDENTITY PRIMARY KEY, [ParentId] INT NULL, [Type] INT NOT NULL, FOREIGN KEY ( [ParentId] ) REFERENCES [Posts] ( [Id] ) FOREIGN KEY ( [Type] ) REFERENCES [PostTypes] ( [Type] ) TABLE [PostTypes] [Id] INT NOT NULL PRIMARY KEY, [Name] SYSNAME NOT NULL TABLE [PostTypeValidParents] [ChildType] INT NOT NULL, [ParentType] INT NOT NULL, PRIMARY KEY ( [ChildType], [ParentType] ), FOREIGN KEY ( [ChildType] ) REFERENCES [PostTypes] ( [Type] ), FOREIGN KEY ( [ParentType] ) REFERENCES [PostTypes] ( [Type] ) INSERT [PostTypes] ( [Type], [name] ) VALUES ( 0, 'Global' ), ( 1, 'Category' ), ( 2, 'Thread' ), ( 3, 'Reply' ) INSERT [PostTypeValidParents] ( [ChildType], [ParentType] ) VALUES ( 1, 0 ), ( 1, 1 ), ( 2, 1 ), ( 3, 2 ) </code></pre> <p>Now, I want to create a trigger which validate <code>[Posts]</code> based on the rules defined in <code>[PostTypeValidParents]</code>. Here's what I have so far:</p> <pre><code>CREATE TRIGGER [ValidatePost] ON [Posts] AFTER INSERT, UPDATE AS BEGIN IF ( EXISTS ( SELECT * FROM [deleted] ) AND UPDATE ( [Type] ) ) RAISERROR ( N'The [Posts].[Type] column cannot be modified.', 16, 1 ); DECLARE @parents TABLE ( [ChildType] INT NOT NULL, [ParentType] INT NOT NULL ); INSERT @parents SELECT c.[Type], CASE WHEN p.[Type] IS NULL THEN 0 ELSE p.[Type] END FROM [inserted] c LEFT JOIN [Forum].[Posts] p ON c.[ParentId] = p.[Id]; DECLARE @childType NVARCHAR(30), @parentType NVARCHAR(30); WITH [Conflicts] AS ( SELECT [ChildType], [ParentType] FROM @parents EXCEPT SELECT [ChildType], [ParentType] FROM [PostTypeValidParents] ) SELECT TOP 1 @childType = c.[Name], @parentType = p.[Name] FROM [Conflicts] x JOIN [PostTypes] c ON x.[ChildType] = c.[Type] JOIN [PostTypes] p ON x.[ParentType] = p.[Type]; IF ( @childType IS NOT NULL ) RAISERROR ( N'Posts of type ''%s'' may not have a parent of type ''%s''.', 16, 1, @childType, @parentType ); END </code></pre> <p>My basic pattern here is, </p> <ol> <li>check for read-only fields and <code>RAISERROR</code> if modified </li> <li><code>SELECT</code> critical conditions into a table variable </li> <li>find unsupported conditions with an <code>EXCEPT</code> inside a CTE, <code>SELECT</code>'ing into a variable and <code>RAISERROR</code> if not null.</li> </ol> <p>It seems to work well enough (though I haven't thoroughly tested it yet). My problem is that this seems a bit verbose for what should be a relatively simple validation trigger. I'll have to write many of these in the near future, so I'm hoping to find a simpler pattern that accomplishes the same thing. Can anyone offer suggestions on how to reduce this code?</p>
[]
[ { "body": "<p>Your code is correct as long as you plan to validate business integrity using triggers.</p>\n\n<p>But I would question whether business validation in SQL Server is a right choice:</p>\n\n<ul>\n<li>You have no means (other than parsing return error string) to process errors on client side.</li>\n<li>This kind of code may cause deadlocks under heavy load (I can't find them here but it doesn't mean there aren't any :))</li>\n<li>Each insert causes at least 2 table searches</li>\n</ul>\n\n<p>Alternative way (how most applications works) is to rely on a business logic inside client application to enforce business rules. It's much easier (and straightforward) to verify that your parent is of a valid type. </p>\n\n<p>Also, based on your <code>PostTypes</code> table I think each type of \"posts\" should be different enough to store it in its own table. In that case the whole story of validating types is gone, and all the validation will be done by foreign keys.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T14:41:46.830", "Id": "36682", "Score": "0", "body": "Thanks for taking the time to answer. :) I don't have control over the client code, in fact several different client apps will connect to this db, so I don't want to rely on a BLL in the client. About splitting [Posts] into separate tables, I'd initially designed it that way, but there's a lot of common code for all post types (revisions, flags, access control, etc.) that would need to be duplicated. I suppose I could use something like a TPT inheritance model, but I'm not sure how to do that in pure SQL." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T07:14:38.950", "Id": "23770", "ParentId": "23767", "Score": "1" } } ]
{ "AcceptedAnswerId": "23770", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T05:55:42.317", "Id": "23767", "Score": "3", "Tags": [ "sql", "sql-server" ], "Title": "Request review of sql validation trigger" }
23767
<p>I'm using both Core Data and <code>NSFetchedResultsController</code>. Is there anything I can improve on?</p> <pre><code>// // RoutineTableViewController.m // App // // Created by Me on 3/21/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #import "RoutineTableViewController.h" #import &lt;QuartzCore/QuartzCore.h&gt; #import "FlurryAnalytics.h" #import "RoutineDayTableViewController.h" #import "Routine.h" #import "Exercise.h" #import "DataModelController.h" @implementation RoutineTableViewController - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:YES]; self.fetchedResultsController = nil; [self.fetchedResultsController performFetch:nil]; [self toggleEditButton]; } - (void)viewDidLoad { [super viewDidLoad]; [FlurryAnalytics logEvent:@"Routine"]; if (!self.managedObjectContext) { self.managedObjectContext = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; } self.navigationItem.title = @"Routines"; self.routineTableView.rowHeight = 65; self.routineTableView.delegate = self; self.routineTableView.backgroundColor = [UIColor clearColor]; self.view.backgroundColor = [UIColor myBackgroundColor]; self.navigationItem.leftBarButtonItem = self.editButtonItem; self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(presentCreateRoutineAlert)]; [self toggleEditButton]; } - (void)toggleEditButton { if (!self.fetchedResultsController.fetchedObjects.count &gt; 0) { self.navigationItem.leftBarButtonItem.enabled = NO; } else { self.navigationItem.leftBarButtonItem.enabled = YES; } } -(void)presentCreateRoutineAlert { UIAlertView *anAlert = [[UIAlertView alloc]initWithTitle:@"Add Routine" message:@"Enter name for routine" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Create", nil]; [anAlert setAlertViewStyle:UIAlertViewStylePlainTextInput]; [anAlert show]; } - (void)alertView:(UIAlertView *)iAlertView willDismissWithButtonIndex:(NSInteger)iButtonIndex { if (iButtonIndex != [iAlertView cancelButtonIndex]) { NSString *aRoutineName = [iAlertView textFieldAtIndex:0].text; [self createRoutineWithName:aRoutineName]; } } -(void)createRoutineWithName:(NSString *)iRoutineName { Routine *aRoutine = [DataModelController createRotuineWithName:iRoutineName]; [self.routineTableView reloadData]; [self pushToListForRoutine:aRoutine]; } -(void)pushToListForRoutine:(Routine *)iRoutine { RoutineDayTableViewController *detailViewController = [[RoutineDayTableViewController alloc] initWithNibName:@"RoutineDayTableViewController" bundle:nil withRoutine:iRoutine]; detailViewController.hidesBottomBarWhenPushed = YES; [self.navigationController pushViewController:detailViewController animated:YES]; } #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { id &lt;NSFetchedResultsSectionInfo&gt; sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; return [sectionInfo numberOfObjects]; } - (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath { cell.imageView.image = [UIImage imageNamed:@"44-shoebox.png"]; cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"newcell.png"]]; cell.textLabel.backgroundColor = [UIColor clearColor]; cell.detailTextLabel.backgroundColor = [UIColor clearColor]; cell.textLabel.font = [UIFont textLabelFontBig]; Routine *aRoutine = (Routine *)[self.fetchedResultsController objectAtIndexPath:indexPath]; cell.textLabel.text = aRoutine.name; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [self.routineTableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; } [self configureCell:cell atIndexPath:indexPath]; return cell; } - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { return YES; } - (void)setEditing:(BOOL)editing animated:(BOOL)animate { [self.routineTableView setEditing: !self.routineTableView.editing animated:YES]; if (self.routineTableView.editing) [self.navigationItem.leftBarButtonItem setTitle:@"Done"]; else [self.navigationItem.leftBarButtonItem setTitle:@"Edit"]; } - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]]; NSError *error = nil; if (![self.managedObjectContext save:&amp;error]) { NSLog(@"error: %@", error); } } } - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { return YES; } #pragma mark - Table view delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { Routine *aRoutine = (Routine *)[self.fetchedResultsController objectAtIndexPath:indexPath]; [self pushToListForRoutine:aRoutine]; [tableView deselectRowAtIndexPath:indexPath animated:YES]; } #pragma mark - Fetched results controller - (NSFetchedResultsController *)fetchedResultsController { if (_fetchedResultsController != nil) { return _fetchedResultsController; } NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:YES]; [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]]; [fetchRequest setFetchBatchSize:20]; NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil]; self.fetchedResultsController = theFetchedResultsController; _fetchedResultsController.delegate = self; NSError *error = nil; if (![theFetchedResultsController performFetch:&amp;error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return _fetchedResultsController; } #pragma mark - Fetched results controller delegate - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller { [self.routineTableView beginUpdates]; } - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { [self.routineTableView endUpdates]; [self toggleEditButton]; } - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id &lt;NSFetchedResultsSectionInfo&gt;)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type { switch(type) { case NSFetchedResultsChangeInsert: [self.routineTableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationAutomatic]; break; case NSFetchedResultsChangeDelete: [self.routineTableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationAutomatic]; break; } } - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath { UITableView *tableView = self.routineTableView; switch(type) { case NSFetchedResultsChangeInsert: [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; break; case NSFetchedResultsChangeDelete: [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; break; case NSFetchedResultsChangeUpdate: [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath]; break; case NSFetchedResultsChangeMove: [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic]; [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationAutomatic]; break; } } @end </code></pre>
[]
[ { "body": "<p>Just briefly looking at your table view controller code, I'd <em>in general</em> suggest a more efficient way of configuring your cells. You have:</p>\n\n<pre><code>- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {\n cell.imageView.image = [UIImage imageNamed:@\"44-shoebox.png\"];\n cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;\n cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@\"newcell.png\"]];\n cell.textLabel.backgroundColor = [UIColor clearColor];\n cell.detailTextLabel.backgroundColor = [UIColor clearColor];\n cell.textLabel.font = [UIFont textLabelFontBig];\n\n Routine *aRoutine = (Routine *)[self.fetchedResultsController objectAtIndexPath:indexPath];\n cell.textLabel.text = aRoutine.name;\n}\n\n- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {\n static NSString *CellIdentifier = @\"Cell\";\n\n UITableViewCell *cell = [self.routineTableView dequeueReusableCellWithIdentifier:CellIdentifier];\n\n if (!cell) {\n cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];\n }\n\n [self configureCell:cell atIndexPath:indexPath];\n return cell;\n}\n</code></pre>\n\n<p>This means that <code>configureCell:atIndexPath:</code> will be run <strong>every time</strong> a cell is requested, which happens whenever the user scrolls the table. Most of the work in that method only needs to be done when <strong>new</strong> cells are created, which won't necessarily even happen during every user scroll (since cells are <em>recycled</em>).</p>\n\n<p>... especially since you're creating a new <code>UIImageView</code> in that method, which isn't necessary. It looks like only this line:</p>\n\n<pre><code>cell.textLabel.text = aRoutine.name;\n</code></pre>\n\n<p>needs to be run every time a cell is requested, since the name can change. So, I would move that code out of <code>configureCell:atIndexPath:</code>, and change your code to this:</p>\n\n<pre><code> - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {\n static NSString *CellIdentifier = @\"Cell\";\n\n UITableViewCell *cell = [self.routineTableView dequeueReusableCellWithIdentifier:CellIdentifier];\n\n if (!cell) {\n cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];\n [self configureCell:cell atIndexPath:indexPath];\n }\n\n // update the cell label for this specific routine name:\n Routine *aRoutine = (Routine *)[self.fetchedResultsController objectAtIndexPath:indexPath];\n cell.textLabel.text = aRoutine.name;\n\n return cell;\n }\n</code></pre>\n\n<p>Now, with the way we're using <code>configureCell:atIndexPath:</code>, it might be clearer to rename it to <code>initializeCell:atIndexPath:</code> or something. Also, if you have too much more code in that method, I might suggest making a new subclass of <code>UITableViewCell</code>, and just putting all that code into its <code>initWithStyle:reuseIdentifier:</code> method, so you can remove the call to <code>configureCell:atIndexPath:</code> from the table view controller completely. </p>\n\n<p>But, that would be more of a code modularity / cleanliness issue. The first point I made about not calling <code>configureCell:atIndexPath:</code> every time can actually be a performance issue.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T22:23:43.157", "Id": "25298", "ParentId": "23769", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T06:32:48.330", "Id": "23769", "Score": "4", "Tags": [ "objective-c", "ios", "cocoa-touch" ], "Title": "NSFetchedResultsController implementation" }
23769
<p>Because we're passing object to Spring Framework in which Jackson classes convert them into JSON as a response, we chose to implement a simpler <code>Tweet</code> class rather than the Twitter4j-provided <code>Status</code> class, which includes numerous data that is irrelevant.</p> <p>Status class provided by Twitter4j has arrays of entities that specify start and end indices of the entity in the body text.</p> <p>For example:</p> <blockquote> <p>Hello @fuxximus, how are you?</p> </blockquote> <p>The tweet will have an entity @fuxximus with indices: start 6 end 15. So having multiple entities and inserting tags around them makes any index after the inserted shifted by the number of chars of the inserted tag/string. I don't think the entities are sorted in the order of their appearance, and even so it wouldn't matter because there are different types of entities.</p> <p>So to account to that I came up with a simple <code>HashMap</code> that registers all indices and their added string length as they're entered, then when inserting every next insertion it calculates its new offset if change to it has been made from the <code>HashMap</code>.</p> <p>Note: the tags will be more dynamic in the future, so the length of the tag will be variable.</p> <p>Is there a more elegant way of solving this than using HashMap and looping through it every single entity? I couldn't come up with anything else.</p> <pre><code>package com.univision.proxy.data.twitter; import java.util.Date; import java.util.HashMap; import java.util.Map; import twitter4j.HashtagEntity; import twitter4j.MediaEntity; import twitter4j.Status; import twitter4j.URLEntity; import twitter4j.UserMentionEntity; public class Tweet { public String name; public String screenname; public Date time; public String body; public Boolean is_retweet = false; public String original_name = null; public String original_screenname = null; public Date original_time = null; public long original_id = 0; public long id; public Tweet(Status stat){ if(stat.isRetweet()){ this.is_retweet = true; this.original_name = stat.getUser().getName(); this.original_screenname = stat.getUser().getScreenName(); this.original_time = stat.getCreatedAt(); this.original_id = stat.getId(); stat = stat.getRetweetedStatus(); } this.name = stat.getUser().getName(); this.screenname = stat.getUser().getScreenName(); this.time = stat.getCreatedAt(); this.id = stat.getId(); this.body = ParseTweetText(stat); } public static String ParseTweetText(Status stat) { StringBuffer body = new StringBuffer(stat.getText()); HashMap&lt;Integer,Integer&gt; paddings = new HashMap&lt;Integer,Integer&gt;(); HashtagEntity[] hashtags = stat.getHashtagEntities(); MediaEntity[] medias = stat.getMediaEntities(); URLEntity[] urls = stat.getURLEntities(); UserMentionEntity[] users = stat.getUserMentionEntities(); String tag = ""; for(HashtagEntity hashtag : hashtags){ tag = "&lt;span class=\"link\"&gt;"; body.insert(CalculateOffset(paddings, hashtag.getStart()), tag); paddings.put(hashtag.getStart(), tag.length()); tag = "&lt;/span&gt;"; body.insert(CalculateOffset(paddings, hashtag.getEnd()), tag); paddings.put(hashtag.getEnd(), tag.length()); } for(MediaEntity media : medias){ tag = "&lt;span class=\"link\"&gt;"; body.insert(CalculateOffset(paddings, media.getStart()), tag); paddings.put(media.getStart(), tag.length()); tag = "&lt;/span&gt;"; body.insert(CalculateOffset(paddings, media.getEnd()), tag); paddings.put(media.getEnd(), tag.length()); } for(URLEntity url : urls){ tag = "&lt;span class=\"link\"&gt;"; body.insert(CalculateOffset(paddings, url.getStart()), tag); paddings.put(url.getStart(), tag.length()); tag = "&lt;/span&gt;"; body.insert(CalculateOffset(paddings, url.getEnd()), tag); paddings.put(url.getEnd(), tag.length()); } for(UserMentionEntity user : users){ tag = "&lt;span class=\"link\"&gt;"; body.insert(CalculateOffset(paddings, user.getStart()), tag); paddings.put(user.getStart(), tag.length()); tag = "&lt;/span&gt;"; body.insert(CalculateOffset(paddings, user.getEnd()), tag); paddings.put(user.getEnd(), tag.length()); } return body.toString(); } public static int CalculateOffset(HashMap&lt;Integer,Integer&gt; indices, int index) { int ret_val = index; for (Map.Entry&lt;Integer, Integer&gt; entry : indices.entrySet()) { if(index &gt; entry.getKey()){ ret_val += entry.getValue(); } } return ret_val; } } </code></pre>
[]
[ { "body": "<p>If the interfaces <code>HashtagEntity</code>, <code>MediaEntity</code>, <code>URLEntity</code>, and <code>UserMentionEntity</code> were subinterfaces of a superinterface <code>Entity</code>, you could refactor the 4 loops into 4 calls to one function that would take <code>Entity[]</code> as one of the parameters, although with the Java inability to pass byref, I'm not sure it would be that good.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T01:40:41.677", "Id": "36808", "Score": "0", "body": "I checked twitter4j docs those 4 did not share any common class as you said. It would have been nice though. Wait.... i think i missed something." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T01:45:52.043", "Id": "36809", "Score": "0", "body": "Only URLEntity extends MediaEntity, and all 4 only have java.io.Serializable as a superinterface." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T15:52:29.053", "Id": "36945", "Score": "0", "body": "Yes, that's why I said \"If\". It looks like you are already messing with the source code by replacing the provided Tweet class with your own. You can create the `Entity` interface yourself and make the other interface become subinterfaces of the `Entity` one." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T16:13:41.120", "Id": "23865", "ParentId": "23776", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T08:55:29.250", "Id": "23776", "Score": "4", "Tags": [ "java", "strings", "twitter", "hash-map" ], "Title": "Insert tags around entities in body" }
23776
<p>This is my second attempt to create asynchronous version of AutoResetEvent. <a href="https://codereview.stackexchange.com/questions/23522/autoreseteventasync-am-i-missing-something">At first</a> I tried to make it completely lock-less, but it turned out to be impossible. This implementation contains a lock however the lock isn't an instance wide:</p> <pre><code>/// &lt;summary&gt; /// Asynchronous version of &lt;see cref="AutoResetEvent" /&gt; /// &lt;/summary&gt; public sealed class AutoResetEventAsync { private static readonly Task&lt;bool&gt; Completed = Task.FromResult(true); private readonly ConcurrentQueue&lt;TaskCompletionSource&lt;bool&gt;&gt; handlers = new ConcurrentQueue&lt;TaskCompletionSource&lt;bool&gt;&gt;(); private int isSet; /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="AutoResetEventAsync" /&gt; class with a Boolean value indicating whether to set the intial state to signaled. /// &lt;/summary&gt; /// &lt;param name="initialState"&gt;true to set the initial state signaled; false to set the initial state to nonsignaled.&lt;/param&gt; public AutoResetEventAsync(bool initialState) { this.isSet = initialState ? 1 : 0; } /// &lt;summary&gt; /// Sets the state of the event to signaled, allowing one waiting continuation to proceed. /// &lt;/summary&gt; public void Set() { if (!this.TrySet()) return; TaskCompletionSource&lt;bool&gt; handler; // Notify first alive handler while (this.handlers.TryDequeue(out handler)) if (CheckIfAlive(handler)) // Flag check lock (handler) { if (!CheckIfAlive(handler)) continue; if (this.TryReset()) handler.SetResult(true); else this.handlers.Enqueue(handler); break; } } /// &lt;summary&gt; /// Try to switch the state to signaled from not signaled /// &lt;/summary&gt; /// &lt;returns&gt; /// true if suceeded, false if failed /// &lt;/returns&gt; private bool TrySet() { return Interlocked.CompareExchange(ref this.isSet, 1, 0) == 0; } /// &lt;summary&gt; /// Waits for a signal asynchronously /// &lt;/summary&gt; public Task WaitAsync() { return this.WaitAsync(CancellationToken.None); } /// &lt;summary&gt; /// Waits for a signal asynchronously /// &lt;/summary&gt; /// &lt;param name="cancellationToken"&gt; /// A &lt;see cref="P:System.Threading.Tasks.TaskFactory.CancellationToken" /&gt; to observe while waiting for a signal. /// &lt;/param&gt; /// &lt;exception cref="OperationCanceledException"&gt; /// The &lt;paramref name="cancellationToken" /&gt; was canceled. /// &lt;/exception&gt; public Task WaitAsync(CancellationToken cancellationToken) { // Short path if (this.TryReset()) return Completed; cancellationToken.ThrowIfCancellationRequested(); // Wait for a signal var handler = new TaskCompletionSource&lt;bool&gt;(false); this.handlers.Enqueue(handler); if (CheckIfAlive(handler)) // Flag check lock (handler) if (CheckIfAlive(handler) &amp;&amp; this.TryReset()) { handler.SetResult(true); return handler.Task; } cancellationToken.Register(() =&gt; { if (CheckIfAlive(handler)) // Flag check lock (handler) if (CheckIfAlive(handler)) handler.SetCanceled(); }); return handler.Task; } private static bool CheckIfAlive(TaskCompletionSource&lt;bool&gt; handler) { return handler.Task.Status == TaskStatus.WaitingForActivation; } private bool TryReset() { return Interlocked.CompareExchange(ref this.isSet, 0, 1) == 1; } } </code></pre> <p>Any suggestions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-14T17:21:44.153", "Id": "36843", "Score": "0", "body": "If it's an `AutoResetEvent`, shouldn't it allow only one continuation to proceed? Your documentation for `Set()` says otherwise." } ]
[ { "body": "<p>Your new code seems thread-safe to me. Though there are some small issues:</p>\n\n<pre><code>lock (handler)\n</code></pre>\n\n<p>I think that you should use braces after <code>lock</code>/<code>if</code>/<code>while</code> whenever the following statement is more than a single line, even if the language doesn't require it. It makes it simpler to see where does which block end.</p>\n\n<pre><code>if (CheckIfAlive(handler)) // Flag check\n lock (handler)\n if (CheckIfAlive(handler) &amp;&amp; this.TryReset()) {\n handler.SetResult(true);\n return handler.Task;\n }\n</code></pre>\n\n<p>I don't see any reason to perform this check here again. <code>TryReset()</code> was already checked just a few quick lines before.</p>\n\n<pre><code>if (CheckIfAlive(handler)) // Flag check\n lock (handler)\n if (CheckIfAlive(handler))\n</code></pre>\n\n<p>Double checked locking is a dangerous practice, because it's hard to get right. I <em>think</em> your usage of it here is correct, but I would still avoid using it, unless you know the small performance gain will actually make a difference for you.</p>\n\n<pre><code>if (CheckIfAlive(handler))\n handler.SetCanceled();\n</code></pre>\n\n<p>Instead of calling <code>CheckIfAlive()</code> all over the place, you could use the <code>Try*</code> methods instead.</p>\n\n<pre><code>if (this.TryReset())\n handler.SetResult(true);\nelse\n this.handlers.Enqueue(handler);\n</code></pre>\n\n<p>Primitives like <code>AutoResetEvent</code> usually don't guarantee strict FIFO ordering. But I think they should guarantee at least some amount of fairness. With your implementation, it's not that unlikely that an item will never be processed (because it's constantly being moved to the back of the queue) even while others are being processed normally. I think you should think about whether this is a problem for you or not.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-17T15:50:07.923", "Id": "24012", "ParentId": "23783", "Score": "3" } }, { "body": "<blockquote>\n <p>At first I tried to make it completely lock-less, but it turned out to be impossible. This implementation contains a lock however the lock isn't an instance wide.</p>\n</blockquote>\n\n<p>It may shock you to hear that lock-free code may be slower than code using locking.</p>\n\n<p>Lock-free code is usually longer and is definitely much more complex. You should not attempt to write lock-free code until you fully understand the <a href=\"http://www.bluebytesoftware.com/blog/2007/11/10/CLR20MemoryModel.aspx\">.NET</a> <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163715.aspx\">memory</a> <a href=\"http://msdn.microsoft.com/en-us/magazine/jj863136.aspx\">model</a>. <a href=\"http://tinyurl.com/kzmryxg\">Joe Duffy's book</a> would be a good starting point after reading those articles. I would say you are ready to write lock-free code when you can describe why <a href=\"http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html\">double-checked locking is broken in Java</a> and correctly answer this question: is it also broken in C#?</p>\n\n<p>But back to the point: lock-free code is easily <em>slower</em> than regular locking in this instance because lock-free code is only faster when there's a lot of <em>contention</em>. When you're writing <code>async</code>-compatible primitives, any locks you take are only going to last for the <em>synchronous</em> portion of that method call - an extremely short time. So, unless you have literally hundreds of different threads all calling <em>Set</em> or <em>WaitAsync</em> on the same instance at the same time, you won't have a problem. In other words, <code>async</code> primitives kind of \"lift\" you to a higher level of scheduling - you actually build your own queue of waiters. And any <code>lock</code> you have isn't going to affect the <em>real</em> contention, which will be represented by that queue.</p>\n\n<p>So, on with the actual code review...</p>\n\n<p>As @svick correctly pointed out, you have a (benign) race condition in your code that may cause starvation, when your <code>Set</code> chooses to re-enqueue a TCS. You are also holding onto resources longer than necessary by keeping \"dead\" TCS instances in your queue. Remember that each TCS has a <code>Task</code> along with all its continuations, and any local variables captured by their lambdas, etc.</p>\n\n<p>But that's not a deal-breaker, it's just somewhat unfair (starvation) and inefficient (holding references). There's a more sinister and subtle problem with this implementation.</p>\n\n<p>You are calling back to end-user code while holding a lock. This is violating one of the central laws of multithreaded programming. Whenever you do this, there is a possibility of deadlock.</p>\n\n<p>It's very subtle because the callback is not obvious, but it's there in both <code>Set</code> and <code>Reset</code>: <code>SetResult</code> and <code>SetCanceled</code> both (synchronously) invoke any task continuations that were scheduled with the <code>ExecuteSynchronously</code> flag.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-27T02:05:54.217", "Id": "29047", "ParentId": "23783", "Score": "7" } }, { "body": "<p>The code does a lot of <code>cancellationToken.Register()</code> calls without ever unregistering.</p>\n\n<p>I'd create an inner class</p>\n\n<pre><code>private class Handler\n{\n /// &lt;summary&gt;\n /// Gets or sets the task completion source.\n /// &lt;/summary&gt;\n public TaskCompletionSource&lt;bool&gt; TaskCompletionSource { get; set; }\n\n /// &lt;summary&gt;\n /// Gets or sets the cancellation token registration.\n /// &lt;/summary&gt;\n public CancellationTokenRegistration CancellationTokenRegistration { get; set; }\n}\n</code></pre>\n\n<p>and set that as what the <code>ConcurrentQueue</code> holds. Then, go</p>\n\n<pre><code>var handler = new Handler { TaskCompletionSource = new TaskCompletionSource&lt;bool&gt;(false) };\n</code></pre>\n\n<p>and a few lines down from there:</p>\n\n<pre><code>lock (handler)\n{\n handler.CancellationTokenRegistration = cancellationToken.Register(\n () =&gt;\n {\n if (CheckIfAlive(handler.TaskCompletionSource)) // Flag check\n {\n lock (handler)\n {\n if (CheckIfAlive(handler.TaskCompletionSource))\n {\n handler.TaskCompletionSource.SetCanceled();\n }\n }\n }\n });\n}\n</code></pre>\n\n<p>Finally, sprinkle <code>handler.CancellationTokenRegistration.Dispose();</code> lines where ever the dequeued handler gets used and not requeued (no need to check for null, it is a struct).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-05T15:52:49.510", "Id": "59128", "ParentId": "23783", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T11:34:01.193", "Id": "23783", "Score": "5", "Tags": [ "c#", ".net", "multithreading", "asynchronous", "async-await" ], "Title": "Asynchronous version of AutoResetEvent" }
23783
<p>I wrote a two player Noughts and Crosses game in Python 3, and came here to ask how I can improve this code.</p> <pre><code>import random cell = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] board = '\n\t ' + cell[0] + ' | ' + cell[1] + ' | ' + cell[2] + '\n\t-----------\n\t ' + cell[3] + ' | ' + cell[4] + ' | ' + cell[5] + '\n\t-----------\n\t ' + cell[6] + ' | ' + cell[7] + ' | ' + cell[8] def owin(cell): return cell[0] == cell[1] == cell[2] == 'O' or cell[3] == cell[4] == cell[5] == 'O' or cell[6] == cell[7] == cell[8] == 'O' or cell[0] == cell[3] == cell[6] == 'O' or cell[1] == cell[4] == cell[7] == 'O' or cell[2] == cell[5] == cell[8] == 'O' or cell[0] == cell[4] == cell[8] == 'O' or cell[2] == cell[4] == cell[6] == 'O' def xwin(cell): return cell[0] == cell[1] == cell[2] == 'X' or cell[3] == cell[4] == cell[5] == 'X' or cell[6] == cell[7] == cell[8] == 'X' or cell[0] == cell[3] == cell[6] == 'X' or cell[1] == cell[4] == cell[7] == 'X' or cell[2] == cell[5] == cell[8] == 'X' or cell[0] == cell[4] == cell[8] == 'X' or cell[2] == cell[4] == cell[6] == 'X' def tie(cell): return cell[0] in ('O', 'X') and cell[1] in ('O', 'X') and cell[2] in ('O', 'X') and cell[3] in ('O', 'X') and cell[4] in ('O', 'X') and cell[5] in ('O', 'X') and cell[6] in ('O', 'X') and cell[7] in ('O', 'X') and cell[8] in ('O', 'X') print('\tNOUGHTS AND CROSSES\n\t\tBy Lewis Cornwall') instructions = input('Would you like to read the instructions? (y/n)') if instructions == 'y': print('\nEach player takes turns to place a peice on the following grid:\n\n\t 1 | 2 | 3\n\t-----------\n\t 4 | 5 | 6\n\t-----------\n\t 7 | 8 | 9\n\nBy inputing a vaule when prompted. The first to 3 peices in a row wins.') player1 = input('Enter player 1\'s name: ') player2 = input('Enter player 2\'s name: ') print(player1 + ', you are O and ' + player2 + ', you are X.') nextPlayer = player1 while not(owin(cell) or xwin(cell)) and not tie(cell): print('This is the board:\n' + board) if nextPlayer == player1: move = input('\n' + player1 + ', select a number (1 - 9) to place your peice: ') cell[int(move) - 1] = 'O' board = '\n\t ' + cell[0] + ' | ' + cell[1] + ' | ' + cell[2] + '\n\t-----------\n\t ' + cell[3] + ' | ' + cell[4] + ' | ' + cell[5] + '\n\t-----------\n\t ' + cell[6] + ' | ' + cell[7] + ' | ' + cell[8] nextPlayer = player2 else: move = input('\n' + player2 + ', select a number (1 - 9) to place your peice: ') cell[int(move) - 1] = 'X' board = '\n\t ' + cell[0] + ' | ' + cell[1] + ' | ' + cell[2] + '\n\t-----------\n\t ' + cell[3] + ' | ' + cell[4] + ' | ' + cell[5] + '\n\t-----------\n\t ' + cell[6] + ' | ' + cell[7] + ' | ' + cell[8] nextPlayer = player1 if owin(cell): print('Well done, ' + player1 + ', you won!') elif xwin(cell): print('Well done, ' + player2 + ', you won!') else: print('Unfortunately, neither of you were able to win today.') input('Press &lt;enter&gt; to quit.') </code></pre>
[]
[ { "body": "<p>Some notes:</p>\n\n<blockquote>\n <p>cell = ['1', '2', '3', '4', '5', '6', '7', '8', '9']</p>\n</blockquote>\n\n<p>Try to be less verbose: <code>cell = \"123456789\".split()</code> or <code>cell = [str(n) for n in range(1, 10)]</code>. Anyway, conceptually it's very dubious you initialize the board with its number instead of its state. Also, <code>cell</code> is not a good name, it's a collection, so <code>cells</code>.</p>\n\n<pre><code>board = '\\n\\t ' + cell[0] + ...\n</code></pre>\n\n<p>Don't write such a long lines, split them to fit a sound max width (80/100/...). Anyway, here the problem is that you shouldn't do that manually, do it programmatically (<a href=\"http://docs.python.org/2/library/itertools.html#recipes\" rel=\"nofollow noreferrer\">grouped</a> from itertools):</p>\n\n<pre><code>board = \"\\n\\t-----------\\n\\t\".join(\" | \".join(xs) for xs in grouped(cell, 3)) \n</code></pre>\n\n<blockquote>\n <p>return cell[0] == cell<a href=\"http://docs.python.org/2/library/itertools.html#recipes\" rel=\"nofollow noreferrer\">1</a> == cell[2] == 'O' or cell[3] == cell[4] == cell[5] == 'O' or cell[6] == cell[7] == cell[8] == 'O' or cell[0] == cell[3] == cell[6] == 'O' or cell<a href=\"http://docs.python.org/2/library/itertools.html#recipes\" rel=\"nofollow noreferrer\">1</a> == cell[4] == cell[7] == 'O' or cell[2] == cell[5] == cell[8]== 'O</p>\n</blockquote>\n\n<p>Ditto, use code: </p>\n\n<pre><code>groups = grouped(cell, 3)\nany(all(x == 'O' for x in xs) for xs in [groups, zip(*groups)])\n</code></pre>\n\n<p>Note that you are not checking if a cell has already a piece.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T12:23:06.963", "Id": "23787", "ParentId": "23784", "Score": "4" } }, { "body": "<p>Do not repeat code for each player. Instead, create functions with appropriate parameters. For example, instead of <code>if owin(cell):</code> you could have a <code>win</code> function that can be used like</p>\n\n<pre><code>if win(cell, 'O'):\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if win(cell) == 'O':\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T12:51:37.347", "Id": "23788", "ParentId": "23784", "Score": "0" } }, { "body": "<p>You should change <code>input</code> to <code>raw_input</code> so that its automatically passed as a string.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T17:46:54.410", "Id": "36697", "Score": "2", "body": "this appears to be python3, so that doesn't apply." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T17:47:39.673", "Id": "36698", "Score": "1", "body": "I am using Python 3, so `raw_input` should not be used" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T17:44:55.397", "Id": "23801", "ParentId": "23784", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T11:42:53.097", "Id": "23784", "Score": "9", "Tags": [ "python", "game" ], "Title": "Noughts and Crosses game in Python" }
23784
<p>I have a card matching game with a model of:</p> <ul> <li><code>Card</code></li> <li><code>Deck</code></li> <li><code>PlayingCard</code></li> <li><code>PlayingCardDeck</code></li> </ul> <p>And another model called <code>CardMatchingGame</code>.</p> <p>Now, I had a task to add a button to the view for new game, which deals the cards again and setting the labels to 0 (#flips and score).</p> <p>I added this method:</p> <pre><code>- (IBAction)newGame:(UIButton *)sender { self.flipsCount = 0; self.game = nil; for (UIButton *button in self.cardButtons) { Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:button]]; card.unplayble = NO; card.faceUp = NO; button.alpha = 1; } self.notificationLabel.text = nil; [self updateUI]; } </code></pre> <p>And this is the whole viewcontroller:</p> <pre><code>#import "CardGameViewController.h" #import "PlayingCardsDeck.h" #import "CardMatchingGame.h" @interface CardGameViewController () @property (weak, nonatomic) IBOutlet UILabel *flipsLabel; @property (weak, nonatomic) IBOutlet UILabel *notificationLabel; @property (weak, nonatomic) IBOutlet UILabel *scoreCounter; @property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *cardButtons; @property (strong, nonatomic) CardMatchingGame *game; @property (nonatomic) int flipsCount; @end @implementation CardGameViewController //creating the getter method that creates a new card game. -(CardMatchingGame *) game { if (!_game) _game = [[CardMatchingGame alloc] initWithCardCount:self.cardButtons.count usingDeck:[[PlayingCardsDeck alloc] init]]; return _game; } //creating a setter for the IBOutletCollection cardButtons -(void) setCardButtons:(NSArray *)cardButtons { _cardButtons = cardButtons; [self updateUI]; } //creating the setter for the flipCount property. Whick is setting the flipsLabel to the right text and adding the number of counts. -(void) setFlipsCount:(int)flipsCount { _flipsCount = flipsCount; self.flipsLabel.text = [NSString stringWithFormat:@"Flips: %d", self.flipsCount]; } -(void) updateUI { for (UIButton *cardButton in self.cardButtons) { Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:cardButton]]; [cardButton setTitle:card.contents forState:UIControlStateSelected]; [cardButton setTitle:card.contents forState:UIControlStateSelected|UIControlStateDisabled]; cardButton.selected = card.isFaceUp; cardButton.enabled = !card.unplayble; if (card.unplayble) { cardButton.alpha = 0.1; } //updating the score self.scoreCounter.text = [NSString stringWithFormat:@"Score: %d", self.game.score]; //if notification in CardMatchingGame.m is no nil, it will be presented if (self.game.notification) { self.notificationLabel.text = self.game.notification; } } } //Here I created a method to flipCards when the card is selected, and give the user a random card from the deck each time he flips the card. After each flip i'm incrementing the flipCount setter by one. - (IBAction)flipCard:(UIButton *)sender { [self.game flipCardAtIndex:[self.cardButtons indexOfObject:sender]]; self.flipsCount++; [self updateUI]; } //cleaning the history using the cleanHistory method in CardMatchingGame.m and creating a new game by setting geme to nil - (IBAction)newGame:(UIButton *)sender { self.flipsCount = 0; self.game = nil; for (UIButton *button in self.cardButtons) { Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:button]]; card.unplayble = NO; card.faceUp = NO; button.alpha = 1; } self.notificationLabel.text = nil; [self updateUI]; } @end </code></pre> <p>Could you please tell me if this is a logical solution? I'm a very new programmer and critiques are important to me.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T09:38:39.303", "Id": "36672", "Score": "0", "body": "if not Code Review, try at Stackoverflow or GameDev.stackexchange.com" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T11:03:13.243", "Id": "36673", "Score": "0", "body": "JohnBigs - I have flagged your question for mod review to see if this would be a good candidate for codereview. If it is, they will automatically migrate the question for you. You are free to flag your question and request the migrate as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T11:06:13.490", "Id": "36674", "Score": "0", "body": "@TimothyGroote - this wouldn't be on-topic for SO as there isn't a problem. This may be too low level of a question to fit in at Gamedev. Codereview is likely the best fit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-20T22:05:33.050", "Id": "39201", "Score": "0", "body": "What is a `Card` vs. a `PlayingCard`? Are there `Card` objects (in your **game**) that are *not* `PlayingCard` instances?" } ]
[ { "body": "<p>You certainly get points for using <code>IBOutletCollection(UIButton)</code>. But, it's unclear why you want to replace this array with a new one? If you're going to do that it should be this view controller that creates the new buttons and adds them as subviews. Also, if you're going to create the buttons in code then I wouldn't expect the first set to be defined in the XIB.</p>\n\n<p>I'm assuming (based on your property definitions) that you're using ARC too.</p>\n\n<p>This section of code can be better by maintaining and incrementing an index instead of interrogating the array you're looping over for the index:</p>\n\n<pre><code>for (UIButton *cardButton in self.cardButtons) {\n Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:cardButton]];\n</code></pre>\n\n<p>Also, in the updateUI button loop you don't need to set the title multiple times to the same thing and the loop should be completed before you modify the label text.</p>\n\n<p>You want to know about logic, but there is basically no logic in this class. What this class does have is a bit of confusion about whether it owns the buttons and associated cards or if some other class does. The only comments that can be made really relate to efficiency rather than logic.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-19T15:07:35.910", "Id": "26341", "ParentId": "23785", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T08:52:02.640", "Id": "23785", "Score": "6", "Tags": [ "beginner", "objective-c", "ios", "playing-cards", "cocoa-touch" ], "Title": "Logic in a card matching game controller" }
23785
<p>Im trying to solve two problems I see with JSF2 and Spring.</p> <h1>First</h1> <ul> <li><code>@Autowired</code> in <code>@ManagedBean</code> does not work</li> <li>Nor does <code>@ViewScoped</code> with <code>@Controller</code></li> <li><code>@ManagedProperty</code> is not type safe and requires setter</li> </ul> <h1>Second</h1> <ul> <li>You can not serialize singleton spring beans without hassle</li> <li>Managed beans must be serializable so the container can serialize the session</li> </ul> <p>So I enabled <code>@Autowired</code> in managed beans and fixed serialization with this common base class which all managed beans (at least <code>@SessionScoped</code> and <code>@ViewScoped</code> ones) derive from.</p> <pre><code>public abstract class Handler implements Serializable { private static final long serialVersionUID = 1L; @PostConstruct private void init() { Spring.appCtx.getAutowireCapableBeanFactory().autowireBean(this); } private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { ois.defaultReadObject(); Spring.appCtx.getAutowireCapableBeanFactory().autowireBean(this); } } </code></pre> <p>Handlers are now implemented like that:</p> <pre><code>@ManagedBean @RequestScoped public class Index extends Handler implements Serializable { private static final long serialVersionUID = 1L; @Autowired SampleService ss; public String hello() { return ss.sayHello(); } } </code></pre> <p>First tests seem fine, but I'm curious if I'm causing any problems I don't know of.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-25T12:40:12.810", "Id": "37535", "Score": "1", "body": "You might consider making the service reference transient. `transient SampleService ss;`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T19:35:11.477", "Id": "73922", "Score": "0", "body": "@cjstehno: Could you write your comment as an asnwer to help us killing a zombie? http://meta.codereview.stackexchange.com/a/1511/7076" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T20:18:59.613", "Id": "73926", "Score": "1", "body": "Sure. No problem. Done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-08T18:12:25.603", "Id": "287179", "Score": "0", "body": "You can make your Managed bean Extends 'SpringBeanAutowiringSupport'" } ]
[ { "body": "<p>You might consider making the service reference transient. </p>\n\n<pre><code>transient SampleService ss;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T20:18:34.080", "Id": "42890", "ParentId": "23790", "Score": "3" } }, { "body": "<ol>\n<li><p><code>Handler</code> is too generic name for a class. Try to find something more descriptive (which doesn't force readers to check the implementation if they want to know what the class does), <code>SerializationHandler</code>, for example.</p></li>\n<li><p>In Java classes could have only one superclass. If you make it an abstract superclass you can't have another one which might be cumbersome in some cases.</p>\n\n<blockquote>\n <p>Inheritance is appropriate only in circumstances where the subclass really is a\n subtype of the superclass. In other words, a class B should extend a class A only if\n an “is-a” relationship exists between the two classes. If you are tempted to have a\n class B extend a class A, ask yourself the question: Is every B really an A? If you\n cannot truthfully answer yes to this question, B should not extend A. If the answer\n is no, it is often the case that B should contain a private instance of A and expose a\n smaller and simpler API: A is not an essential part of B, merely a detail of its\n implementation.</p>\n</blockquote>\n\n<p>Source: <em>Effective Java, Second Edition</em>, <em>Item 16: Favor composition over inheritance</em></p>\n\n<p>I'd use composition with a helper class:</p>\n\n<pre><code>@ManagedBean\n@RequestScoped\npublic class Index implements Serializable {\n private static final long serialVersionUID = 1L;\n\n @Autowired\n SampleService ss;\n\n public String hello() {\n return ss.sayHello();\n }\n\n @PostConstruct\n private void init() {\n WireHelper.wireObject(this);\n }\n\n private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {\n ois.defaultReadObject();\n WireHelper.wireObject(this);\n }\n}\n\npublic final class WireHelper {\n public static void wireObject(Object object) {\n Spring.appCtx.getAutowireCapableBeanFactory().autowireBean(this);\n }\n}\n</code></pre></li>\n<li><p>If you stay with the original implementation: you don't necessarily need <code>implements Serializable</code> here since <code>Handler</code> already implements that interface:</p>\n\n<pre><code>public class Index extends Handler implements Serializable {\n ...\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:25:08.687", "Id": "73948", "Score": "1", "body": "1) Good idea but does not matter too much because every `ManagedBean` will implement `Handler`. 2) I don't know if you are familiar with jsf, but there will be multiple `ManagedBean`s (some call them handlers) per jsf page, which may get easily into hundreds in a big app. If you don't extend, you will have to reimplement `readObject()` every time. Too much duplication and very error prone (may be forgotten, hard to check). The solution we chose one year ago was simply to turn of session serialization in tomcat. Using `@Scope`s `proxyMode` works, too)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:32:07.050", "Id": "73953", "Score": "0", "body": "@atamanroman: Thanks for the feedback! Just to make sure: \"turn of\" -> \"turn off\" - is it a typo?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T22:10:52.507", "Id": "73959", "Score": "1", "body": "Yes of course, sorry. Can't edit anymore, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-15T07:57:20.413", "Id": "164688", "Score": "0", "body": "With Java 8 you can use default methods to achieve both! Interface without Code duplication :-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:00:52.597", "Id": "42897", "ParentId": "23790", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T13:05:19.420", "Id": "23790", "Score": "7", "Tags": [ "java", "dependency-injection", "spring", "jsf-2", "serialization" ], "Title": "Spring autowiring in managed beans with support for serialization - is this safe?" }
23790
<p>There are some things that I know that need to be fixed, such as <code>mysql_*</code> needing to be converted to PDO, and using a better hash. I am working on building a social networking site, and I've been having issues with some of the <code>mysql</code> like <code>mysql_real_escape_string</code> and implementing newer techniques. Any criticism and/or help would be very appreciated.</p> <p>register script</p> <pre><code>&lt;? $reg = @$_POST['reg']; //declaring variables to prevent errors //registration form $fn = (!empty($_POST['fname'])) ? $_POST['fname'] : ''; $ln = (!empty($_POST['lname'])) ? $_POST['lname'] : ''; $un = (!empty($_POST['username'])) ? $_POST['username'] : ''; $em = (!empty($_POST['email'])) ? $_POST['email'] : ''; $em2 = (!empty($_POST['email2'])) ? $_POST['email2'] : ''; $pswd = (!empty($_POST['password'])) ? $_POST['password'] : ''; $pswd2 = (!empty($_POST['password2'])) ? $_POST['password2'] : ''; $d = date("y-m-d"); // Year - Month - Day if ($reg) { if ($em==$em2) { // Check if user already exists $statement = $db-&gt;prepare('SELECT username FROM users WHERE username = :username'); if ($statement-&gt;execute(array(':username' =&gt; $un))) { if ($statement-&gt;rowCount() &gt; 0){ //user exists echo "Username already exists, please choose another user name."; exit(); } } //check all of the fields have been filled in if ($fn&amp;&amp;$ln&amp;&amp;$un&amp;&amp;$em&amp;&amp;$em2&amp;&amp;$pswd&amp;&amp;$pswd2) { //check that passwords match if ($pswd==$pswd2) { //check the maximum length of username/first name/last name does not exceed 25 characters if (strlen($un)&gt;25||strlen($fn)&gt;25||strlen($ln)&gt;25) { echo "The maximum limit for username/first name/last name is 25 characters!"; } else { //check the length of the password is between 5 and 30 characters long if (strlen($pswd)&gt;30||strlen($pswd)&lt;5) { echo "Your password must be between 5 and 30 characters long!"; } else { //encrypt password and password 2 using md5 before sending to database $pswd = md5($pswd); $pswd2 = md5($pswd2); $db-&gt;setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING ); $sql = 'INSERT INTO users (username, first_name, last_name, email, password, sign_up_date)'; $sql .= 'VALUES (:username, :first_name, :last_name, :email, :password, :sign_up_date)'; $query=$db-&gt;prepare($sql); $query-&gt;bindParam(':username', $un, PDO::PARAM_STR); $query-&gt;bindParam(':first_name', $fn, PDO::PARAM_STR); $query-&gt;bindParam(':last_name', $ln, PDO::PARAM_STR); $query-&gt;bindParam(':email', $em, PDO::PARAM_STR); $query-&gt;bindParam(':password', $pswd, PDO::PARAM_STR); $query-&gt;bindParam(':sign_up_date', $d, PDO::PARAM_STR); $query-&gt;execute(); die("&lt;h2&gt;Welcome to Rebel Connect&lt;/h2&gt;Login to your account to get started."); } } } else { echo "Your passwords do not match!"; } } else { echo "Please fill in all fields!"; } } else { echo "Your e-mails don't match!"; } } ?&gt; </code></pre> <p>login script</p> <pre><code>&lt;? //Login Script if (isset($_POST["user_login"]) &amp;&amp; isset($_POST["password_login"])) { $user_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["user_login"]); // filter everything but numbers and letters $password_login = preg_replace('#[^A-Za-z0-9]#i', '', $_POST["password_login"]); // filter everything but numbers and letters $password_login=md5($password_login); $db = new PDO('mysql:host=localhost;dbname=socialnetwork', 'root', 'abc123'); $db-&gt;setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING ); $sql = $db-&gt;prepare("SELECT id FROM users WHERE username = :user_login AND password = :password_login LIMIT 1"); if ($sql-&gt;execute(array( ':user_login' =&gt; $user_login, ':password_login' =&gt; $password_login))) { if ($sql-&gt;rowCount() &gt; 0){ while($row = $sql-&gt;fetch(PDO::FETCH_ASSOC)){ $id = $row["id"]; } $_SESSION["id"] = $id; $_SESSION["user_login"] = $user_login; $_SESSION["password_login"] = $password_login; exit("&lt;meta http-equiv=\"refresh\" content=\"0\"&gt;"); } else { echo 'Either the password or username you have entered is incorrect. Please check them and try again!'; exit(); } } } ?&gt; </code></pre> <p>profile.php</p> <pre><code>&lt;? include("inc/incfiles/header.inc.php");?&gt; &lt;? if(isset($_GET['u'])){ $username = mysql_real_escape_string($_GET['u']); if(ctype_alnum($username)) { //check user exists $check = mysql_query("SELECT username, first_name FROM users WHERE username='$username'"); if(mysql_num_rows($check)===1){ $get = mysql_fetch_assoc($check); $username = $get['username']; $firstname = $get['first_name']; } else { echo "&lt;meta http-equiv=\"refresh\" content=\"0; url=http://localhost/tutorial/findfriends/index.php\"&gt;"; exit(); } } } ?&gt; &lt;div class="postForm"&gt;Post form will go here&lt;/div&gt; &lt;div class="profilePosts"&gt;Your posts will go here&lt;/div&gt; &lt;img src="" height="250" width="200" alt="&lt;? echo $username; ?&gt;'s Profile" title="&lt;? echo $username; ?&gt;'s Profile" /&gt; &lt;br /&gt; &lt;div class="textHeader"&gt;&lt;? echo $username; ?&gt;'s Profile&lt;/div&gt; &lt;div class="profileLeftSideContent"&gt; Some content about this person's profile &lt;/div&gt; &lt;div class="textHeader"&gt;&lt;? echo $username; ?&gt;'s Friends&lt;/div&gt; &lt;div class="profileLeftSideContent"&gt; &lt;img src="#" height="50" width="40"/&gt;&amp;nbsp;&amp;nbsp; &lt;img src="#" height="50" width="40"/&gt;&amp;nbsp;&amp;nbsp; &lt;img src="#" height="50" width="40"/&gt;&amp;nbsp;&amp;nbsp; &lt;img src="#" height="50" width="40"/&gt;&amp;nbsp;&amp;nbsp; &lt;img src="#" height="50" width="40"/&gt;&amp;nbsp;&amp;nbsp; &lt;img src="#" height="50" width="40"/&gt;&amp;nbsp;&amp;nbsp; &lt;img src="#" height="50" width="40"/&gt;&amp;nbsp;&amp;nbsp; &lt;img src="#" height="50" width="40"/&gt;&amp;nbsp;&amp;nbsp; &lt;/div&gt; </code></pre>
[]
[ { "body": "<p><strong>for your register script</strong></p>\n\n<pre><code>$ln = (!empty($_POST['lname'])) ? $_POST['lname'] : '';\n$un = (!empty($_POST['username'])) ? $_POST['username'] : '';\n$em = (!empty($_POST['email'])) ? $_POST['email'] : '';\n$em2 = (!empty($_POST['email2'])) ? $_POST['email2'] : '';\n$pswd = (!empty($_POST['password'])) ? $_POST['password'] : '';\n$pswd2 = (!empty($_POST['password2'])) ? $_POST['password2'] : '';\n$d = date(\"y-m-d\");\n</code></pre>\n\n<ol>\n<li>use more descriptive variable names. looking at <code>$ln</code>, <code>$un</code>, <code>$em</code>, <code>$em2</code> and <code>$d</code> is a real pain to look at lower in the code. Try <code>$lastname</code>, <code>$username</code>, etc.</li>\n<li>instead of using <code>(!empty($_POST['fname']))</code> make it the reverse so you dont have to do a negate. try using <code>(empty($_POST['fname'])) ? '' : $_POST['fname']</code></li>\n<li>Instead of <code>$reg = @$_POST['reg'];</code> and <code>if($fn &amp;&amp; $ln &amp;&amp; $un &amp;&amp; $em &amp;&amp; $em2 &amp;&amp; $pswd &amp;&amp; $pswd2)</code> try: <code>$doRegistration = isset($_POST['reg']) &amp;&amp; !(\nempty($_POST['lname']) ||\nempty($_POST['username']) || \nempty($_POST['email']) ||\nempty($_POST['email2']) ||\nempty($_POST['password']) ||\nempty($_POST['password2']))</code>. Doing this will avoid opening a database connection to check the username if your not actually going to create an account. Only open a database connection when you have all your data lined up and ready to go.</li>\n<li>use constants when ever possible. so for <code>if(strlen($un)&gt;25||strlen($fn)&gt;25||strlen($ln)&gt;25)</code> change 25 to something like USERNAME_MAX_LENGTH, FIRSTNAME_MAX_LENGTH and LASTNAME_MAX_LENGTH by defining it like so: <code>define('USERNAME_MAX_LENGTH', 25);</code> etc. do the same for password length also.</li>\n</ol>\n\n<p><strong>for your login script</strong></p>\n\n<ol>\n<li>There is no need to filter your password and username with <code>preg_replace</code> before you use it in your prepared statement. Just use the <a href=\"http://php.net/manual/en/pdostatement.bindparam.php\" rel=\"nofollow noreferrer\">pdo::bindParam</a> function and it will escape the input for you.</li>\n<li>It's not a good idea to store the password in your session. See <a href=\"https://security.stackexchange.com/questions/18991/is-it-safe-to-store-password-in-php-session\">this on security</a>.</li>\n</ol>\n\n<p><strong>in profile.php</strong></p>\n\n<ol>\n<li>try to use a better variable name than <code>$get</code> and <code>$check</code>. maybe something like <code>$row</code> and <code>$query</code> would be more suitable.</li>\n<li>And you already know this but stop using mysql_* functions and change that over to PDO with prepared statements with param binding.</li>\n<li>Since your not checking for special characters in the username upon registration you need to htmlencode it when you echo it. change all instances of <code>echo $username;</code> to <code>echo(htmlentities($username));</code></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T12:44:47.473", "Id": "36743", "Score": "0", "body": "Thanks Omar for your answer. Most of what you said seems to make sense (whether or not I understand the reason). I didn't know about not storing the password in my session, and I'm going to start trying to find it. For the login script, all I need to do is remove `preg_replace` and the things that follow it? For the registration bit, I echo the following: `echo \"Please Fill In All Fields\"`. Would I place that after the `$doRegistration`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T12:54:33.493", "Id": "36744", "Score": "0", "body": "Also for the defining part, how would I implement that with an `if` statement?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-13T14:25:15.150", "Id": "36752", "Score": "0", "body": "Just define the constants at the top of the script. You reference their value like a regular variable, only without the dollar sign." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T17:57:41.143", "Id": "23802", "ParentId": "23792", "Score": "3" } }, { "body": "<p>Instead of duplicating a lot of code (and having to type each name twice!! -> copy paste errors!):</p>\n\n<pre><code>$ln = (!empty($_POST['lname'])) ? $_POST['lname'] : '';\n$un = (!empty($_POST['username'])) ? $_POST['username'] : '';\n$em = (!empty($_POST['email'])) ? $_POST['email'] : '';\n$em2 = (!empty($_POST['email2'])) ? $_POST['email2'] : '';\n$pswd = (!empty($_POST['password'])) ? $_POST['password'] : '';\n$pswd2 = (!empty($_POST['password2'])) ? $_POST['password2'] : '';\n</code></pre>\n\n<p>I'd create a utility function somewhere (the name is a bit off, that should be made nicer):</p>\n\n<pre><code>function contentOrEmptyString( $stringInput ) {\n return ((!empty($stringInput)) ? $stringInput : '');\n}\n</code></pre>\n\n<p>With that:</p>\n\n<pre><code>$ln = contentOrEmptyString($_POST['lname']);\n$un = contentOrEmptyString($_POST['username']);\n$em = contentOrEmptyString($_POST['email']);\n$em2 = contentOrEmptyString($_POST['email2']);\n$pswd = contentOrEmptyString($_POST['password']);\n$pswd2 = contentOrEmptyString($_POST['password2']);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-19T14:18:01.810", "Id": "24102", "ParentId": "23792", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-12T14:58:30.500", "Id": "23792", "Score": "3", "Tags": [ "php", "pdo" ], "Title": "Review my PHP login and register script, and profile page, and how to improve them" }
23792