Search Results

Search found 331 results on 14 pages for 'mutable'.

Page 13/14 | < Previous Page | 9 10 11 12 13 14  | Next Page >

  • Inheritance - Could not initialize proxy - no Session.

    - by Ninu
    hello....i'm newbie developer.... i really need help at now... i just get started with Nhibernate thing at .Net... when i learn Inheritance and try it...it makes me confusing...why i get error like this : Initializing[AP.Core.Domain.AccountPayable.APInvoice#API03/04/2010/001]-Could not initialize proxy - no Session. this is my xml : <class xmlns="urn:nhibernate-mapping-2.2" mutable="true" name="AP.Core.Domain.AccountPayable.APAdjustment, AP.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" table="APAdjustment"> <id name="AdjustmentNumber" type="System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="AdjustmentNumber" length="17" /> <generator class="assigned" /> </id> <property name="Amount" type="System.Decimal, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="Amount" /> </property> <property name="TransactionDate" type="System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <column name="TransactionDate" /> </property> <many-to-one class="AP.Core.Domain.AccountPayable.APInvoice, AP.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" lazy="proxy" name="PurchaseInvoice"> <column name="PurchaseInvoice_id" not-null="true" /> </many-to-one> <joined-subclass name="AP.Core.Domain.AccountPayable.APCreditAdjustment, AP.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" lazy="true" table="APCreditAdjustment"> <key> <column name="APAdjustment_id" /> </key> </joined-subclass> </class> </hibernate-mapping> and this is inheritance Class : Parent Class -- public class APAdjustment { #region :FIELD private string adjustmentNumber; private decimal amount; private DateTime transactionDate; private APInvoice purchaseInvoice; Child Class -- public class APCreditAdjustment : APAdjustment { public APCreditAdjustment(){ and this my Data access : public IList<APAdjustment> GetByNameAll() { ICriteria criteria = Nhibernatesession.CreateCriteria(typeof(APAdjustment)); return criteria.List<APAdjustment>() ; } My Problem is : when i load data with gridview ...it works...but i change the property to autogenerate="true" ...i missing "PurchaseInvoice" field...and i change to bind manually,and it works..when i edit that gridview ...i get this error... Initializing[AP.Core.Domain.AccountPayable.APInvoice#API03/04/2010/001]-Could not initialize proxy - no Session so then i change my xml ...lazy="no-proxy" ...it still work...but when edit again ...i get error again ..and i do "Comment out the selected lines" to my association "Many-to-one"...i really works it..but that's not i want... CAN ANYBODY HELP ME...??Plizz...:( Note : I almost forget it ,i use fluent hibernate to generate to database.From fluent Hibernate ..i put *.xml file ...so i'm work to xml NHibernate...not fluent hibernate thing...:)

    Read the article

  • Search Display Controller Crashes When Returning Results

    - by Convolution
    I have a tableview with a search display controller. It has been working fine in the past, but recently has started crashing for certain search results. Here my code searches a Golfer based on their Name, Age and Handicap. The data is correctly loaded into the table, I can access and drill down to receive further information. However when I type in a search query for either Name or Age, the app crashes, while the Golfers Handicap is returned fine. Note: dataSouceArray is the data source for the tableview, dataSourceArrayCopy is the mutable copy of the data used to add and remove objects in the search filter. - (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope { /* Update the filtered array based on the search text and scope. */ [self.dataSourceArrayCopy removeAllObjects]; // First clear the filtered array. /* Search the main list for products whose type matches the scope (if selected) and whose name matches searchText; add items that match to the filtered array. */ for (Golfer *golfer in dataSourceArray) { if ([scope isEqualToString:@"Name"] || [golfer.golferName isEqualToString:scope]) { NSComparisonResult result = [golfer.golferName compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])]; if (result == NSOrderedSame) { [self.customerListCopy addObject:golfer]; } } if ([scope isEqualToString:@"Age"] || [golfer.golferAge isEqualToString:scope]) { NSComparisonResult result = [golfer.golferAge compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])]; if (result == NSOrderedSame) { [self.dataSourceArrayCopy addObject:golfer]; } } if ([scope isEqualToString:@"Handicap"] || [golfer.golferHandicap isEqualToString:scope]) { NSComparisonResult result = [golfer.golferHandicap compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])]; if (result == NSOrderedSame) { [self.dataSourceArrayCopy addObject:golfer]; } } } } - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString { [self filterContentForSearchText:searchString scope: [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]]; // Return YES to cause the search result table view to be reloaded. return YES; } - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption { [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope: [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]]; // Return YES to cause the search result table view to be reloaded. return YES; } Any help would be appreciated, thank you for taking the time to read this.

    Read the article

  • ISQLQuery using AddJoin not loading related instance

    - by Remi Despres-Smyth
    I've got a problem using an ISQLQuery with an AddJoin. The entity I'm trying to return is RegionalFees, which has a composite-id which includes a Province instance. (This is the the instance being improperly loaded.) Here's the mapping: <class name="Project.RegionalFees, Project" table="tblRegionalFees"> <composite-id name="Id" class="Project.RegionalFeesId, project" unsaved-value="any" access="property"> <key-many-to-one class="Project.Province, Project" name="Region" access="property" column="provinceId" not-found="exception" /> <key-property name="StartDate" access="property" column="startDate" type="DateTime" /> </composite-id> <property name="SomeFee" column="someFee" type="Decimal" /> <property name="SomeOtherFee" column="someOtherFee" type="Decimal" /> <!-- Other unrelated stuff --> </class> <class name="Project.Province, Project" table="trefProvince" mutable="false"> <id name="Id" column="provinceId" type="Int64" unsaved-value="0"> <generator class="identity" /> </id> <property name="Code" column="code" access="nosetter.pascalcase-m-underscore" /> <property name="Label" column="label" access="nosetter.pascalcase-m-underscore" /> </class> Here's my query method: public IEnumerable<RegionalFees> GetRegionalFees() { // Using an ISQLQuery cause there doesn't appear to be an equivalent of // the SQL HAVING clause, which would be optimal for loading this set const String qryStr = "SELECT * " + "FROM tblRegionalFees INNER JOIN trefProvince " + "ON tblRegionalFees.provinceId=trefProvince.provinceId " + "WHERE EXISTS ( " + "SELECT provinceId, MAX(startDate) AS MostRecentFeesDate " + "FROM tblRegionalFees InnerRF " + "WHERE tblRegionalFees.provinceId=InnerRF.provinceId " + "AND startDate <= ? " + "GROUP BY provinceId " + "HAVING tblRegionalFees.startDate=MAX(startDate))"; var qry = NHibernateSessionManager.Instance.GetSession().CreateSQLQuery(qryStr); qry.SetDateTime(0, DateTime.Now); qry.AddEntity("RegFees", typeof(RegionalFees)); qry.AddJoin("Region", "RegFees.Id.Region"); return qry.List<RegionalFees>(); } The odd behavior here is that when I call GetRegionalFees (whose goal is to load just the most recent fee instances per region), it all loads fine if the Province instance is a proxy. If, however, Province is not loaded as a transparent proxy, the Province instance which is part of RegionalFees' RegionalFeesId property has null Code and Region values, although the Id value is set correctly. It looks to me like I have a problem in how I'm joining the Province class - since if it's lazy loaded the id is set from tblRegionalFees, and it gets loaded independently afterwards - but I haven't been able to figure out the solution.

    Read the article

  • Performance of looping over an Unboxed array in Haskell

    - by Joey Adams
    First of all, it's great. However, I came across a situation where my benchmarks turned up weird results. I am new to Haskell, and this is first time I've gotten my hands dirty with mutable arrays and Monads. The code below is based on this example. I wrote a generic monadic for function that takes numbers and a step function rather than a range (like forM_ does). I compared using my generic for function (Loop A) against embedding an equivalent recursive function (Loop B). Having Loop A is noticeably faster than having Loop B. Weirder, having both Loop A and B together is faster than having Loop B by itself (but slightly slower than Loop A by itself). Some possible explanations I can think of for the discrepancies. Note that these are just guesses: Something I haven't learned yet about how Haskell extracts results from monadic functions. Loop B faults the array in a less cache efficient manner than Loop A. Why? I made a dumb mistake; Loop A and Loop B are actually different. Note that in all 3 cases of having either or both Loop A and Loop B, the program produces the same output. Here is the code. I tested it with ghc -O2 for.hs using GHC version 6.10.4 . import Control.Monad import Control.Monad.ST import Data.Array.IArray import Data.Array.MArray import Data.Array.ST import Data.Array.Unboxed for :: (Num a, Ord a, Monad m) => a -> a -> (a -> a) -> (a -> m b) -> m () for start end step f = loop start where loop i | i <= end = do f i loop (step i) | otherwise = return () primesToNA :: Int -> UArray Int Bool primesToNA n = runSTUArray $ do a <- newArray (2,n) True :: ST s (STUArray s Int Bool) let sr = floor . (sqrt::Double->Double) . fromIntegral $ n+1 -- Loop A for 4 n (+ 2) $ \j -> writeArray a j False -- Loop B let f i | i <= n = do writeArray a i False f (i+2) | otherwise = return () in f 4 forM_ [3,5..sr] $ \i -> do si <- readArray a i when si $ forM_ [i*i,i*i+i+i..n] $ \j -> writeArray a j False return a primesTo :: Int -> [Int] primesTo n = [i | (i,p) <- assocs . primesToNA $ n, p] main = print $ primesTo 30000000

    Read the article

  • question about book example - Java Concurrency in Practice, Listing 4.12

    - by mike
    Hi, I am working through an example in Java Concurrency in Practice and am not understanding why a concurrent-safe container is necessary in the following code. I'm not seeing how the container "locations" 's state could be modified after construction; so since it is published through an 'unmodifiableMap' wrapper, it appears to me that an ordinary HashMap would suffice. EG, it is accessed concurrently, but the state of the map is only accessed by readers, no writers. The value fields in the map are syncronized via delegation to the 'SafePoint' class, so while the points are mutable, the keys for the hash, and their associated values (references to SafePoint instances) in the map never change. I think my confusion is based on what precisely the state of the collection is in the problem. Thanks!! -Mike Listing 4.12, Java Concurrency in Practice, (this listing available as .java here, and also in chapter form via google) /////////////begin code @ThreadSafe public class PublishingVehicleTracker { private final Map<String, SafePoint> locations; private final Map<String, SafePoint> unmodifiableMap; public PublishingVehicleTracker( Map<String, SafePoint> locations) { this.locations = new ConcurrentHashMap<String, SafePoint>(locations); this.unmodifiableMap = Collections.unmodifiableMap(this.locations); } public Map<String, SafePoint> getLocations() { return unmodifiableMap; } public SafePoint getLocation(String id) { return locations.get(id); } public void setLocation(String id, int x, int y) { if (!locations.containsKey(id)) throw new IllegalArgumentException( "invalid vehicle name: " + id); locations.get(id).set(x, y); } } // monitor protected helper-class @ThreadSafe public class SafePoint { @GuardedBy("this") private int x, y; private SafePoint(int[] a) { this(a[0], a[1]); } public SafePoint(SafePoint p) { this(p.get()); } public SafePoint(int x, int y) { this.x = x; this.y = y; } public synchronized int[] get() { return new int[] { x, y }; } public synchronized void set(int x, int y) { this.x = x; this.y = y; } } ///////////end code

    Read the article

  • NSArraycontroller selectionIndexes bindings

    - by Michael Scherbaum
    Hi all, I have the following set-up: A Window that has a splitView in which I display I NSCollectionView in the left view and a detailView in the right view. Both views are set-up in separate xibs. Furthermore I have a Datacontroller (of class NSArrayController) that manages a mutable Array of NSMutableDictionaries (moviesForChoice). The dataController is set-up as application delegate. The movie objects in the array have properties like (name, plot, genre etc.) so far so good... In the xib for the NScollectionview I bound a NSArraycontroller content property to my datacontroller via Application.delegate.moviesForChoice The collectionView accesses the arraycontroller.arrrangedObjects and arraycontroller.selectionIndexes. This works fine the contents are displayed and the selection works fine in the collectionview (my collectionviewItem renders a selection color) In the xib for the detailView I want to display information for the selected object in the collectionview. Therefore I also added an arraycontroller to the xib, bound the content aray to Application.delegate.moviesForChoice and bound the NSTextfields in the view to e.g. arraycontroller.selection.name Here comes my issue: everytime I open the window with the two xibs, my collectionview displays all movies that are for choice correctly, and the detailview displays the information for the 1st object in my collectionview. Whenever I click on a different movie in the collectionView the res. item renders a selection color, but the detailView doesn't update. My understanding of it would be that the DataController is not informed about updates in the selectionIndexes and can therefore not trigger an update in the detailView. Correct me if I'm wrong... To remedy this I tried to bind the selectionIndexes property of the arraycontroller in the collectionView xib to Application.delegate.moviesForChoice.selecionIndexes but this failed with: addObserver:forKeyPath:options:context:] is not supported. Key path: selectionIndexes I could imagine that this means that the datacontroller is not KVO compliant for my Array moviesForChoice, but I implemented the following methods for it: -(void)insertObject:(NSDictionary *)dict inMoviesForChoiceAtIndex:(NSUInteger)index { [moviesForChoice insertObject:dict atIndex:index]; } -(void)removeObjectFromMoviesForChoiceAtIndex:(NSUInteger)index { [moviesForChoice removeObjectAtIndex:index]; } -(void)setMoviesForChoice:(NSMutableArray *)a { moviesForChoice = a; } -(NSArray*)moviesForChoice { return moviesForChoice; } -(NSUInteger)countOfMoviesForChoice { return [moviesForChoice count]; } - (void)addMovieForChoiceObject:(Movie *)anObject { [moviesForChoice addObject:anObject]; } So where am I wrong? How do I correctly bind to the selectionIndexes? You help is much appreciated! M

    Read the article

  • How to replace an object in an NSMutableArray at a given index with a new object

    - by shakeelw
    Hi guys. I have an NSMutableArray object(retained, synthesized as all) that is initiated just fine and I can easily add objects to it using the 'addObject:' method. But if I want to replace an object at a certain index with a new one in that NSMutableArray, it doesn't work. For example: ClassA.h @interface ClassA : NSObject { NSMutableArray *list; } @property (nonatomic, copy, readwrite) NSMutableArray *list; end ClassA.m import "ClassA.h" @implementation ClassA @synthesize list; (id)init { [super init]; NSMutableArray *localList = [[NSMutableArray alloc] init]; self.list = localList; [localList release]; //Add initial data [list addObject:@"Hello "]; [list addObject:@"World"]; } // Custom set accessor to ensure the new list is mutable (void)setList:(NSMutableArray *)newList { if (list != newList) { [list release]; list = [newList mutableCopy]; } } -(void)updateTitle:(NSString *)newTitle:(NSString *)theIndex { int i = [theIndex intValue]-1; [self.list replaceObjectAtIndex:i withObject:newTitle]; NSLog((NSString *)[self.list objectAtIndex:i]); // gives the correct output } However, the change remains true only inside the method. from any other method, the NSLog((NSString *)[self.list objectAtIndex:i]); gives the same old value. How can I actually get the old object replaced with the new one at a specific index so that the change can be noticed from within any other method as well. I even modified the method like this, but the result is the same: -(void)updateTitle:(NSString *)newTitle:(NSString *)theIndex { int i = [theIndex intValue]-1; NSMutableArray *localList = [[NSMutableArray alloc] init]; localList = [localList mutableCopy]; for(int j = 0; j < [list count]; j++) { if(j == i) { [localList addObject:newTitle]; NSLog(@"j == 1"); NSLog([NSString stringWithFormat:@"%d", j]); } else { [localList addObject:(NSString *)[self.list objectAtIndex:j]]; } } [self.list release]; //self.list = [localList mutableCopy]; [self setList:localList]; [localList release]; } Please help out guys :)

    Read the article

  • Perfect Forwarding to async lambda

    - by Alexander Kondratskiy
    I have a function template, where I want to do perfect forwarding into a lambda that I run on another thread. Here is a minimal test case which you can directly compile: #include <thread> #include <future> #include <utility> #include <iostream> #include <vector> /** * Function template that does perfect forwarding to a lambda inside an * async call (or at least tries to). I want both instantiations of the * function to work (one for lvalue references T&, and rvalue reference T&&). * However, I cannot get the code to compile when calling it with an lvalue. * See main() below. */ template <typename T> std::string accessValueAsync(T&& obj) { std::future<std::string> fut = std::async(std::launch::async, [](T&& vec) mutable { return vec[0]; }, std::forward<T>(obj)); return fut.get(); } int main(int argc, char const *argv[]) { std::vector<std::string> lvalue{"Testing"}; // calling with what I assume is an lvalue reference does NOT compile std::cout << accessValueAsync(lvalue) << std::endl; // calling with rvalue reference compiles std::cout << accessValueAsync(std::move(lvalue)) << std::endl; // I want both to compile. return 0; } For the non-compiling case, here is the last line of the error message which is intelligible: main.cpp|13 col 29| note: no known conversion for argument 1 from ‘std::vector<std::basic_string<char> >’ to ‘std::vector<std::basic_string<char> >&’ I have a feeling it may have something to do with how T&& is deduced, but I can't pinpoint the exact point of failure and fix it. Any suggestions? Thank you! EDIT: I am using gcc 4.7.0 just in case this could be a compiler issue (probably not)

    Read the article

  • SDL_BlitSurface segmentation fault (surfaces aren't null)

    - by Trollkemada
    My app is crashing on SDL_BlitSurface() and i can't figure out why. I think it has something to do with my static object. If you read the code you'll why I think so. This happens when the limits of the map are reached, i.e. (iwidth || jheight). This is the code: Map.cpp (this render) Tile const * Map::getTyle(int i, int j) const { if (i >= 0 && j >= 0 && i < width && j < height) { return data[i][j]; } else { return &Tile::ERROR_TYLE; // This makes SDL_BlitSurface (called later) crash //return new Tile(TileType::ERROR); // This works with not problem (but is memory leak, of course) } } void Map::render(int x, int y, int width, int height) const { //DEBUG("(Rendering...) x: "<<x<<", y: "<<y<<", width: "<<width<<", height: "<<height); int firstI = x / TileType::PIXEL_PER_TILE; int firstJ = y / TileType::PIXEL_PER_TILE; int lastI = (x+width) / TileType::PIXEL_PER_TILE; int lastJ = (y+height) / TileType::PIXEL_PER_TILE; // The previous integer division rounds down when dealing with positive values, but it rounds up // negative values. This is a fix for that (We need those values always rounded down) if (firstI < 0) { firstI--; } if (firstJ < 0) { firstJ--; } const int firstX = x; const int firstY = y; SDL_Rect srcRect; SDL_Rect dstRect; for (int i=firstI; i <= lastI; i++) { for (int j=firstJ; j <= lastJ; j++) { if (i*TileType::PIXEL_PER_TILE < x) { srcRect.x = x % TileType::PIXEL_PER_TILE; srcRect.w = TileType::PIXEL_PER_TILE - (x % TileType::PIXEL_PER_TILE); dstRect.x = i*TileType::PIXEL_PER_TILE + (x % TileType::PIXEL_PER_TILE) - firstX; } else if (i*TileType::PIXEL_PER_TILE >= x + width) { srcRect.x = 0; srcRect.w = x % TileType::PIXEL_PER_TILE; dstRect.x = i*TileType::PIXEL_PER_TILE - firstX; } else { srcRect.x = 0; srcRect.w = TileType::PIXEL_PER_TILE; dstRect.x = i*TileType::PIXEL_PER_TILE - firstX; } if (j*TileType::PIXEL_PER_TILE < y) { srcRect.y = 0; srcRect.h = TileType::PIXEL_PER_TILE - (y % TileType::PIXEL_PER_TILE); dstRect.y = j*TileType::PIXEL_PER_TILE + (y % TileType::PIXEL_PER_TILE) - firstY; } else if (j*TileType::PIXEL_PER_TILE >= y + height) { srcRect.y = y % TileType::PIXEL_PER_TILE; srcRect.h = y % TileType::PIXEL_PER_TILE; dstRect.y = j*TileType::PIXEL_PER_TILE - firstY; } else { srcRect.y = 0; srcRect.h = TileType::PIXEL_PER_TILE; dstRect.y = j*TileType::PIXEL_PER_TILE - firstY; } SDL::YtoSDL(dstRect.y, srcRect.h); SDL_BlitSurface(getTyle(i,j)->getType()->getSurface(), &srcRect, SDL::getScreen(), &dstRect); // <-- Crash HERE /*DEBUG("i = "<<i<<", j = "<<j); DEBUG("srcRect.x = "<<srcRect.x<<", srcRect.y = "<<srcRect.y<<", srcRect.w = "<<srcRect.w<<", srcRect.h = "<<srcRect.h); DEBUG("dstRect.x = "<<dstRect.x<<", dstRect.y = "<<dstRect.y);*/ } } } Tile.h #ifndef TILE_H #define TILE_H #include "TileType.h" class Tile { private: TileType const * type; public: static const Tile ERROR_TYLE; Tile(TileType const * t); ~Tile(); TileType const * getType() const; }; #endif Tile.cpp #include "Tile.h" const Tile Tile::ERROR_TYLE(TileType::ERROR); Tile::Tile(TileType const * t) : type(t) {} Tile::~Tile() {} TileType const * Tile::getType() const { return type; } TileType.h #ifndef TILETYPE_H #define TILETYPE_H #include "SDL.h" #include "DEBUG.h" class TileType { protected: TileType(); ~TileType(); public: static const int PIXEL_PER_TILE = 30; static const TileType * ERROR; static const TileType * AIR; static const TileType * SOLID; virtual SDL_Surface * getSurface() const = 0; virtual bool isSolid(int x, int y) const = 0; }; #endif ErrorTyle.h #ifndef ERRORTILE_H #define ERRORTILE_H #include "TileType.h" class ErrorTile : public TileType { friend class TileType; private: ErrorTile(); mutable SDL_Surface * surface; static const char * FILE_PATH; public: SDL_Surface * getSurface() const; bool isSolid(int x, int y) const ; }; #endif ErrorTyle.cpp (The surface can't be loaded when building the object, because it is a static object and SDL_Init() needs to be called first) #include "ErrorTile.h" const char * ErrorTile::FILE_PATH = ("C:\\error.bmp"); ErrorTile::ErrorTile() : TileType(), surface(NULL) {} SDL_Surface * ErrorTile::getSurface() const { if (surface == NULL) { if (SDL::isOn()) { surface = SDL::loadAndOptimice(ErrorTile::FILE_PATH); if (surface->w != TileType::PIXEL_PER_TILE || surface->h != TileType::PIXEL_PER_TILE) { WARNING("Bad tile surface size"); } } else { ERROR("Trying to load a surface, but SDL is not on"); } } if (surface == NULL) { // This if doesn't get called, so surface != NULL ERROR("WTF? Can't load surface :\\"); } return surface; } bool ErrorTile::isSolid(int x, int y) const { return true; }

    Read the article

  • How to solve a deallocated connection in iPhone SDK 3.1.3? - Streams - CFSockets

    - by Christian
    Hi everyone, Debugging my implementation I found a memory leak issue. I know where is the issue, I tried to solve it but sadly without success. I will try to explain you, maybe someone of you can help with this. First I have two classes involved in the issue, the publish class (where publishing the service and socket configuration is done) and the connection (where the socket binding and the streams configuration is done). The main issue is in the connection via native socket. In the 'publish' class the "server" accepts a connection with a callback. The callback has the native-socket information. Then, a connection with native-socket information is created. Next, the socket binding and the streams configuration is done. When those actions are successful the instance of the connection is saved in a mutable array. Thus, the connection is established. static void AcceptCallback(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info) { Publish *rePoint = (Publish *)info; if ( type != kCFSocketAcceptCallBack) { return; } CFSocketNativeHandle nativeSocketHandle = *((CFSocketNativeHandle *)data); NSLog(@"The AcceptCallback was called, a connection request arrived to the server"); [rePoint handleNewNativeSocket:nativeSocketHandle]; } - (void)handleNewNativeSocket:(CFSocketNativeHandle)nativeSocketHandle{ Connection *connection = [[[Connection alloc] initWithNativeSocketHandle:nativeSocketHandle] autorelease]; // Create the connection if (connection == nil) { close(nativeSocketHandle); return; } NSLog(@"The connection from the server was created now try to connect"); if ( ! [connection connect]) { [connection close]; return; } [clients addObject:connection]; //save the connection trying to avoid the deallocation } The next step is receive the information from the client, thus a read-stream callback is triggered with the information of the established connection. But when the callback-handler tries to use this connection the error occurs, it says that such connection is deallocated. The issue here is that I don't know where/when the connection is deallocated and how to know it. I am using the debugger, but after some trials, I don't see more info. void myReadStreamCallBack (CFReadStreamRef stream, CFStreamEventType eventType, void *info) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; Connection *handlerEv = [[(Connection *)info retain] autorelease]; // The error -[Connection retain]: message sent to deallocated instance 0x1f5ef0 (Where 0x1f5ef0 is the reference to the established connection) [handlerEv readStreamHandleEvent:stream andEvent:eventType]; [pool drain]; } void myWriteStreamCallBack (CFWriteStreamRef stream, CFStreamEventType eventType, void *info){ NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init]; Connection *handlerEv = [[(Connection *)info retain] autorelease]; //Sometimes the error also happens here, I tried without the pool, but it doesn't help neither. [handlerEv writeStreamHandleEvent:eventType]; [p drain]; } Something strange is that when I run the debugger(with breakpoints) everything goes well, the connection is not deallocated and the callbacks work fine and the server is able to receive the message. I will appreciate any hint!

    Read the article

  • Fluent NHibernate - subclasses with shared reference

    - by ollie
    Edit: changed class names. I'm using Fluent NHibernate (v 1.0.0.614) automapping on the following set of classes (where Entity is the base class provided in the S#arp Architecture framework): public class Car : Entity { public virtual int ModelYear { get; set; } public virtual Company Manufacturer { get; set; } } public class Sedan : Car { public virtual bool WonSedanOfYear { get; set; } } public class Company : Entity { public virtual IList<Sedan> Sedans { get; set; } } This results in the following Configuration (as written to hbm.xml): <class name="Company" table="Companies"> <id name="Id" type="System.Int32" unsaved-value="0"> <column name="`ID`" /> <generator class="identity" /> </id> <bag cascade="all" inverse="true" name="Sedans" mutable="true"> <key> <column name="`CompanyID`" /> </key> <one-to-many class="Sedan" /> </bag> </class> <class name="Car" table="Cars"> <id name="Id" type="System.Int32" unsaved-value="0"> <column name="`ID`" /> <generator class="identity" /> </id> <property name="ModelYear" type="System.Int32"> <column name="`ModelYear`" /> </property> <many-to-one cascade="save-update" class="Company" name="Manufacturer"> <column name="`CompanyID`" /> </many-to-one> <joined-subclass name="Sedan"> <key> <column name="`CarID`" /> </key> <property name="WonSedanOfYear" type="System.Boolean"> <column name="`WonSedanOfYear`" /> </property> </joined-subclass> </class> So far so good! But now comes the ugly part. The generated database tables: Table: Companies Columns: ID (PK, int, not null) Table: Cars Columns: ID (PK, int, not null) ModelYear (int, null) CompanyID (FK, int, null) Table: Sedan Columns: CarID (PK, FK, int, not null) WonSedanOfYear (bit, null) CompanyID (FK, int, null) Instead of one FK for Company, I get two! How can I ensure I only get one FK for Company? Override the automapping? Put a convention in place? Or is this a bug? Your thoughts are appreciated.

    Read the article

  • Const references when dereferencing iterator on set, starting from Visual Studio 2010

    - by Patrick
    Starting from Visual Studio 2010, iterating over a set seems to return an iterator that dereferences the data as 'const data' instead of non-const. The following code is an example of something that does compile on Visual Studio 2005, but not on 2010 (this is an artificial example, but clearly illustrates the problem we found on our own code). In this example, I have a class that stores a position together with a temperature. I define comparison operators (not all them, just enough to illustrate the problem) that only use the position, not the temperature. The point is that for me two instances are identical if the position is identical; I don't care about the temperature. #include <set> class DataPoint { public: DataPoint (int x, int y) : m_x(x), m_y(y), m_temperature(0) {} void setTemperature(double t) {m_temperature = t;} bool operator<(const DataPoint& rhs) const { if (m_x==rhs.m_x) return m_y<rhs.m_y; else return m_x<rhs.m_x; } bool operator==(const DataPoint& rhs) const { if (m_x!=rhs.m_x) return false; if (m_y!=rhs.m_y) return false; return true; } private: int m_x; int m_y; double m_temperature; }; typedef std::set<DataPoint> DataPointCollection; void main(void) { DataPointCollection points; points.insert (DataPoint(1,1)); points.insert (DataPoint(1,1)); points.insert (DataPoint(1,2)); points.insert (DataPoint(1,3)); points.insert (DataPoint(1,1)); for (DataPointCollection::iterator it=points.begin();it!=points.end();++it) { DataPoint &point = *it; point.setTemperature(10); } } In the main routine I have a set to which I add some points. To check the correctness of the comparison operator, I add data points with the same position multiple times. When writing the contents of the set, I can clearly see there are only 3 points in the set. The for-loop loops over the set, and sets the temperature. Logically this is allowed, since the temperature is not used in the comparison operators. This code compiles correctly in Visual Studio 2005, but gives compilation errors in Visual Studio 2010 on the following line (in the for-loop): DataPoint &point = *it; The error given is that it can't assign a "const DataPoint" to a [non-const] "DataPoint &". It seems that you have no decent (= non-dirty) way of writing this code in VS2010 if you have a comparison operator that only compares parts of the data members. Possible solutions are: Adding a const-cast to the line where it gives an error Making temperature mutable and making setTemperature a const method But to me both solutions seem rather 'dirty'. It looks like the C++ standards committee overlooked this situation. Or not? What are clean solutions to solve this problem? Did some of you encounter this same problem and how did you solve it? Patrick

    Read the article

  • Why might a System.String object not cache its hash code?

    - by Dan Tao
    A glance at the source code for string.GetHashCode using Reflector reveals the following (for mscorlib.dll version 4.0): public override unsafe int GetHashCode() { fixed (char* str = ((char*) this)) { char* chPtr = str; int num = 0x15051505; int num2 = num; int* numPtr = (int*) chPtr; for (int i = this.Length; i > 0; i -= 4) { num = (((num << 5) + num) + (num >> 0x1b)) ^ numPtr[0]; if (i <= 2) { break; } num2 = (((num2 << 5) + num2) + (num2 >> 0x1b)) ^ numPtr[1]; numPtr += 2; } return (num + (num2 * 0x5d588b65)); } } Now, I realize that the implementation of GetHashCode is not specified and is implementation-dependent, so the question "is GetHashCode implemented in the form of X or Y?" is not really answerable. I'm just curious about a few things: If Reflector has disassembled the DLL correctly and this is the implementation of GetHashCode (in my environment), am I correct in interpreting this code to indicate that a string object, based on this particular implementation, would not cache its hash code? Assuming the answer is yes, why would this be? It seems to me that the memory cost would be minimal (one more 32-bit integer, a drop in the pond compared to the size of the string itself) whereas the savings would be significant, especially in cases where, e.g., strings are used as keys in a hashtable-based collection like a Dictionary<string, [...]>. And since the string class is immutable, it isn't like the value returned by GetHashCode will ever even change. What could I be missing? UPDATE: In response to Andras Zoltan's closing remark: There's also the point made in Tim's answer(+1 there). If he's right, and I think he is, then there's no guarantee that a string is actually immutable after construction, therefore to cache the result would be wrong. Whoa, whoa there! This is an interesting point to make (and yes it's very true), but I really doubt that this was taken into consideration in the implementation of GetHashCode. The statement "therefore to cache the result would be wrong" implies to me that the framework's attitude regarding strings is "Well, they're supposed to be immutable, but really if developers want to get sneaky they're mutable so we'll treat them as such." This is definitely not how the framework views strings. It fully relies on their immutability in so many ways (interning of string literals, assignment of all zero-length strings to string.Empty, etc.) that, basically, if you mutate a string, you're writing code whose behavior is entirely undefined and unpredictable. I guess my point is that for the author(s) of this implementation to worry, "What if this string instance is modified between calls, even though the class as it is publicly exposed is immutable?" would be like for someone planning a casual outdoor BBQ to think to him-/herself, "What if someone brings an atomic bomb to the party?" Look, if someone brings an atom bomb, party's over.

    Read the article

  • No improvement in speed when using Ehcache with Hibernate

    - by paddydub
    I'm getting no improvement in speed when using Ehcache with Hibernate Here are the results I get when i run the test below. The test is reading 80 Stop objects and then the same 80 Stop objects again using the cache. On the second read it is hitting the cache, but there is no improvement in speed. Any idea's on what I'm doing wrong? Speed Test: First Read: Reading stops 1-80 : 288ms Second Read: Reading stops 1-80 : 275ms Cache Info: elementsInMemory: 79 elementsInMemoryStore: 79 elementsInDiskStore: 0 JunitCacheTest public class JunitCacheTest extends TestCase { static Cache stopCache; public void testCache() { ApplicationContext context = new ClassPathXmlApplicationContext("beans-hibernate.xml"); StopDao stopDao = (StopDao) context.getBean("stopDao"); CacheManager manager = new CacheManager(); stopCache = (Cache) manager.getCache("ie.dataStructure.Stop.Stop"); //First Read for (int i=1; i<80;i++) { Stop toStop = stopDao.findById(i); } //Second Read for (int i=1; i<80;i++) { Stop toStop = stopDao.findById(i); } System.out.println("elementsInMemory " + stopCache.getSize()); System.out.println("elementsInMemoryStore " + stopCache.getMemoryStoreSize()); System.out.println("elementsInDiskStore " + stopCache.getDiskStoreSize()); } public static Cache getStopCache() { return stopCache; } } HibernateStopDao @Repository("stopDao") public class HibernateStopDao implements StopDao { private SessionFactory sessionFactory; @Transactional(readOnly = true) public Stop findById(int stopId) { Cache stopCache = JunitCacheTest.getStopCache(); Element cacheResult = stopCache.get(stopId); if (cacheResult != null){ return (Stop) cacheResult.getValue(); } else{ Stop result =(Stop) sessionFactory.getCurrentSession().get(Stop.class, stopId); Element element = new Element(result.getStopID(),result); stopCache.put(element); return result; } } } ehcache.xml <cache name="ie.dataStructure.Stop.Stop" maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="5200" timeToLiveSeconds="5200" overflowToDisk="true"> </cache> stop.hbm.xml <class name="ie.dataStructure.Stop.Stop" table="stops" catalog="hibernate3" mutable="false" > <cache usage="read-only"/> <comment></comment> <id name="stopID" type="int"> <column name="STOPID" /> <generator class="assigned" /> </id> <property name="coordinateID" type="int"> <column name="COORDINATEID" not-null="true"> <comment></comment> </column> </property> <property name="routeID" type="int"> <column name="ROUTEID" not-null="true"> <comment></comment> </column> </property> </class> Stop public class Stop implements Comparable<Stop>, Serializable { private static final long serialVersionUID = 7823769092342311103L; private Integer stopID; private int routeID; private int coordinateID; }

    Read the article

  • Converting OCaml to F#: F# equivelent of Pervasives at_exit

    - by Guy Coder
    I am converting the OCaml Format module to F# and tracked a problem back to a use of the OCaml Pervasives at_exit. val at_exit : (unit -> unit) -> unit Register the given function to be called at program termination time. The functions registered with at_exit will be called when the program executes exit, or terminates, either normally or because of an uncaught exception. The functions are called in "last in, first out" order: the function most recently added with at_exit is called first. In the process of conversion I commented out the line as the compiler did not flag it as being needed and I was not expecting an event in the code. I checked the FSharp.PowerPack.Compatibility.PervasivesModule for at_exit using VS Object Browser and found none. I did find how to run code "at_exit"? and How do I write an exit handler for an F# application? The OCaml line is at_exit print_flush with print_flush signature: val print_flush : (unit -> unit) Also in looking at the use of it during a debug session of the OCaml code, it looks like at_exit is called both at the end of initialization and at the end of each use of a call to the module. Any suggestions, hints on how to do this. This will be my first event in F#. EDIT Here is some of what I have learned about the Format module that should shed some light on the problem. The Format module is a library of functions for basic pretty printer commands of simple OCaml values such as int, bool, string. The format module has commands like print_string, but also some commands to say put the next line in a bounded box, think new set of left and right margins. So one could write: print_string "Hello" or open_box 0; print_string "<<"; open_box 0; print_string "p \/ q ==> r"; close_box(); print_string ">>"; close_box() The commands such as open_box and print_string are handled by a loop that interprets the commands and then decides wither to print on the current line or advance to the next line. The commands are held in a queue and there is a state record to hold mutable values such as left and right margin. The queue and state needs to be primed, which from debugging the test cases against working OCaml code appears to be done at the end of initialization of the module but before the first call is made to any function in the Format module. The queue and state is cleaned up and primed again for the next set of commands by the use of mechanisms for at_exit that recognize that the last matching frame for the initial call to the format modules has been removed thus triggering the call to at_exit which pushes out any remaining command in the queue and re-initializes the queue and state. So the sequencing of the calls to print_flush is critical and appears to be at more than what the OCaml documentation states.

    Read the article

  • Override `drop` for a custom sequence

    - by Bruno Reis
    In short: in Clojure, is there a way to redefine a function from the standard sequence API (which is not defined on any interface like ISeq, IndexedSeq, etc) on a custom sequence type I wrote? 1. Huge data files I have big files in the following format: A long (8 bytes) containing the number n of entries n entries, each one being composed of 3 longs (ie, 24 bytes) 2. Custom sequence I want to have a sequence on these entries. Since I cannot usually hold all the data in memory at once, and I want fast sequential access on it, I wrote a class similar to the following: (deftype DataSeq [id ^long cnt ^long i cached-seq] clojure.lang.IndexedSeq (index [_] i) (count [_] (- cnt i)) (seq [this] this) (first [_] (first cached-seq)) (more [this] (if-let [s (next this)] s '())) (next [_] (if (not= (inc i) cnt) (if (next cached-seq) (DataSeq. id cnt (inc i) (next cached-seq)) (DataSeq. id cnt (inc i) (with-open [f (open-data-file id)] ; open a memory mapped byte array on the file ; seek to the exact position to begin reading ; decide on an optimal amount of data to read ; eagerly read and return that amount of data )))))) The main idea is to read ahead a bunch of entries in a list and then consume from that list. Whenever the cache is completely consumed, if there are remaining entries, they are read from the file in a new cache list. Simple as that. To create an instance of such a sequence, I use a very simple function like: (defn ^DataSeq load-data [id] (next (DataSeq. id (count-entries id) -1 []))) ; count-entries is a trivial "open file and read a long" memoized As you can see, the format of the data allowed me to implement count in very simply and efficiently. 3. drop could be O(1) In the same spirit, I'd like to reimplement drop. The format of these data files allows me to reimplement drop in O(1) (instead of the standard O(n)), as follows: if dropping less then the remaining cached items, just drop the same amount from the cache and done; if dropping more than cnt, then just return the empty list. otherwise, just figure out the position in the data file, jump right into that position, and read data from there. My difficulty is that drop is not implemented in the same way as count, first, seq, etc. The latter functions call a similarly named static method in RT which, in turn, calls my implementation above, while the former, drop, does not check if the instance of the sequence it is being called on provides a custom implementation. Obviously, I could provide a function named anything but drop that does exactly what I want, but that would force other people (including my future self) to remember to use it instead of drop every single time, which sucks. So, the question is: is it possible to override the default behaviour of drop? 4. A workaround (I dislike) While writing this question, I've just figured out a possible workaround: make the reading even lazier. The custom sequence would just keep an index and postpone the reading operation, that would happen only when first was called. The problem is that I'd need some mutable state: the first call to first would cause some data to be read into a cache, all the subsequent calls would return data from this cache. There would be a similar logic on next: if there's a cache, just next it; otherwise, don't bother populating it -- it will be done when first is called again. This would avoid unnecessary disk reads. However, this is still less than optimal -- it is still O(n), and it could easily be O(1). Anyways, I don't like this workaround, and my question is still open. Any thoughts? Thanks.

    Read the article

  • Lightning talk: Coderetreat

    - by Michael Williamson
    In the spirit of trying to encourage more deliberate practice amongst coders in Red Gate, Lauri Pesonen had the idea of running a coderetreat in Red Gate. Lauri and I ran the first one a few weeks ago: given that neither of us hadn’t even been to a coderetreat before, let alone run one, I think it turned out quite well. The participants gave positive feedback, saying that they enjoyed the day, wrote some thought-provoking code and would do it again. Sam Blackburn was one of the attendees, and gave a lightning talk to the other developers in one of our regular lightning talk sessions: In case you can’t watch the video, I’ve transcribed the talk below, although I’d recommend watching the video if you can — I didn’t have much time to do the transcribing! So, what is a coderetreat? So it’s not just something in Red Gate, there’s a website and everything, although it’s not a very big website. It calls itself a community network. The basic ideas behind coderetreat are: you’ve got one day, and you split it into one hour sections. You spend three quarters of that coding, and do a little retrospective at the end. You’re supposed to start fresh each, we were told to delete our code after every session. We were in pairs, swapping after each session, and we did the same task every time. In fact, Conway’s Game of Life is the only task mentioned anywhere that I find for coderetreat. So I don’t know what we’ll do next time, or if we’re meant to do the same thing again. There are some guiding principles which felt to us like restrictions, that you have to code in crazy ways to encourage better code. Final thing is that it’s supposed to be free for outsiders to join. It’s meant to be a kind of networking thing, where you link up with people from other companies. We had a pilot day with Michael and Lauri. Since it was basically the first time any of us had done anything like this, everybody was from Red Gate. We didn’t chat to anybody else for the initial one. The task was Conway’s Game of Life, which most of you have probably heard of it, all but one of us knew about it when did the coderetreat. I won’t got into the details of what it is, but it felt like the right size of task, basically one or two groups actually produced something working by the end of the day, and of course that doesn’t mean it’s necessarily a day’s work to produce that because we were starting again every hour. The task really drives you more than trying to create good code, I found. It was really tempting to try and get it working rather than stick to the rules. But it’s really good to stop and try again because there are so many what-ifs when you’ve finished writing something, “what if I’d done it this way?”. You can answer all those questions at a coderetreat because it’s not about getting a product out the door, it’s about learning and playing with ideas. So we had all these different practices we were trying. I’ll try and go through most of these. Single responsibility is this idea that everything should do just one thing. It was the very first session, we were still trying to figure out how do you go about the Game of Life? So by the end of forty-five minutes hadn’t produced very much for that first session. We were still thinking, “Do we start with a board, how do we represent all these squares? It can be infinitely big, help, this is getting really difficult!”. So, most of us didn’t really get anywhere on the first one. Although it was interesting that some people started with the board, one group started with the FateDecider class that decides whether things live or die. A sort of god class, but in a good way. They managed to implement all of the rules without even defining how the squares were arranged or anything like that. Another thing we tried was TDD (test-driven development). I’m sure most of you know what TDD is: Watch a test, watch it fail for the right reason Write code to pass the test, watch it pass Refactor, check the test still passes Repeat! It basically worked, we were able to produce code, but we often found the tests defined the direction that code went, which is obviously the idea of TDD. But you tend to find that by the time you’ve even written your first assertion, which is supposed to be the very first thing you write, because you write your tests backwards from the assertions back to the initial conditions, you’ve already constrained the logic of the code in some way by the time you’ve done that. You then get to this situation of, “Well, we actually want to go in a slightly different direction. Can we do this?”. Can we write tests that don’t constrain the architecture? Wrapping up all primitives: it’s kind of turtles all the way down. We had a Size, which has a Width and Height, which both derive from Dimension. You’ve got pages of code before you’ve even done anything. No getters and setters (use tell don’t ask instead): mocks and stubs for tests are required if you want to assert that your results are what you think they should be. You can’t just check the internal state of the code. And people found that really challenging and it made them think in a different way which I think is really good. Not having mutable state: that was kind of confusing because we weren’t quite sure what fitted within that rule and what didn’t, and I think we were trying too hard to follow the rule rather than the guideline. No if-statements: supposed to use polymorphism instead, but polymorphism still requires a factory with conditional behaviour. We did something really crazy to get around this: public T If(bool condition, Func<T> left, Func<T> right) { var dict = new Dictionary<bool, Func<T>> {{true, left}, {false, right}}; return dict[condition].Invoke(); } That is not really polymorphism, is it? For-loops: you can always replace a for-loop with recursion, but it doesn’t tend to make it any more readable unless it’s the kind of task that really lends itself to that. So it was interesting, it was good practice, but it wouldn’t make it easier it’s the kind of tree-structure algorithm where that would help. Having a limit on the number of levels of indentation: again, I think it does produce very nice, clean code, but it wasn’t actually a challenge because you just extract methods. That’s quite a useful thing because you can apply that to real code and say, “Okay, should this method really be going crazy like this?” No talking: we hated that. It’s like there’s two of you at a computer, and one of you is doing the typing, what does the other guy do if they’re not allowed to talk. The answer is TDD ping-pong – one person writes the tests, and then the other person writes the code to pass the test. And that creates communication without actually having to have discussion about things which is kind of cool. No code comments: just makes no difference to anything. It’s a forty-five minute exercise, so what are you going to put comments in code for? Finally, this is my fault. I discovered an entertaining way of doing the calculation that was kind of cool (using convolutions over the state of the board). Unfortunately, it turns out to be really hard to implement in C#, so didn’t even manage to work out how to do that convolution in C#. It’s trivial in some high-level languages, but you need something matrix-orientated for it to really work. That’s most of it, really. The thoughts that people went away with: we put down our answers to questions like “What have you learnt?” and “What surprised you?”, “How are you going to do things differently?”, and most people said redoing the problem is really, really good for understanding it properly. People hate having a massive legacy codebase that they can’t change, so being able to attack something three different ways in an environment where the end-product isn’t important: that’s something people really enjoyed. Pair-programming: also people said that they wanted to do more of that, especially with TDD ping-pong, where you write the test and somebody else writes the code. Various people thought different things about immutables, but most people thought they were good, they promote functional programming. And TDD people found really hard. “Tell, don’t ask” people found really, really hard and really, really, really hard to do well. And the recursion just made things trickier to debug. But most people agreed that coderetreats are really cool, and we should do more of them.

    Read the article

  • C#/.NET Little Wonders: The Joy of Anonymous Types

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. In the .NET 3 Framework, Microsoft introduced the concept of anonymous types, which provide a way to create a quick, compiler-generated types at the point of instantiation.  These may seem trivial, but are very handy for concisely creating lightweight, strongly-typed objects containing only read-only properties that can be used within a given scope. Creating an Anonymous Type In short, an anonymous type is a reference type that derives directly from object and is defined by its set of properties base on their names, number, types, and order given at initialization.  In addition to just holding these properties, it is also given appropriate overridden implementations for Equals() and GetHashCode() that take into account all of the properties to correctly perform property comparisons and hashing.  Also overridden is an implementation of ToString() which makes it easy to display the contents of an anonymous type instance in a fairly concise manner. To construct an anonymous type instance, you use basically the same initialization syntax as with a regular type.  So, for example, if we wanted to create an anonymous type to represent a particular point, we could do this: 1: var point = new { X = 13, Y = 7 }; Note the similarity between anonymous type initialization and regular initialization.  The main difference is that the compiler generates the type name and the properties (as readonly) based on the names and order provided, and inferring their types from the expressions they are assigned to. It is key to remember that all of those factors (number, names, types, order of properties) determine the anonymous type.  This is important, because while these two instances share the same anonymous type: 1: // same names, types, and order 2: var point1 = new { X = 13, Y = 7 }; 3: var point2 = new { X = 5, Y = 0 }; These similar ones do not: 1: var point3 = new { Y = 3, X = 5 }; // different order 2: var point4 = new { X = 3, Y = 5.0 }; // different type for Y 3: var point5 = new {MyX = 3, MyY = 5 }; // different names 4: var point6 = new { X = 1, Y = 2, Z = 3 }; // different count Limitations on Property Initialization Expressions The expression for a property in an anonymous type initialization cannot be null (though it can evaluate to null) or an anonymous function.  For example, the following are illegal: 1: // Null can't be used directly. Null reference of what type? 2: var cantUseNull = new { Value = null }; 3:  4: // Anonymous methods cannot be used. 5: var cantUseAnonymousFxn = new { Value = () => Console.WriteLine(“Can’t.”) }; Note that the restriction on null is just that you can’t use it directly as the expression, because otherwise how would it be able to determine the type?  You can, however, use it indirectly assigning a null expression such as a typed variable with the value null, or by casting null to a specific type: 1: string str = null; 2: var fineIndirectly = new { Value = str }; 3: var fineCast = new { Value = (string)null }; All of the examples above name the properties explicitly, but you can also implicitly name properties if they are being set from a property, field, or variable.  In these cases, when a field, property, or variable is used alone, and you don’t specify a property name assigned to it, the new property will have the same name.  For example: 1: int variable = 42; 2:  3: // creates two properties named varriable and Now 4: var implicitProperties = new { variable, DateTime.Now }; Is the same type as: 1: var explicitProperties = new { variable = variable, Now = DateTime.Now }; But this only works if you are using an existing field, variable, or property directly as the expression.  If you use a more complex expression then the name cannot be inferred: 1: // can't infer the name variable from variable * 2, must name explicitly 2: var wontWork = new { variable * 2, DateTime.Now }; In the example above, since we typed variable * 2, it is no longer just a variable and thus we would have to assign the property a name explicitly. ToString() on Anonymous Types One of the more trivial overrides that an anonymous type provides you is a ToString() method that prints the value of the anonymous type instance in much the same format as it was initialized (except actual values instead of expressions as appropriate of course). For example, if you had: 1: var point = new { X = 13, Y = 42 }; And then print it out: 1: Console.WriteLine(point.ToString()); You will get: 1: { X = 13, Y = 42 } While this isn’t necessarily the most stunning feature of anonymous types, it can be handy for debugging or logging values in a fairly easy to read format. Comparing Anonymous Type Instances Because anonymous types automatically create appropriate overrides of Equals() and GetHashCode() based on the underlying properties, we can reliably compare two instances or get hash codes.  For example, if we had the following 3 points: 1: var point1 = new { X = 1, Y = 2 }; 2: var point2 = new { X = 1, Y = 2 }; 3: var point3 = new { Y = 2, X = 1 }; If we compare point1 and point2 we’ll see that Equals() returns true because they overridden version of Equals() sees that the types are the same (same number, names, types, and order of properties) and that the values are the same.   In addition, because all equal objects should have the same hash code, we’ll see that the hash codes evaluate to the same as well: 1: // true, same type, same values 2: Console.WriteLine(point1.Equals(point2)); 3:  4: // true, equal anonymous type instances always have same hash code 5: Console.WriteLine(point1.GetHashCode() == point2.GetHashCode()); However, if we compare point2 and point3 we get false.  Even though the names, types, and values of the properties are the same, the order is not, thus they are two different types and cannot be compared (and thus return false).  And, since they are not equal objects (even though they have the same value) there is a good chance their hash codes are different as well (though not guaranteed): 1: // false, different types 2: Console.WriteLine(point2.Equals(point3)); 3:  4: // quite possibly false (was false on my machine) 5: Console.WriteLine(point2.GetHashCode() == point3.GetHashCode()); Using Anonymous Types Now that we’ve created instances of anonymous types, let’s actually use them.  The property names (whether implicit or explicit) are used to access the individual properties of the anonymous type.  The main thing, once again, to keep in mind is that the properties are readonly, so you cannot assign the properties a new value (note: this does not mean that instances referred to by a property are immutable – for more information check out C#/.NET Fundamentals: Returning Data Immutably in a Mutable World). Thus, if we have the following anonymous type instance: 1: var point = new { X = 13, Y = 42 }; We can get the properties as you’d expect: 1: Console.WriteLine(“The point is: ({0},{1})”, point.X, point.Y); But we cannot alter the property values: 1: // compiler error, properties are readonly 2: point.X = 99; Further, since the anonymous type name is only known by the compiler, there is no easy way to pass anonymous type instances outside of a given scope.  The only real choices are to pass them as object or dynamic.  But really that is not the intention of using anonymous types.  If you find yourself needing to pass an anonymous type outside of a given scope, you should really consider making a POCO (Plain Old CLR Type – i.e. a class that contains just properties to hold data with little/no business logic) instead. Given that, why use them at all?  Couldn’t you always just create a POCO to represent every anonymous type you needed?  Sure you could, but then you might litter your solution with many small POCO classes that have very localized uses. It turns out this is the key to when to use anonymous types to your advantage: when you just need a lightweight type in a local context to store intermediate results, consider an anonymous type – but when that result is more long-lived and used outside of the current scope, consider a POCO instead. So what do we mean by intermediate results in a local context?  Well, a classic example would be filtering down results from a LINQ expression.  For example, let’s say we had a List<Transaction>, where Transaction is defined something like: 1: public class Transaction 2: { 3: public string UserId { get; set; } 4: public DateTime At { get; set; } 5: public decimal Amount { get; set; } 6: // … 7: } And let’s say we had this data in our List<Transaction>: 1: var transactions = new List<Transaction> 2: { 3: new Transaction { UserId = "Jim", At = DateTime.Now, Amount = 2200.00m }, 4: new Transaction { UserId = "Jim", At = DateTime.Now, Amount = -1100.00m }, 5: new Transaction { UserId = "Jim", At = DateTime.Now.AddDays(-1), Amount = 900.00m }, 6: new Transaction { UserId = "John", At = DateTime.Now.AddDays(-2), Amount = 300.00m }, 7: new Transaction { UserId = "John", At = DateTime.Now, Amount = -10.00m }, 8: new Transaction { UserId = "Jane", At = DateTime.Now, Amount = 200.00m }, 9: new Transaction { UserId = "Jane", At = DateTime.Now, Amount = -50.00m }, 10: new Transaction { UserId = "Jaime", At = DateTime.Now.AddDays(-3), Amount = -100.00m }, 11: new Transaction { UserId = "Jaime", At = DateTime.Now.AddDays(-3), Amount = 300.00m }, 12: }; So let’s say we wanted to get the transactions for each day for each user.  That is, for each day we’d want to see the transactions each user performed.  We could do this very simply with a nice LINQ expression, without the need of creating any POCOs: 1: // group the transactions based on an anonymous type with properties UserId and Date: 2: byUserAndDay = transactions 3: .GroupBy(tx => new { tx.UserId, tx.At.Date }) 4: .OrderBy(grp => grp.Key.Date) 5: .ThenBy(grp => grp.Key.UserId); Now, those of you who have attempted to use custom classes as a grouping type before (such as GroupBy(), Distinct(), etc.) may have discovered the hard way that LINQ gets a lot of its speed by utilizing not on Equals(), but also GetHashCode() on the type you are grouping by.  Thus, when you use custom types for these purposes, you generally end up having to write custom Equals() and GetHashCode() implementations or you won’t get the results you were expecting (the default implementations of Equals() and GetHashCode() are reference equality and reference identity based respectively). As we said before, it turns out that anonymous types already do these critical overrides for you.  This makes them even more convenient to use!  Instead of creating a small POCO to handle this grouping, and then having to implement a custom Equals() and GetHashCode() every time, we can just take advantage of the fact that anonymous types automatically override these methods with appropriate implementations that take into account the values of all of the properties. Now, we can look at our results: 1: foreach (var group in byUserAndDay) 2: { 3: // the group’s Key is an instance of our anonymous type 4: Console.WriteLine("{0} on {1:MM/dd/yyyy} did:", group.Key.UserId, group.Key.Date); 5:  6: // each grouping contains a sequence of the items. 7: foreach (var tx in group) 8: { 9: Console.WriteLine("\t{0}", tx.Amount); 10: } 11: } And see: 1: Jaime on 06/18/2012 did: 2: -100.00 3: 300.00 4:  5: John on 06/19/2012 did: 6: 300.00 7:  8: Jim on 06/20/2012 did: 9: 900.00 10:  11: Jane on 06/21/2012 did: 12: 200.00 13: -50.00 14:  15: Jim on 06/21/2012 did: 16: 2200.00 17: -1100.00 18:  19: John on 06/21/2012 did: 20: -10.00 Again, sure we could have just built a POCO to do this, given it an appropriate Equals() and GetHashCode() method, but that would have bloated our code with so many extra lines and been more difficult to maintain if the properties change.  Summary Anonymous types are one of those Little Wonders of the .NET language that are perfect at exactly that time when you need a temporary type to hold a set of properties together for an intermediate result.  While they are not very useful beyond the scope in which they are defined, they are excellent in LINQ expressions as a way to create and us intermediary values for further expressions and analysis. Anonymous types are defined by the compiler based on the number, type, names, and order of properties created, and they automatically implement appropriate Equals() and GetHashCode() overrides (as well as ToString()) which makes them ideal for LINQ expressions where you need to create a set of properties to group, evaluate, etc. Technorati Tags: C#,CSharp,.NET,Little Wonders,Anonymous Types,LINQ

    Read the article

  • CodePlex Daily Summary for Sunday, July 08, 2012

    CodePlex Daily Summary for Sunday, July 08, 2012Popular ReleasesBlackJumboDog: Ver5.6.7: 2012.07.08 Ver5.6.7 (1) ????????????????「????? Request.Receve()」?????????? (2) Web???????????FlMML customized: FlMML customized ??: FlMML customized ????。 ??、PCM??????????、??????。ecBlog: ecBlog 0.2: ecBlog alpha realaseTaskScheduler ASP.NET: Release 3 - 1.2.0.0: Release 3 - Version 1.2.0.0 That version was altered only the library: In TaskScheduler was added new properties: UseBackgroundThreads Enables the use of separate threads for each task. StoreThreadsInPool Manager enables to store in the Pool threads that are performing the tasks. OnStopSchedulerAutoCancelThreads Scheduler allows aborting threads when it is stopped. false if the scheduler is not aborted the threads that are running. AutoDeletedExecutedTasks Allows Manager Delete Task afte...DotNetNuke Persian Packages: ??? ?? ???? ????? ???? 6.2.0: *????? ???? ??? ?? ???? 6.2.0 ? ??????? ???? ????? ???? ??? ????? *????? ????? ????? ??? ??? ???? ??? ??????? ??????? - ???? *?????? ???? ??? ?????? ?? ???? ???? ????? ? ?? ??? ?? ???? ???? ?? *????? ????? ????? ????? ????? / ??????? ???? ?? ???? ??? ??? - ???? *???? ???? ???? ????? ? ??????? ??? ??? ??? ?? ???? *????? ????? ???????? ??? ? ??????? ?? ?? ?????? ????? ????????? ????? ?????? - ???? *????? ????? ?????? ????? ?? ???? ?? ?? ?? ???????? ????? ????? ????????? ????? ?????? *???? ?...testtom07052012git02: r1: r1Cypher Bot: Cypher Bot 4.1: Cypher Bot is the most advanced encryption tool on the planet.... and now it actually works. That's right we fixed the bugs! For a full program summary go to the Home Page or visit www.iRareMedia.com So what's new? We've pretty much fixed all the bugs, but here's a run down if you wanna know exactly what's different: Fixed Installation / Setup Error, where an error message would display: "No Internet Connection, Try Again Later" Fixed File Encryption / Decryption error where the file exten...Coding4Fun Kinect Service: Coding4Fun Kinect Service v1.5: Requires Kinect for Windows SDK v1.5 Minor bug fixes + Kinect for Windows SDK v1.5 Aligning version with the Kinect for Windows SDK requiredtedplay: tedplay 1.1: tedplay 1.1 source and Win32 binary is out now. Changes are: SID card support Commodore 64 PSID music format support optimized FIR filter global hotkeys for skipping tracks (Windows only) module properties window (Windows only) mutable noise channel via GUI button (Windows only) disable SID card from the menu (Windows only) bugfixes PSID tunes are played on the C64 clock frequency but in a Commodore plus/4 virtual machine. The purpose is not to have yet another SID player, but t...xUnit.net Contrib: xunitcontrib-resharper 0.6 (RS 7.0, 6.1.1): xunitcontrib release 0.6 (ReSharper runner) This release provides a test runner plugin for Resharper 7.0 (EAP build 82) and 6.1, targetting all versions of xUnit.net. (See the xUnit.net project to download xUnit.net itself.) Copies of the plugin that support previous verions of ReSharper can be downloaded from this release. The plan is to support the latest revisions of the last two paid-for major versions of ReSharper (namely 7.0 and 6.1) Also note that all builds work against ALL VERSIONS...Umbraco CMS: Umbraco 4.8.0 Beta: Whats newuComponents in the core Multi-Node Tree Picker, Multiple Textstring, Slider and XPath Lists Easier Lucene searching built in IFile providers for easier file handling Updated 3rd party libraries Applications / Trees moved out of the database SQL Azure support added Various bug fixes Getting Started A great place to start is with our Getting Started Guide: Getting Started Guide: http://umbraco.codeplex.com/Project/Download/FileDownload.aspx?DownloadId=197051 Make sure to...CODE Framework: 4.0.20704.0: See CODE Framework (.NET) Change Log for changes in this version.xUnit.net - Unit testing framework for C# and .NET (a successor to NUnit): xUnit.net 1.9.1: xUnit.net release 1.9.1Build #1600 Important note for Resharper users: Resharper support has been moved to the xUnit.net Contrib project. Important note for TestDriven.net users: If you are having issues running xUnit.net tests in TestDriven.net, especially on 64-bit Windows, we strongly recommend you upgrade to TD.NET version 3.0 or later. Important note for VS2012 users: The VS2012 runner is in the Visual Studio Gallery now, and should be installed via Tools | Extension Manager from insi...MVC Controls Toolkit: Mvc Controls Toolkit 2.2.0: Added Modified all Mv4 related features to conform with the Mvc4 RC Now all items controls accept any IEnumerable<T>(before just List<T> were accepted by most of controls) retrievalManager class that retrieves automatically data from a data source whenever it catchs events triggered by filtering, sorting, and paging controls move method to the updatesManager to move one child objects from a father to another. The move operation can be undone like the insert, update and delete operatio...IronPython: 2.7.3: On behalf of the IronPython team, I'm happy to announce the final release of IronPython 2.7.3. This release includes everything from IronPython 54498, 62475, and 74478 as well. Like all IronPython 2.7-series releases, .NET 4 is required to install it. Installing this release will replace any existing IronPython 2.7-series installation. The incompatibility with IronRuby has been resolved, and they can once again be installed side-by-side. The biggest improvements in IronPython 2.7.3 are: the...Mini SQL Query: Mini SQL Query (v1.0.68.441): Just a bug fix release for when the connections try to refresh after an edit. Make sure you read the Quickstart for an introduction.Microsoft Ajax Minifier: Microsoft Ajax Minifier 4.58: Fix for Issue #18296: provide "ALL" value to the -ignore switch to ignore all error and warning messages. Fix for issue #18293: if encountering EOF before a function declaration or expression is properly closed, throw an appropriate error and don't crash. Adjust the variable-renaming algorithm so it's very specific when renaming variables with the same number of references so a single source file ends up with the same minified names on different platforms. add the ability to specify kno...LogExpert: 1.4 build 4566: This release for the 1.4 version line contains various fixes which have been made some times ago. Until now these fixes were only available in the 1.5 alpha versions. It also contains a fix for: 710. Column finder (press F8 to show) Terminal server issues: Multiple sessions with same user should work now Settings Export/Import available via Settings Dialog still incomple (e.g. tab colors are not saved) maybe I change the file format one day no command line support yet (for importin...CommonLibrary.NET: CommonLibrary.NET 0.9.8.5 - Final Release: A collection of very reusable code and components in C# 4.0 ranging from ActiveRecord, Csv, Command Line Parsing, Configuration, Holiday Calendars, Logging, Authentication, and much more. FluentscriptCommonLibrary.NET 0.9.8 contains a scripting language called FluentScript. Releases notes for FluentScript located at http://fluentscript.codeplex.com/wikipage?action=Edit&title=Release%20Notes&referringTitle=Documentation Fluentscript - 0.9.8.5 - Final ReleaseApplication: FluentScript Versio...SharePoint 2010 Metro UI: SharePoint 2010 Metro UI8: Please review the documentation link for how to install. Installation takes some basic knowledge of how to upload and edit SharePoint Artifact files. Please view the discussions tab for ongoing FAQsNew ProjectsAdventures of Adventure Land: Adventures of Adventure Land is a new text based adventure. You will be able to level up, fight challenging enemies, use magical spells, and simply adventure.AdventureWorks Silverlight samples: AdventureWorks Silverlight samplesAFS.Collab.Duplex: my duplexarmmychan: ????????C# - WPF - .Net - MSSQL - Open Source Restaurant POS System: A C# .Net / WPF / MSSQL Restaurant Point of Sale (POS) Software that is PCI-DSS 2.0 Compliant running stable in many restaurants / integrated with MercuryPay.dcview: dcinside.com? ??? ? ?? ?? ??? ???? ???.DotNetNuke Contact Form: simple yet effective DotNetNuke contact formISBNdb.com Helper Library: A .net helper library that encapsulates all the functionality of the API at www.isbndb.com in .NET CLR objects.JPO Class Register: Simple class register.NACHA C# Class with WPF Test App: Do you need to generate a NACHA PPD file? This is great starting point for you! Actually, it's a great, almost finished, point for you! More info below.NotificationsWidget In ASP MVC: SummaryPayPal Manager: I decided to make a basic (for now) desktop client for PayPal to get better at WebRequests in VB.NET. I will be adding much more such as sending payments, etc.Pomodoro Timer Count Down App: Pomodoro count down timer Application Features ------------------------------- Pomodoro Mode Count down timer mode Start stop pause Notification Powershell HTML Highlight: Powershell html syntax highlightingProject F10_P1: F10 p1Razor-sharp your skills: This project will have details about the C# 2.0 C# 3.0 C# 4.0 C# 5.0 Salaria: Bienvenue sur notre projet "Salaria".SharePoint 2010 - Unlock SP Files: Unlock any file in SharePoint or get lock information of a SharePoint file.( Compatible with office 365) ""The file "" is locked for exclusive use by""SharePoint 2010 Metro Masterpage: This project will give you a full metro masterpage for sharepoint 2010SharePoint Cache Refresh Framework: This project's aim is build a small and easy to use framework for SharePoint developers to be able to control cached objects across servers in a SharePoint FarmTFSProjectTest: A test project.uhimania test project: testUpgrade SPSolution: This is a Sharepoint 2010 Management Shell cmdlet, which upgrades a sharepoint solution and installs/activates any new features added in the package.Video Frame Explorer: Video Frame Explorer allows you to make thumbnails (caps, previews) of video files. It supports of practically any videos-formats (even MP4, MKV, MOV if you havWML: WML

    Read the article

  • CodePlex Daily Summary for Tuesday, July 10, 2012

    CodePlex Daily Summary for Tuesday, July 10, 2012Popular ReleasesjListSelect - jQuery plug-in for a fully customizable select input: 1.0: This is the initial release. Documentation is available using the Documentation tab above and inside the JavaScript code.Push Framework: Push Framework 1.5: This version brings many bug fixes and enhancements to its predecessor.DbDiff: Database Diff and Database Scripting: 1.1.3.3: Sql 2005, Sql 2012 fixes Removed dbdiff recommended default exe because it was a wrong build.re-linq: 1.13.158: This is build 1.13.158 of re-linq. Find the complete release notes for the build here: Release NotesMishra Reader: Mishra Reader beta 3: Per-feed browsing Tons of bug fixes Note: This release requires .NET 4.5 RC. You'll be prompted to install it if you don't already have it. The RC will be upgradeable to the RTM once it's available.MVVM Light Toolkit: MVVM Light Toolkit V4 RTM: The issue with the installer is fixed, sorry for the problems folks This version supports Silverlight 3, Silverlight 4, Silverlight 5, WPF 3.5 SP1, WPF4, Windows Phone 7.0 and 7.5, WinRT (Windows 8). Support for Visual Studio 2010 and Visual Studio 2012 RC.BlackJumboDog: Ver5.6.7: 2012.07.08 Ver5.6.7 (1) ????????????????「????? Request.Receve()」?????????? (2) Web???????????FlMML customized: FlMML customized ??: FlMML customized ????。 ??、PCM??????????、??????。ecBlog: ecBlog 0.2: ecBlog alpha realaseTaskScheduler ASP.NET: Release 3 - 1.2.0.0: Release 3 - Version 1.2.0.0 That version was altered only the library: In TaskScheduler was added new properties: UseBackgroundThreads Enables the use of separate threads for each task. StoreThreadsInPool Manager enables to store in the Pool threads that are performing the tasks. OnStopSchedulerAutoCancelThreads Scheduler allows aborting threads when it is stopped. false if the scheduler is not aborted the threads that are running. AutoDeletedExecutedTasks Allows Manager Delete Task afte...DotNetNuke Persian Packages: ??? ?? ???? ????? ???? 6.2.0: *????? ???? ??? ?? ???? 6.2.0 ? ??????? ???? ????? ???? ??? ????? *????? ????? ????? ??? ??? ???? ??? ??????? ??????? - ???? *?????? ???? ??? ?????? ?? ???? ???? ????? ? ?? ??? ?? ???? ???? ?? *????? ????? ????? ????? ????? / ??????? ???? ?? ???? ??? ??? - ???? *???? ???? ???? ????? ? ??????? ??? ??? ??? ?? ???? *????? ????? ???????? ??? ? ??????? ?? ?? ?????? ????? ????????? ????? ?????? - ???? *????? ????? ?????? ????? ?? ???? ?? ?? ?? ???????? ????? ????? ????????? ????? ?????? *???? ?...Cypher Bot: Cypher Bot 4.1: Cypher Bot is the most advanced encryption tool on the planet.... and now it actually works. That's right we fixed the bugs! For a full program summary go to the Home Page or visit www.iRareMedia.com So what's new? We've pretty much fixed all the bugs, but here's a run down if you wanna know exactly what's different: Fixed Installation / Setup Error, where an error message would display: "No Internet Connection, Try Again Later" Fixed File Encryption / Decryption error where the file exten...Coding4Fun Kinect Service: Coding4Fun Kinect Service v1.5: Requires Kinect for Windows SDK v1.5 Minor bug fixes + Kinect for Windows SDK v1.5 Aligning version with the Kinect for Windows SDK requiredtedplay: tedplay 1.1: tedplay 1.1 source and Win32 binary is out now. Changes are: SID card support Commodore 64 PSID music format support optimized FIR filter global hotkeys for skipping tracks (Windows only) module properties window (Windows only) mutable noise channel via GUI button (Windows only) disable SID card from the menu (Windows only) bugfixes PSID tunes are played on the C64 clock frequency but in a Commodore plus/4 virtual machine. The purpose is not to have yet another SID player, but t...xUnit.net Contrib: xunitcontrib-resharper 0.6 (RS 7.0, 6.1.1): xunitcontrib release 0.6 (ReSharper runner) This release provides a test runner plugin for Resharper 7.0 (EAP build 82) and 6.1, targetting all versions of xUnit.net. (See the xUnit.net project to download xUnit.net itself.) Copies of the plugin that support previous verions of ReSharper can be downloaded from this release. The plan is to support the latest revisions of the last two paid-for major versions of ReSharper (namely 7.0 and 6.1) Also note that all builds work against ALL VERSIONS...Umbraco CMS: Umbraco 4.8.0 Beta: Whats newuComponents in the core Multi-Node Tree Picker, Multiple Textstring, Slider and XPath Lists Easier Lucene searching built in IFile providers for easier file handling Updated 3rd party libraries Applications / Trees moved out of the database SQL Azure support added Various bug fixes Getting Started A great place to start is with our Getting Started Guide: Getting Started Guide: http://umbraco.codeplex.com/Project/Download/FileDownload.aspx?DownloadId=197051 Make sure to...CODE Framework: 4.0.20704.0: See CODE Framework (.NET) Change Log for changes in this version.xUnit.net - Unit testing framework for C# and .NET (a successor to NUnit): xUnit.net 1.9.1: xUnit.net release 1.9.1Build #1600 Important note for Resharper users: Resharper support has been moved to the xUnit.net Contrib project. Important note for TestDriven.net users: If you are having issues running xUnit.net tests in TestDriven.net, especially on 64-bit Windows, we strongly recommend you upgrade to TD.NET version 3.0 or later. Important note for VS2012 users: The VS2012 runner is in the Visual Studio Gallery now, and should be installed via Tools | Extension Manager from insi...MVC Controls Toolkit: Mvc Controls Toolkit 2.2.0: Added Modified all Mv4 related features to conform with the Mvc4 RC Now all items controls accept any IEnumerable<T>(before just List<T> were accepted by most of controls) retrievalManager class that retrieves automatically data from a data source whenever it catchs events triggered by filtering, sorting, and paging controls move method to the updatesManager to move one child objects from a father to another. The move operation can be undone like the insert, update and delete operatio...IronPython: 2.7.3: On behalf of the IronPython team, I'm happy to announce the final release of IronPython 2.7.3. This release includes everything from IronPython 54498, 62475, and 74478 as well. Like all IronPython 2.7-series releases, .NET 4 is required to install it. Installing this release will replace any existing IronPython 2.7-series installation. The incompatibility with IronRuby has been resolved, and they can once again be installed side-by-side. The biggest improvements in IronPython 2.7.3 are: the...New ProjectsAuction Helper: Auction HelperBizTalk 0MQ Adapter: The BizTalk 0MQ Adapter allows BizTalk to send and receive messages using the ZeroMq cross platform messaging framework.fluentstatement: FluentStatement is a library for .NET usable to create Expressions Trees through its fluent interface. These ET can contain Lambda Expressions and Statements.Freemansoft: ??????????????????gppsoftware: gppsoftwarejAutoFitText - jQuery plug-in to auto-fit text similar to iOS applications: This is a jQuery plug-in that automatically fits text in a specific container using font size manipulation and/or string truncation. The end result is simjDelayedAction - jQuery plug-in to allow a delayed reaction to an event: This is a jQuery plug-in that allows the creation of an event (or multiple event) handler with a delay that can be extended or canceled before reacting.jInMemoryImageLoader - jQuery plug-in to asynchronously load an image: This is a jQuery plug-in that allows the asynchronous, in-memory loading of an image file with a callback for when it has succeeded or failed to load.jListSelect - jQuery plug-in for a fully customizable select input: A jQuery plug-in that allows you to create a fully customizable select input.jNumericalInput - jQuery plug-in to limit a text input to only numeric values: A simple jQuery plug-in that, when applied to an input of type text, only allows the input to have a numeric value (positive or negative).jVerticalAlignMiddle - jQuery plug-in to vertically align elements: A simple jQuery plug-in that vertically centers one element within its parent container.lhhp.net: this project is for testLiteCode: Your having enough of crackers, reverse engineers ? With LiteCode you can host your code remotely at a server where no cracker can touch itNetEx .net tool set: NetEx .net tool setOpenFlashChart: OpenFlashChart ??????Flash Chart??。 Project RPG: Developers learn how to design a game from the ground up.saka-pon.net: saka-pon.net.School System: Its all about school managementSeeForYourself: SeeForYourSelfSharepoint JQuery Editor Web Part: Enables quick JQuery development by executing your code immediately while in desing mode.Simplex: Simplex ???????????????J2EE???????????????。 Stuff.NET: This library provides several useful classes and methods to deal with frequently appearing challenges. e.g.: pathfinding, forms/controls, dynamic compiling, ...

    Read the article

  • Getting null value after adding objects to customClass

    - by Brian Stacks
    Ok here's my code first viewController.h @interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate> { NSMutableArray *twitterObjects; } @property (strong, nonatomic) IBOutlet UICollectionView *myCollectionView; Here is my viewController.m // // ViewController.m // MDF2p2 // // Created by Brian Stacks on 6/5/14. // Copyright (c) 2014 Brian Stacks. All rights reserved. // #import "ViewController.h" // add accounts framework to code #import <Accounts/Accounts.h> // add social frameworks #import <Social/Social.h> #import "TwitterCustomObject.h" #import "CustomCell.h" #import "DetailViewController.h" @interface ViewController () @end @implementation ViewController -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { //CustomCell * cell = (CustomCell*)sender; //NSIndexPath *indexPath = [_myCollectionView indexPathForCell:cell]; // setting an id for view controller DetailViewController *detailViewcontroller = segue.destinationViewController; //TwitterCustomObject *newCustomClass = [twitterObjects objectAtIndex:indexPath.row]; if (detailViewcontroller != nil) { // setting the custom customClass object //detailViewcontroller.myNewCurrentClass = newCustomClass; } } - (void)viewDidLoad { twitterObjects = [[NSMutableArray alloc]init]; [super viewDidLoad]; [self twitterAPIcall]; // Do any additional setup after loading the view, typically from a nib. } - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return 100; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { //UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath]; // initiate celli CustomCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath]; // add objects to cell if (cell != nil) { //TwitterCustomObject *newCustomClass = [twitterObjects objectAtIndex:indexPath.row]; //[cell refreshCell:newCustomClass.userName userImage:newCustomClass.userImage]; [cell refreshCell:@"Brian" userImage:[UIImage imageNamed:@"love.jpg"]]; } return cell; } -(void)twitterAPIcall { //create an instance of the account store from account frameworks ACAccountStore *accountStore = [[ACAccountStore alloc]init]; // make sure we have a valid object if (accountStore != nil) { // get the account type ex: Twitter, FAcebook info ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]; // make sure we have a valid object if (accountType != nil) { // give access to the account iformation [accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) { if (granted) { //^^^success user gave access to account information // get the info of accounts NSArray *twitterAccounts = [accountStore accountsWithAccountType:accountType]; // make sure we have a valid object if (twitterAccounts != nil) { //NSLog(@"Accounts: %@",twitterAccounts); // get the current account information ACAccount *currentAccount = [twitterAccounts objectAtIndex:0]; // make sure we have a valid object if (currentAccount != nil) { //string from twitter api NSString *requestString = @"https://api.twitter.com/1.1/friends/list.json"; // request the data from the request screen call SLRequest *myRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:[NSURL URLWithString:requestString] parameters:nil]; // must authenticate request [myRequest setAccount:currentAccount]; // perform the request named myRequest [myRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) { // check to make sure there are no errors and we have a good http:request of 200 if ((error == nil) && ([urlResponse statusCode] == 200)) { // make array of dictionaries from the twitter api data using NSJSONSerialization NSArray *twitterFeed = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil]; NSMutableArray *nameArray = [twitterFeed valueForKeyPath:@"users"]; // for loop that loops through all the post for (NSInteger i =0; i<[twitterFeed count]; i++) { NSString *nameString = [nameArray valueForKeyPath:@"name"]; NSString *imageString = [nameArray valueForKeyPath:@"profile_image_url"]; NSLog(@"Name feed: %@",nameString); NSLog(@"Image feed: %@",imageString); // get data into my mutable array TwitterCustomObject *twitterInfo = [self createPostFromArray:[nameArray objectAtIndex:i]]; //NSLog(@"Image feed: %@",twitterInfo); if (twitterInfo != nil) { [twitterObjects addObject:twitterInfo]; } } } }]; } } } else { // the user didn't give access UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"This app will only work with twitter accounts being allowed!." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:FALSE]; } }]; } } } -(TwitterCustomObject*)createPostFromArray:(NSArray*)postArray { // create strings to catch the data in NSArray *userArray = [postArray valueForKeyPath:@"users"]; NSString *myUserName = [userArray valueForKeyPath:@"name"]; NSString *twitImageURL = [userArray valueForKeyPath:@"profile_image_url"]; UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:twitImageURL]]]; // initiate object to put the data in TwitterCustomObject *twitterData = [[TwitterCustomObject alloc]initWithPostInfo:myUserName myImage:image]; NSLog(@"Name: %@",myUserName); return twitterData; } -(IBAction)done:(UIStoryboardSegue*)segue { } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end Here is my customObject class TwitterCustomClass.h // // TwitterCustomObject.h // MDF2p2 // // Created by Brian Stacks on 6/5/14. // Copyright (c) 2014 Brian Stacks. All rights reserved. // #import <Foundation/Foundation.h> @interface TwitterCustomObject : NSObject { } @property (nonatomic, readonly) NSString *userName; @property (nonatomic, readonly) UIImage *userImage; -(id)initWithPostInfo:(NSString*)screenName myImage:(UIImage*)myImage; @end TwitterCustomClass.m // // TwitterCustomObject.m // MDF2p2 // // Created by Brian Stacks on 6/5/14. // Copyright (c) 2014 Brian Stacks. All rights reserved. // #import "TwitterCustomObject.h" @implementation TwitterCustomObject -(id)initWithPostInfo:(NSString*)screenName myImage:(UIImage*)myImage { // initialize as object if (self = [super init]) { // use the data to be passed back and forth to the tableview _userName = [screenName copy]; _userImage = [myImage copy]; } return self; } @end The problem is I get the values in the method twitterAPIcall, I can get the names and image values or strings from the values. But in the (TwitterCustomObject*)createPostFromArray:(NSArray*)postArray method all values are coming up as null.I thought it got added with this line of code in the twitterAPIcall method [twitterObjects addObject:twitterInfo];?

    Read the article

  • Python hashable dicts

    - by TokenMacGuy
    As an exercise, and mostly for my own amusement, I'm implementing a backtracking packrat parser. The inspiration for this is i'd like to have a better idea about how hygenic macros would work in an algol-like language (as apposed to the syntax free lisp dialects you normally find them in). Because of this, different passes through the input might see different grammars, so cached parse results are invalid, unless I also store the current version of the grammar along with the cached parse results. (EDIT: a consequence of this use of key-value collections is that they should be immutable, but I don't intend to expose the interface to allow them to be changed, so either mutable or immutable collections are fine) The problem is that python dicts cannot appear as keys to other dicts. Even using a tuple (as I'd be doing anyways) doesn't help. >>> cache = {} >>> rule = {"foo":"bar"} >>> cache[(rule, "baz")] = "quux" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'dict' >>> I guess it has to be tuples all the way down. Now the python standard library provides approximately what i'd need, collections.namedtuple has a very different syntax, but can be used as a key. continuing from above session: >>> from collections import namedtuple >>> Rule = namedtuple("Rule",rule.keys()) >>> cache[(Rule(**rule), "baz")] = "quux" >>> cache {(Rule(foo='bar'), 'baz'): 'quux'} Ok. But I have to make a class for each possible combination of keys in the rule I would want to use, which isn't so bad, because each parse rule knows exactly what parameters it uses, so that class can be defined at the same time as the function that parses the rule. But combining the rules together is much more dynamic. In particular, I'd like a simple way to have rules override other rules, but collections.namedtuple has no analogue to dict.update(). Edit: An additional problem with namedtuples is that they are strictly positional. Two tuples that look like they should be different can in fact be the same: >>> you = namedtuple("foo",["bar","baz"]) >>> me = namedtuple("foo",["bar","quux"]) >>> you(bar=1,baz=2) == me(bar=1,quux=2) True >>> bob = namedtuple("foo",["baz","bar"]) >>> you(bar=1,baz=2) == bob(bar=1,baz=2) False tl'dr: How do I get dicts that can be used as keys to other dicts? Having hacked a bit on the answers, here's the more complete solution I'm using. Note that this does a bit extra work to make the resulting dicts vaguely immutable for practical purposes. Of course it's still quite easy to hack around it by calling dict.__setitem__(instance, key, value) but we're all adults here. class hashdict(dict): """ hashable dict implementation, suitable for use as a key into other dicts. >>> h1 = hashdict({"apples": 1, "bananas":2}) >>> h2 = hashdict({"bananas": 3, "mangoes": 5}) >>> h1+h2 hashdict(apples=1, bananas=3, mangoes=5) >>> d1 = {} >>> d1[h1] = "salad" >>> d1[h1] 'salad' >>> d1[h2] Traceback (most recent call last): ... KeyError: hashdict(bananas=3, mangoes=5) based on answers from http://stackoverflow.com/questions/1151658/python-hashable-dicts """ def __key(self): return tuple(sorted(self.items())) def __repr__(self): return "{0}({1})".format(self.__class__.__name__, ", ".join("{0}={1}".format( str(i[0]),repr(i[1])) for i in self.__key())) def __hash__(self): return hash(self.__key()) def __setitem__(self, key, value): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def __delitem__(self, key): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def clear(self): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def pop(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def popitem(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def setdefault(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def update(self, *args, **kwargs): raise TypeError("{0} does not support item assignment" .format(self.__class__.__name__)) def __add__(self, right): result = hashdict(self) dict.update(result, right) return result if __name__ == "__main__": import doctest doctest.testmod()

    Read the article

  • Problem with entityForName & ManagedObjectContext when extending tutorial material

    - by Martin KS
    Afternoon all, I tried to add a second data entity to the persistent store in the (locations) coredata tutorial code, and then access this in a new view. I think that I've followed the tutorial, and checked that I'm doing a clean build etc, but can't see what to change to prevent it crashing. I'm afraid I'm at my wits end with this one, and can't seem to find the step that I've missed. I've pasted the header and code files below, please let me know if I need to share any more of the code. The crash seems to happen on the line: NSEntityDescription *entity = [NSEntityDescription entityForName:@"Album" inManagedObjectContext:[self managedObjectContext]]; There is one other line in the code that refers to galleryviewcontroller at the moment, and that's in the main application delegate: galleryViewController.managedObjectContext = [self managedObjectContext]; GalleryViewController.h #import <UIKit/UIKit.h> @interface GalleryViewController : UIViewController { NSManagedObjectContext *managedObjectContext; int rowNumber; IBOutlet UILabel *lblMessage; UIBarButtonItem *addButton; NSMutableArray *imagesArray; } @property (readwrite) int rowNumber; @property (nonatomic,retain) UILabel *lblMessage; @property (nonatomic,retain) NSMutableArray *imagesArray; @property (nonatomic, retain) NSManagedObjectContext *managedObjectContext; @property (nonatomic, retain) UIBarButtonItem *addButton; -(void)updateRowNumber:(int)theIndex; -(void)addImage; @end GalleryViewController.m #import "RootViewController.h" #import "LocationsAppDelegate.h" #import "Album.h" #import "GalleryViewController.h" #import "Image.h" @implementation GalleryViewController @synthesize lblMessage,rowNumber,addButton,managedObjectContext; @synthesize imagesArray; /* // The designated initializer. Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) { // Custom initialization } return self; } */ -(void)updateRowNumber:(int)theIndex{ rowNumber=theIndex; LocationsAppDelegate *mainDelegate =(LocationsAppDelegate *)[[UIApplication sharedApplication] delegate]; Album *anAlbum = [mainDelegate.albumsArray objectAtIndex:rowNumber]; lblMessage.text = anAlbum.uniqueAlbumIdentifier; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addImage)]; addButton.enabled = YES; self.navigationItem.rightBarButtonItem = addButton; /* Found this in another answer, adding it to the code didn't help. if (managedObjectContext == nil) { managedObjectContext = [[[UIApplication sharedApplication] delegate] managedObjectContext]; } */ NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Album" inManagedObjectContext:[self managedObjectContext]]; [request setEntity:entity]; // Order the albums by creation date, most recent first. NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"imagePath" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; [sortDescriptor release]; [sortDescriptors release]; // Execute the fetch -- create a mutable copy of the result. NSError *error = nil; NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; if (mutableFetchResults == nil) { // Handle the error. } [self setImagesArray:mutableFetchResults]; int a = 5; int b = 10; for( int i=0; i<[imagesArray count]; i++ ) { if( a == 325 ) { a = 5; b += 70; } UIImageView *any = [[UIImageView alloc] initWithFrame:CGRectMake(a,b,70,60)]; any.image = [imagesArray objectAtIndex:i]; any.tag = i; [self.view addSubview:any]; [any release]; a += 80; } } -(void)addImage{ NSString *msg = [NSString stringWithFormat:@"%i",rowNumber]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Add image to" message:msg delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes", nil]; [alert show]; [alert release]; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } - (void)viewDidUnload { [super viewDidUnload]; } - (void)dealloc { [lblMessage release]; [managedObjectContext release]; [super dealloc]; } @end

    Read the article

  • Singleton code linker errors in vc 9.0. Runs fine in linux compiled with gcc

    - by user306560
    I have a simple logger that is implemented as a singleton. It works like i want when I compile and run it with g++ in linux but when I compile in Visual Studio 9.0 with vc++ I get the following errors. Is there a way to fix this? I don't mind changing the logger class around, but I would like to avoid changing how it is called. 1>Linking... 1>loggerTest.obj : error LNK2005: "public: static class Logger * __cdecl Logger::getInstance(void)" (?getInstance@Logger@@SAPAV1@XZ) already defined in Logger.obj 1>loggerTest.obj : error LNK2005: "public: void __thiscall Logger::log(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > const &)" (?log@Logger@@QAEXABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) already defined in Logger.obj 1>loggerTest.obj : error LNK2005: "public: void __thiscall Logger::closeLog(void)" (?closeLog@Logger@@QAEXXZ) already defined in Logger.obj 1>loggerTest.obj : error LNK2005: "private: static class Logger * Logger::_instance" (?_instance@Logger@@0PAV1@A) already defined in Logger.obj 1>Logger.obj : error LNK2001: unresolved external symbol "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > Logger::_path" (?_path@Logger@@0V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A) 1>loggerTest.obj : error LNK2001: unresolved external symbol "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > Logger::_path" (?_path@Logger@@0V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A) 1>Logger.obj : error LNK2001: unresolved external symbol "private: static class boost::mutex Logger::_mutex" (?_mutex@Logger@@0Vmutex@boost@@A) 1>loggerTest.obj : error LNK2001: unresolved external symbol "private: static class boost::mutex Logger::_mutex" (?_mutex@Logger@@0Vmutex@boost@@A) 1>Logger.obj : error LNK2001: unresolved external symbol "private: static class std::basic_ofstream<char,struct std::char_traits<char> > Logger::_log" (?_log@Logger@@0V?$basic_ofstream@DU?$char_traits@D@std@@@std@@A) 1>loggerTest.obj : error LNK2001: unresolved external symbol "private: static class std::basic_ofstream<char,struct std::char_traits<char> > Logger::_log" (?_log@Logger@@0V?$basic_ofstream@DU?$char_traits@D@std@@@std@@A) The code, three files Logger.h Logger.cpp test.cpp #ifndef __LOGGER_CPP__ #define __LOGGER_CPP__ #include "Logger.h" Logger* Logger::_instance = 0; //string Logger::_path = "log"; //ofstream Logger::_log; //boost::mutex Logger::_mutex; Logger* Logger::getInstance(){ { boost::mutex::scoped_lock lock(_mutex); if(_instance == 0) { _instance = new Logger; _path = "log"; } } //mutex return _instance; } void Logger::log(const std::string& msg){ { boost::mutex::scoped_lock lock(_mutex); if(!_log.is_open()){ _log.open(_path.c_str()); } if(_log.is_open()){ _log << msg.c_str() << std::endl; } } } void Logger::closeLog(){ Logger::_log.close(); } #endif ` ... #ifndef __LOGGER_H__ #define __LOGGER_H__ #include <iostream> #include <string> #include <fstream> #include <boost/thread/mutex.hpp> #include <boost/thread.hpp> using namespace std; class Logger { public: static Logger* getInstance(); void log(const std::string& msg); void closeLog(); protected: Logger(){} private: static Logger* _instance; static string _path; static bool _logOpen; static ofstream _log; static boost::mutex _mutex; //check mutable }; #endif test.cpp ` #include <iostream> #include "Logger.cpp" using namespace std; int main(int argc, char *argv[]) { Logger* log = Logger::getInstance(); log->log("hello world\n"); return 0; }

    Read the article

  • What does Ruby have that Python doesn't, and vice versa?

    - by Lennart Regebro
    There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody choosing, as they might not have the same tastes in development as I do. It would therefore be interesting to list the differences, objectively. So no "Python's lambdas sucks". Instead explain what Ruby's lambdas can do that Python's can't. No subjectivity. Example code is good! Don't have several differences in one answer, please. And vote up the ones you know are correct, and down those you know are incorrect (or are subjective). Also, differences in syntax is not interesting. We know Python does with indentation what Ruby does with brackets and ends, and that @ is called self in Python. UPDATE: This is now a community wiki, so we can add the big differences here. Ruby has a class reference in the class body In Ruby you have a reference to the class (self) already in the class body. In Python you don't have a reference to the class until after the class construction is finished. An example: class Kaka puts self end self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python. All classes are mutable in Ruby This lets you develop extensions to core classes. Here's an example of a rails extension: class String def starts_with?(other) head = self[0, other.length] head == other end end Ruby has Perl-like scripting features Ruby has first class regexps, $-variables, the awk/perl line by line input loop and other features that make it more suited to writing small shell scripts that munge text files or act as glue code for other programs. Ruby has first class continuations Thanks to the callcc statement. In Python you can create continuations by various techniques, but there is no support built in to the language. Ruby has blocks With the "do" statement you can create a multi-line anonymous function in Ruby, which will be passed in as an argument into the method in front of do, and called from there. In Python you would instead do this either by passing a method or with generators. Ruby: amethod { |here| many=lines+of+code goes(here) } Python: def function(here): many=lines+of+code goes(here) amethod(function) Interestingly, the convenience statement in Ruby for calling a block is called "yield", which in Python will create a generator. Ruby: def themethod yield 5 end themethod do |foo| puts foo end Python: def themethod(): yield 5 for foo in themethod: print foo Although the principles are different, the result is strikingly similar. Python has built-in generators (which are used like Ruby blocks, as noted above) Python has support for generators in the language. In Ruby you could use the generator module that uses continuations to create a generator from a block. Or, you could just use a block/proc/lambda! Moreover, in Ruby 1.9 Fibers are, and can be used as, generators. docs.python.org has this generator example: def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] Contrast this with the above block examples. Python has flexible name space handling In Ruby, when you import a file with require, all the things defined in that file will end up in your global namespace. This causes namespace pollution. The solution to that is Rubys modules. But if you create a namespace with a module, then you have to use that namespace to access the contained classes. In Python, the file is a module, and you can import its contained names with from themodule import *, thereby polluting the namespace if you want. But you can also import just selected names with from themodule import aname, another or you can simply import themodule and then access the names with themodule.aname. If you want more levels in your namespace you can have packages, which are directories with modules and an __init__.py file. Python has docstrings Docstrings are strings that are attached to modules, functions and methods and can be introspected at runtime. This helps for creating such things as the help command and automatic documentation. def frobnicate(bar): """frobnicate takes a bar and frobnicates it >>> bar = Bar() >>> bar.is_frobnicated() False >>> frobnicate(bar) >>> bar.is_frobnicated() True """ Python has more libraries Python has a vast amount of available modules and bindings for libraries. Python has multiple inheritance Ruby does not ("on purpose" -- see Ruby's website, see here how it's done in Ruby). It does reuse the module concept as a sort of abstract classes. Python has list/dict comprehensions Python: res = [x*x for x in range(1, 10)] Ruby: res = (0..9).map { |x| x * x } Python: >>> (x*x for x in range(10)) <generator object <genexpr> at 0xb7c1ccd4> >>> list(_) [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] Ruby: p = proc { |x| x * x } (0..9).map(&p) Python: >>> {x:str(y*y) for x,y in {1:2, 3:4}.items()} {1: '4', 3: '16'} Ruby: >> Hash[{1=>2, 3=>4}.map{|x,y| [x,(y*y).to_s]}] => {1=>"4", 3=>"16"} Python has decorators Things similar to decorators can be created in Ruby, and it can also be argued that they aren't as necessary as in Python.

    Read the article

< Previous Page | 9 10 11 12 13 14  | Next Page >