Search Results

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

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

  • NSTableView binding problem

    - by Niklas Ottosson
    I have only just started with XCode (v3.2.2) and Interface Builder and have run into a problem. Here is what I have done: I have made a class to be the datasource of a NSTableView: @interface TimeObjectsDS : NSControl { IBOutlet NSTableView * idTableView; NSMutableArray * timeObjects; } @property (assign) NSMutableArray * timeObjects; @property (assign) NSTableView * idTableView; - (id) init; - (void) dealloc; - (void) addTimeObject: (TimeObj *)timeObject; - (int) count; // NSTableViewDataSource Protocol functions - (int)numberOfRowsInTableView:(NSTableView *)tableView; - (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row: (int)row; I have then bound my NSTableView in the View to this datasource like so: I have also bound the View NSTableView to the Model idTableView variable in Interface Builder seen above In the init function I add a element to the mutable array. This is displayed correctly in the NSTableView when I run the application. However when I add another element to the array (of same type as in init) and try to call [idTableView reloadData] on the View nothing happens. In fact the Model idTableView is null. When printing the variable with NSLog(@"idTableView: %@", idTableView) I get "idTableView: (null)" Im runing out of ideas how to fix this. Any ideas to what I could do to fix the binding?

    Read the article

  • Learning Objective-C: Need advice on populating NSMutableDictionary

    - by Zigrivers
    I am teaching myself Objective-C utilizing a number of resources, one of which is the Stanford iPhone Dev class available via iTunes U (past 2010 class). One of the home work assignments asked that I populate a mutable dictionary with a predefined list of keys and values (URLs). I was able to put the code together, but as I look at it, I keep thinking there is probably a much better way for me to approach what I'm trying to do: Populate a NSMutableDictionary with the predefined keys and values Enumerate through the keys of the dictionary and check each key to see if it starts with "Stanford" If it meets the criteria, log both the key and the value I would really appreciate any feedback on how I might improve on what I've put together. I'm the very definition of a beginner, but I'm really enjoying the challenge of learning Objective-C. void bookmarkDictionary () { NSMutableDictionary* bookmarks = [NSMutableDictionary dictionary]; NSString* one = @"Stanford University", *two = @"Apple", *three = @"CS193P", *four = @"Stanford on iTunes U", *five = @"Stanford Mall"; NSString* urlOne = @"http://www.stanford.edu", *urlTwo = @"http://www.apple.com", *urlThree = @"http://cs193p.stanford.edu", *urlFour = @"http://itunes.stanford.edu", *urlFive = @"http://stanfordshop.com"; NSURL* oneURL = [NSURL URLWithString:urlOne]; NSURL* twoURL = [NSURL URLWithString:urlTwo]; NSURL* threeURL = [NSURL URLWithString:urlThree]; NSURL* fourURL = [NSURL URLWithString:urlFour]; NSURL* fiveURL = [NSURL URLWithString:urlFive]; [bookmarks setObject:oneURL forKey:one]; [bookmarks setObject:twoURL forKey:two]; [bookmarks setObject:threeURL forKey:three]; [bookmarks setObject:fourURL forKey:four]; [bookmarks setObject:fiveURL forKey:five]; NSString* akey; NSString* testString = @"Stanford"; for (akey in bookmarks) { if ([akey hasPrefix:testString]) { NSLog(@"Key: %@ URL: %@", akey, [bookmarks objectForKey:akey]); } } } Thanks for your help!

    Read the article

  • Confused over behavior of List.mapi in F#

    - by James Black
    I am building some equations in F#, and when working on my polynomial class I found some odd behavior using List.mapi Basically, each polynomial has an array, so 3*x^2 + 5*x + 6 would be [|6, 5, 3|] in the array, so, when adding polynomials, if one array is longer than the other, then I just need to append the extra elements to the result, and that is where I ran into a problem. Later I want to generalize it to not always use a float, but that will be after I get more working. So, the problem is that I expected List.mapi to return a List not individual elements, but, in order to put the lists together I had to put [] around my use of mapi, and I am curious why that is the case. This is more complicated than I expected, I thought I should be able to just tell it to make a new List starting at a certain index, but I can't find any function for that. type Polynomial() = let mutable coefficients:float [] = Array.empty member self.Coefficients with get() = coefficients static member (+) (v1:Polynomial, v2:Polynomial) = let ret = List.map2(fun c p -> c + p) (List.ofArray v1.Coefficients) (List.ofArray v2.Coefficients) let a = List.mapi(fun i x -> x) match v1.Coefficients.Length - v2.Coefficients.Length with | x when x < 0 -> ret :: [((List.ofArray v1.Coefficients) |> a)] | x when x > 0 -> ret :: [((List.ofArray v2.Coefficients) |> a)] | _ -> [ret]

    Read the article

  • Duplicate method 'ProcessRequest' in ASPX

    - by Mauricio Scheffer
    I'm trying to code ASP.NET MVC views (WebForms view engine) in F#. I can already write regular ASP.NET WebForms ASPX and it works ok, e.g. <%@ Page Language="F#" %> <% for i in 1..2 do %> <%=sprintf "%d" i %> so I assume I have everything in my web.config correctly set up. However, when I make the page inherit from ViewPage: <%@ Page Language="F#" Inherits="System.Web.Mvc.ViewPage" %> I get this error: Compiler Error Message: FS0442: Duplicate method. The abstract method 'ProcessRequest' has the same name and signature as an abstract method in an inherited type. The problem seems to be this piece of code generated by the F# CodeDom provider: [<System.Diagnostics.DebuggerNonUserCodeAttribute>] abstract ProcessRequest : System.Web.HttpContext -> unit [<System.Diagnostics.DebuggerNonUserCodeAttribute>] default this.ProcessRequest (context:System.Web.HttpContext) = let mutable context = context base.ProcessRequest(context) |> ignore when I change the Page directive to use C# instead, the generated code is: [System.Diagnostics.DebuggerNonUserCodeAttribute()] public new virtual void ProcessRequest(System.Web.HttpContext context) { base.ProcessRequest(context); } which of course works fine and AFAIK is not semantically the same as the generated F# code. I'm using .NET 4.0.30319.1 (RTM) and MVC 2 RTM

    Read the article

  • First-chance exception at std::set dectructor

    - by bartek
    Hi, I have a strange exception at my class destructor: First-chance exception reading location 0x00000 class DispLst{ // For fast instance existance test std::set< std::string > instances; [...] DispLst::~DispLst(){ this->clean(); DeleteCriticalSection( &instancesGuard ); } <---- here instances destructor raises exception Call stack: X.exe!std::_Tree,std::allocator ,std::less,std::allocator ,std::allocator,std::allocator ,0 ::begin() Line 556 + 0xc bytes C++ X.exe!std::_Tree,std::allocator ,std::less,std::allocator ,std::allocator,std::allocator ,0 ::_Tidy() Line 1421 + 0x64 bytes C++ X.exe!std::_Tree,std::allocator ,std::less,std::allocator ,std::allocator,std::allocator ,0 ::~_Tree,std::allocator ,std::less,std::allocator ,std::allocator,std::allocator ,0 () Line 541 C++ X.exe!std::set,std::allocator ,std::less,std::allocator ,std::allocator,std::allocator ::~set,std::allocator ,std::less,std::allocator ,std::allocator,std::allocator () + 0x2b bytes C++ X.exe!DispLst::~DispLst() Line 82 + 0xf bytes C++ The exact place of error in xtree: void _Tidy() { // free all storage erase(begin(), end()); <------------------- HERE this->_Alptr.destroy(&_Left(_Myhead)); this->_Alptr.destroy(&_Parent(_Myhead)); this->_Alptr.destroy(&_Right(_Myhead)); this->_Alnod.deallocate(_Myhead, 1); _Myhead = 0, _Mysize = 0; } iterator begin() { // return iterator for beginning of mutable sequence return (_TREE_ITERATOR(_Lmost())); <---------------- HERE } What is going on ? I'm using Visual Studio 2008.

    Read the article

  • Dashcode code translation

    - by Alex Mcp
    Hi, a quick, probably easy question whose answer is probably "best practice" I'm following a tutorial for a custom-template mobile Safari webapp, and to change views around this code is used: function btnSave_ClickHandler(event) { var views = document.getElementById('stackLayout'); var front = document.getElementById('mainScreen'); if (views && views.object && front) { views.object.setCurrentView(front, true); } } My question is just about the if conditional statement. What is this triplet saying, and why do each of those things need to be verified before the view can be changed? Does views.object just test to see if the views variable responds to the object method? Why is this important? EDIT - This is/was the main point of this question, and it regards not Javascript as a language and how if loops work, but rather WHY these 3 things specifically need to be checked: Under what scenarios might views and front not exist? I don't typically write my code so redundantly. If the name of my MySQL table isn't changing, I'll just say UPDATE 'mytable' WHERE... instead of the much more verbose (and in my view, redundant) $mytable = "TheSQLTableName"; if ($mytable == an actual table && $mytable exists && entries can be updated){ UPDATE $mytable; } Whereas if the table's name (or in the JS example, the view's names) ARE NOT "hard coded" but are instead a user input or otherwise mutable, I might right my code as the DashCode example has it. So tell me, can these values "go wrong" anyhow? Thanks!

    Read the article

  • Working with images (CGImage), exif data, and file icons

    - by Nick
    What I am trying to do (under 10.6).... I have an image (jpeg) that includes an icon in the image file (that is you see an icon based on the image in the file, as opposed to a generic jpeg icon in file open dialogs in a program). I wish to edit the exif metadata, save it back to the image in a new file. Ideally I would like to save this back to an exact copy of the file (i.e. preserving any custom embedded icons created etc.), however, in my hands the icon is lost. My code (some bits removed for ease of reading): // set up source ref I THINK THE PROBLEM IS HERE - NOT GRABBING THE INITIAL DATA CGImageSourceRef source = CGImageSourceCreateWithURL( (CFURLRef) URL,NULL); // snag metadata NSDictionary *metadata = (NSDictionary *) CGImageSourceCopyPropertiesAtIndex(source,0,NULL); // make metadata mutable NSMutableDictionary *metadataAsMutable = [[metadata mutableCopy] autorelease]; // grab exif NSMutableDictionary *EXIFDictionary = [[[metadata objectForKey:(NSString *)kCGImagePropertyExifDictionary] mutableCopy] autorelease]; << edit exif >> // add back edited exif [metadataAsMutable setObject:EXIFDictionary forKey:(NSString *)kCGImagePropertyExifDictionary]; // get source type CFStringRef UTI = CGImageSourceGetType(source); // set up write data NSMutableData *data = [NSMutableData data]; CGImageDestinationRef destination = CGImageDestinationCreateWithData((CFMutableDataRef)data,UTI,1,NULL); //add the image plus modified metadata PROBLEM HERE? NOT ADDING THE ICON CGImageDestinationAddImageFromSource(destination,source,0, (CFDictionaryRef) metadataAsMutable); // write to data BOOL success = NO; success = CGImageDestinationFinalize(destination); // save data to disk [data writeToURL:saveURL atomically:YES]; //cleanup CFRelease(destination); CFRelease(source); I don't know if this is really a question of image handling, file handing, post-save processing (I could use sip), or me just being think (I suspect the last). Nick

    Read the article

  • My First F# program

    - by sudaly
    Hi I just finish writing my first F# program. Functionality wise the code works the way I wanted, but not sure if the code is efficient. I would much appreciate if someone could review the code for me and point out the areas where the code can be improved. Thanks Sudaly open System open System.IO open System.IO.Pipes open System.Text open System.Collections.Generic open System.Runtime.Serialization [<DataContract>] type Quote = { [<field: DataMember(Name="securityIdentifier") >] RicCode:string [<field: DataMember(Name="madeOn") >] MadeOn:DateTime [<field: DataMember(Name="closePrice") >] Price:float } let m_cache = new Dictionary<string, Quote>() let ParseQuoteString (quoteString:string) = let data = Encoding.Unicode.GetBytes(quoteString) let stream = new MemoryStream() stream.Write(data, 0, data.Length); stream.Position <- 0L let ser = Json.DataContractJsonSerializer(typeof<Quote array>) let results:Quote array = ser.ReadObject(stream) :?> Quote array results let RefreshCache quoteList = m_cache.Clear() quoteList |> Array.iter(fun result->m_cache.Add(result.RicCode, result)) let EstablishConnection() = let pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4) let mutable sr = null printfn "[F#] NamedPipeServerStream thread created, Wait for a client to connect" pipeServer.WaitForConnection() printfn "[F#] Client connected." try // Stream for the request. sr <- new StreamReader(pipeServer) with | _ as e -> printfn "[F#]ERROR: %s" e.Message sr while true do let sr = EstablishConnection() // Read request from the stream. printfn "[F#] Ready to Receive data" sr.ReadLine() |> ParseQuoteString |> RefreshCache printfn "[F#]Quot Size, %d" m_cache.Count let quot = m_cache.["MSFT.OQ"] printfn "[F#]RIC: %s" quot.RicCode printfn "[F#]MadeOn: %s" (String.Format("{0:T}",quot.MadeOn)) printfn "[F#]Price: %f" quot.Price

    Read the article

  • Why is an Add method required for { } initialization?

    - by Dan Tao
    To use initialization syntax like this: var contacts = new ContactList { { "Dan", "[email protected]" }, { "Eric", "[email protected]" } }; ...my understanding is that my ContactList type would need to define an Add method that takes two string parameters: public void Add(string name, string email); What's a bit confusing to me about this is that the { } initializer syntax seems most useful when creating read-only or fixed-size collections. After all it is meant to mimic the initialization syntax for an array, right? (OK, so arrays are not read-only; but they are fixed size.) And naturally it can only be used when the collection's contents are known (at least the number of elements) at compile-time. So it would almost seem that the main requirement for using this collection initializer syntax (having an Add method and therefore a mutable collection) is at odds with the typical case in which it would be most useful. I'm sure I haven't put as much thought into this matter as the C# design team; it just seems that there could have been different rules for this syntax that would have meshed better with its typical usage scenarios. Am I way off base here? Is the desire to use the { } syntax to initialize fixed-size collections not as common as I think? What other factors might have influenced the formulation of the requirements for this syntax that I'm simply not thinking of?

    Read the article

  • Core Data: Inverse relationship only mirrors when I edit the mutableset. Not sure why.

    - by zorn
    My model is setup so Business has many clients, Client has one business. Inverse relationship is setup in the mom file. I have a unit test like this: - (void)testNewClientFromBusiness { PTBusiness *business = [modelController newBusiness]; STAssertTrue([[business clients] count] == 0, @"is actually %d", [[business clients] count]); PTClient *client = [business newClient]; STAssertTrue([business isEqual:[client business]], nil); STAssertTrue([[business clients] count] == 1, @"is actually %d", [[business clients] count]); } I implement -newClient inside of PTBusiness like this: - (PTClient *)newClient { PTClient *client = [NSEntityDescription insertNewObjectForEntityForName:@"Client" inManagedObjectContext:[self managedObjectContext]]; [client setBusiness:self]; [client updateLocalDefaultsBasedOnBusiness]; return client; } The test fails because [[business clients] count] is still 0 after -newClient is called. If I impliment it like this: - (PTClient *)newClient { PTClient *client = [NSEntityDescription insertNewObjectForEntityForName:@"Client" inManagedObjectContext:[self managedObjectContext]]; NSMutableSet *group = [self mutableSetValueForKey:@"clients"]; [group addObject:client]; [client updateLocalDefaultsBasedOnBusiness]; return client; } The tests passes. My question(s): So am I right in thinking the inverse relationship is only updated when I interact with the mutable set? That seems to go against some other Core Data docs I've read. Is the fact that this is running in a unit test without a run loop have anything to do with it? Any other troubleshooting recommendations? I'd really like to figure out why I can't set up the relationship at the client end.

    Read the article

  • iphone download several files

    - by Floo
    hi all !  In my app i need to download several plist.  to download a plist i use the NSURLconnection  in my code i use an UIAlertView with a UIActivityIndicator then when the download is finished i add a button to the alert to dismiss it.  To download the plist i use somewhere in my code an NSURL set to the adresse where the plist is, next i set a NSURLRequest with the url cache policy and a timeout interval.  Then i set my NSMutableData to the NSURL connection with a NSURLRequest.  In the delegate didReceiveData: i append data to my mutable data object, in the didFailWithError: i handle error. And finaly in the connectionDidFinishLoading  i serialize my data to a plist so i can write to file my plist, and release my alertview.  My problem is : how can i do if i have sevetal file to download because the connectionDidFinishLoading is called each time my NSURLConnection is finished but i want to release my UiAlert when everything is finished. But when the first plist is downloaded my code in the connectionDidFinishLoading will fire.  here is my code :  in the view did load :  // set the UiAlert in the view did load  NSURL *theUrl = [NSURL URLWithString:@"http://adress.com/plist/myPlist.plist"]; NSURLRequest *theRequest = [NSURLRequest requestWithURL:theUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; self.plistConnection = [[ NSURLConnection alloc] initwithRequest:theRequest delegate:self startImmediatly:YES]; //plistConnection is a NSURLConnection - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {  [incomingPListData appendData:data]; } -(void)connection:(NSURLConnection *)connectionDidFailWithError:(NSError *)error { // handle error here  } -(void)connectionDidFinisloading:(NSURLConnection *) connection {  NSPropertyListFormat format; NSString *serialErrorString;  NSData *plist = [NSPropertyListSerialisation propertyListFromData:incomingPlistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&serialErrorString]; if (serialErrorString) {//error} else { // create path and write plist to path} // change message and title of the alert so if i want todownload an another file  where do i put the request the connection and how can i tell the didFinishLoading to fire code when all my file are downloaded.  thanks to all

    Read the article

  • How to make a Global Array?

    - by Wayfarer
    So, I read this post, and it's pretty much exactly what I was looking for. However... it doesn't work. I guess I'm not going to go with the singleton object, but rather making the array in either a Global.h file, or insert it into the _Prefix file. Both times I do that though, I get the error: Expected specifier-qualifier-list before 'static' and it doesn't work. So... I'm not sure how to get it to work, I can remove extern and it works, but I feel like I need that to make it a constant. The end goal is to have this Mutable Array be accessible from any object or any file in my project. Help would be appreciated! This is the code for my Globals.h file: #import <Foundation/Foundation.h> @interface Globals : NSObject { static extern NSMutableArray * myGlobalArray; } @end I don't think I need anything in the implementation file. If I were to put that in the prefix file, the error was the same.

    Read the article

  • Game of life in F# with accelerator

    - by jpalmer
    I'm trying to write life in F# using accelerator v2, but for some odd reason my output isn't square despite all my arrays being square - It appears that everything but a rectangular area in the top left of the matrix is being set to false. I've got no idea how this could be happening as all my operations should treat the entire array equally. Any ideas? open Microsoft.ParallelArrays open System.Windows.Forms open System.Drawing type IPA = IntParallelArray type BPA = BoolParallelArray type PAops = ParallelArrays let RNG = new System.Random() let size = 1024 let arrinit i = Array2D.init size size (fun x y -> i) let target = new DX9Target() let threearr = new IPA(arrinit 3) let twoarr = new IPA(arrinit 2) let onearr = new IPA(arrinit 1) let zeroarr = new IPA(arrinit 0) let shifts = [|-1;-1|]::[|-1;0|]::[|-1;1|]::[|0;-1|]::[|0;1|]::[|1;-1|]::[|1;0|]::[|1;1|]::[] let progress (arr:BPA) = let sums = shifts //adds up whether a neighbor is on or not |> List.fold (fun (state:IPA) t ->PAops.Add(PAops.Cond(PAops.Rotate(arr,t),onearr,zeroarr),state)) zeroarr PAops.Or(PAops.CompareEqual(sums,threearr),PAops.And(PAops.CompareEqual(sums,twoarr),arr)) //rule for life let initrandom () = Array2D.init size size (fun x y -> if RNG.NextDouble() > 0.5 then true else false) type meform () as self= inherit Form() let mutable array = new BoolParallelArray(initrandom()) let timer = new System.Timers.Timer(1.0) //redrawing timer do base.DoubleBuffered <- true do base.Size <- Size(size,size) do timer.Elapsed.Add(fun _ -> self.Invalidate()) do timer.Start() let draw (t:Graphics) = array <- array |> progress let bmap = new System.Drawing.Bitmap(size,size) target.ToArray2D array |> Array2D.iteri (fun x y t -> if not t then bmap.SetPixel(x,y,Color.Black)) t.DrawImageUnscaled(bmap,0,0) do self.Paint.Add(fun t -> draw t.Graphics) do Application.Run(new meform())

    Read the article

  • NSOutlineView/NSTreeController - calculate sum of column

    - by matei
    I have a NSOutlineView bound to a NSTreeController. My data items are a custom class , let's call them "Row", and suppose a Row contains a "name" and a numeric field called "number" . All these "Rows" are found in let's say a "RowContainer" which has a "rows" mutable array holding the parent (level 0) rows. Each row also has a "children" NSMutableArray member which holds it's children. I have this working, and I want to display under the outlineview a textfield with the sum of all the "number" values of the rows. I bound this textfield to a "total" property of the "RowContainer". Now the problem is how or from where to trigger the recalculation of the "total" property, since this involves a recursive walk on the tree of rows, and I always get a "Collection was mutated while being enumerated" error. I've tried making a method "recalculateTotal", and calling it from the "setNumber" method of the "Row" class , but same error occurs. If I put the recalculation logic in the "total" getter, I can't trigger it to do the math. I'm sure the solution is simple but I can't see it

    Read the article

  • More FP-correct way to create an update sql query

    - by James Black
    I am working on access a database using F# and my initial attempt at creating a function to create the update query is flawed. let BuildUserUpdateQuery (oldUser:UserType) (newUser:UserType) = let buf = new System.Text.StringBuilder("UPDATE users SET "); if (oldUser.FirstName.Equals(newUser.FirstName) = false) then buf.Append("SET first_name='").Append(newUser.FirstName).Append("'" ) |> ignore if (oldUser.LastName.Equals(newUser.LastName) = false) then buf.Append("SET last_name='").Append(newUser.LastName).Append("'" ) |> ignore if (oldUser.UserName.Equals(newUser.UserName) = false) then buf.Append("SET username='").Append(newUser.UserName).Append("'" ) |> ignore buf.Append(" WHERE id=").Append(newUser.Id).ToString() This doesn't properly put a , between any update parts after the first, for example: UPDATE users SET first_name='Firstname', last_name='lastname' WHERE id=... I could put in a mutable variable to keep track when the first part of the set clause is appended, but that seems wrong. I could just create an list of tuples, where each tuple is oldtext, newtext, columnname, so that I could then loop through the list and build up the query, but it seems that I should be passing in a StringBuilder to a recursive function, returning back a boolean which is then passed as a parameter to the recursive function. Does this seem to be the best approach, or is there a better one?

    Read the article

  • What's the standard convention for creating a new NSArray from an existing NSArray?

    - by Prairiedogg
    Let's say I have an NSArray of NSDictionaries that is 10 elements long. I want to create a second NSArray with the values for a single key on each dictionary. The best way I can figure to do this is: NSMutableArray *nameArray = [[NSMutableArray alloc] initWithCapacity:[array count]]; for (NSDictionary *p in array) { [nameArray addObject:[p objectForKey:@"name"]]; } self.my_new_array = array; [array release]; [nameArray release]; } But in theory, I should be able to get away with not using a mutable array and using a counter in conjunction with [nameArray addObjectAtIndex:count], because the new list should be exactly as long as the old list. Please note that I am NOT trying to filter for a subset of the original array, but make a new array with exactly the same number of elements, just with values dredged up from the some arbitrary attribute of each element in the array. In python one could solve this problem like this: new_list = [p['name'] for p in old_list] or if you were a masochist, like this: new_list = map(lambda p: p['name'], old_list) Having to be slightly more explicit in objective-c makes me wonder if there is an accepted common way of handling these situations.

    Read the article

  • Why does Hibernate 2nd level cache only cache within a session?

    - by Synesso
    Using a named query in our application and with ehcache as the provider, it seems that the query results are tied to the session. Any attempt to access the value from the cache for a second time results in a LazyInitializationException We have set lazy=true for the following mapping because this object is also used by another part of the system which does not require the reference... and we want to keep it lean. <class name="domain.ReferenceAdPoint" table="ad_point" mutable="false" lazy="false"> <cache usage="read-only"/> <id name="code" type="long" column="ad_point_id"> <generator class="assigned" /> </id> <property name="name" column="ad_point_description" type="string"/> <set name="synonyms" table="ad_point_synonym" cascade="all-delete-orphan" lazy="true"> <cache usage="read-only"/> <key column="ad_point_id" /> <element type="string" column="synonym_description" /> </set> </class> <query name="find.adpoints.by.heading">from ReferenceAdPoint adpoint left outer join fetch adpoint.synonyms where adpoint.adPointField.headingCode = ?</query> Here's a snippet from our hibernate.cfg.xml <property name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</property> <property name="hibernate.cache.use_query_cache">true</property> It doesn't seem to make sense that the cache would be constrained to the session. Why are the cached queries not usable outside of the (relatively short-lived) sessions?

    Read the article

  • How can I SETF an element in a tree by an accessor?

    - by Willi Ballenthin
    We've been using Lisp in my AI course. The assignments I've received have involved searching and generating tree-like structures. For each assignment, I've ended up writing something like: (defun initial-state () (list 0 ; score nil ; children 0 ; value 0)) ; something else and building my functions around these "states", which are really just nested lists with some loosely defined structure. To make the structure more rigid, I've tried to write accessors, such as: (defun state-score ( state ) (nth 2 state)) This works for reading the value (which should be all I need to do in a nicely functional world. However, as time crunches, and I start to madly hack, sometimes I want a mutable structure). I don't seem to be able to SETF the returned ...thing (place? value? pointer?). I get an error with something like: (setf (state-score *state*) 10) Sometimes I seem to have a little more luck writing the accessor/mutator as a macro: (defmacro state-score ( state ) `(nth 2 ,state)) However I don't know why this should be a macro, so I certainly shouldn't write it as a macro (except that sometimes it works. Programming by coincidence is bad). What is an appropriate strategy to build up such structures? More importantly, where can I learn about whats going on here (what operations affect the memory in what way)?

    Read the article

  • initialising a 2-dim Array in Scala

    - by Stefan W.
    (Scala 2.7.7:) I don't get used to 2d-Arrays. Arrays are mutable, but how do I specify a 2d-Array which is - let's say of size 3x4. The dimension (2D) is fixed, but the size per dimension shall be initializable. I tried this: class Field (val rows: Int, val cols: Int, sc: java.util.Scanner) { var field = new Array [Char](rows)(cols) for (r <- (1 to rows)) { val line = sc.nextLine () val spl = line.split (" ") field (r) = spl.map (_.charAt (0)) } def put (val rows: Int, val cols: Int, c: Char) = todo () } I get this error: :11: error: value update is not a member of Char field (r) = spl.map (_.charAt (0)) If it would be Java, it would be much more code, but I would know how to do it, so I show what I mean: public class Field { private char[][] field; public Field (int rows, int cols, java.util.Scanner sc) { field = new char [rows][cols]; for (int r = 0; r < rows; ++r) { String line = sc.nextLine (); String[] spl = line.split (" "); for (int c = 0; c < cols; ++c) field [r][c] = spl[c].charAt (0); } } public static void main (String args[]) { new Field (3, 4, new java.util.Scanner ("fraese.fld")); } } and fraese.fld would look, for example, like that: M M M M . M I get some steps wide with val field = new Array Array [Char] but how would I then implement 'put'? Or is there a better way to implement the 2D-Array. Yes, I could use a one-dim-Array, and work with put (y, x, c) = field (y * width + x) = c but I would prefer a notation which looks more 2d-ish.

    Read the article

  • shielding #include within namespace { } block?

    - by Jeff
    Edit: I know that method 1 is essentially invalid and will probably use method 2, but I'm looking for the best hack or a better solution to mitigate rampant, mutable namespace proliferation. I have multiple class or method definitions in one namespace that have different dependencies, and would like to use the fewest namespace blocks or explicit scopings possible but while grouping #include directives with the definitions that require them as best as possible. I've never seen any indication that any preprocessor could be told to exclude namespace {} scoping from #include contents, but I'm here to ask if something similar to this is possible: (see bottom for explanation of why I want something dead simple) // NOTE: apple.h, etc., contents are *NOT* intended to be in namespace Foo! // would prefer something most this: namespace Foo { #include "apple.h" B *A::blah(B const *x) { /* ... */ } #include "banana.h" int B::whatever(C const &var) { /* ... */ } #include "blueberry.h" void B::something() { /* ... */ } } // namespace Foo ... // over this: #include "apple.h" #include "banana.h" #include "blueberry.h" namespace Foo { B *A::blah(B const *x) { /* ... */ } int B::whatever(C const &var) { /* ... */ } void B::something() { /* ... */ } } // namespace Foo ... // or over this: #include "apple.h" namespace Foo { B *A::blah(B const *x) { /* ... */ } } // namespace Foo #include "banana.h" namespace Foo { int B::whatever(C const &var) { /* ... */ } } // namespace Foo #include "blueberry.h" namespace Foo { void B::something() { /* ... */ } } // namespace Foo My real problem is that I have projects where a module may need to be branched but have coexisting components from the branches in the same program. I have classes like FooA, etc., that I've called Foo::A in the hopes being able to branch less painfully as Foo::v1_2::A, where some program may need both a Foo::A and a Foo::v1_2::A. I'd like "Foo" or "Foo::v1_2" to show up only really once per file, as a single namespace block, if possible. Moreover, I tend to prefer to locate blocks of #include directives immediately above the first definition in the file that requires them. What's my best choice, or alternatively, what should I be doing instead of hijacking the namespaces?

    Read the article

  • Fetching Core Data for Tableview on iPhone - Tutorial leaves me with crashes when adding items to a

    - by Gordon Fontenot
    Been following the Core Data tutorial on Apple's developer site, and all is good until I have to add something to the fetched store. I am getting this error after a successful build and load when I try to add a new item to the list: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted). Due to the fact that the fetch goes through fine, and that if I replace the fetching with eventList = [[NSMutableArray alloc] init] it works as expected (without persistance, of course), I am led to believe that the problem comes from not creating the Mutable Array correctly. Here's the problematic part of the code: NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:managedObjectContext]; [request setEntity:entity]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:NO]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; [sortDescriptors release]; [sortDescriptor release]; NSError *error; NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; if (mutableFetchResults = nil) { //Handle the error } [self setEventList:mutableFetchResults]; [mutableFetchResults release]; [request release]; I have tried switching the NSArrays in the second chunk out with NSMutableArrays, but I still get the same error. For reference, the section of code that is throwing the error when I try adding an entry is here: [eventList insertObject:event atIndex:0]; NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES]; it errors out at the insertRowsAtIndexPaths call. Thanks in advance for any help

    Read the article

  • [F#] Parallelize code in nested loops

    - by Juliet
    You always hear that functional code is inherently easier to parallelize than non-functional code, so I decided to write a function which does the following: Given a input of strings, total up the number of unique characters for each string. So, given the input [ "aaaaa"; "bbb"; "ccccccc"; "abbbc" ], our method will returns a: 6; b: 6; c: 8. Here's what I've written: (* seq<#seq<char>> -> Map<char,int> *) let wordFrequency input = input |> Seq.fold (fun acc text -> (* This inner loop can be processed on its own thread *) text |> Seq.choose (fun char -> if Char.IsLetter char then Some(char) else None) |> Seq.fold (fun (acc : Map<_,_>) item -> match acc.TryFind(item) with | Some(count) -> acc.Add(item, count + 1) | None -> acc.Add(item, 1)) acc ) Map.empty This code is ideally parallelizable, because each string in input can be processed on its own thread. Its not as straightforward as it looks since the innerloop adds items to a Map shared between all of the inputs. I'd like the inner loop factored out into its own thread, and I don't want to use any mutable state. How would I re-write this function using an Async workflow?

    Read the article

  • Several Objective-C objects become Invalid for no reason, sometimes.

    - by farnsworth
    - (void)loadLocations { NSString *url = @"<URL to a text file>"; NSStringEncoding enc = NSUTF8StringEncoding; NSString *locationString = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:url] usedEncoding:&enc error:nil]; NSArray *lines = [locationString componentsSeparatedByString:@"\n"]; for (int i=0; i<[lines count]; i++) { NSString *line = [lines objectAtIndex:i]; NSArray *components = [line componentsSeparatedByString:@", "]; Restaurant *res = [byID objectForKey:[components objectAtIndex:0]]; if (res) { NSString *resAddress = [components objectAtIndex:3]; NSArray *loc = [NSArray arrayWithObjects:[components objectAtIndex:1], [components objectAtIndex:2]]; [res.locationCoords setObject:loc forKey:resAddress]; } else { NSLog([[components objectAtIndex:0] stringByAppendingString:@" res id not found."]); } } } There are a few weird things happening here. First, at the two lines where the NSArray lines is used, this message is printed to the console- *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFDictionary count]: method sent to an uninitialized mutable dictionary object' which is strange since lines is definitely not an NSMutableDictionary, definitely is initialized, and because the app doesn't crash. Also, at random points in the loop, all of the variables that the debugger can see will become Invalid. Local variables, property variables, everything. Then after a couple lines they will go back to their original values. setObject:forKey never has an effect on res.locationCoords, which is an NSMutableDictionary. I'm sure that res, res.locationCoords, and byId are initialized. I also tried adding a retain or copy to lines, same thing. I'm sure there's a basic memory management principle I'm missing here but I'm at a loss.

    Read the article

  • Why is my UITableView not being set?

    - by Jamie L
    I checked using the debbuger in the viewDidLoad method and tracerTableView is 0x0 which i assume means it is nil. I don't understand. I should go ahaed say yes I have already checked my nib file and yes all the connections are correct. Here is the header file and the begging of the .m. ///////////// .h file //////////// @interface TrackerListController : UITableViewController { // The mutable (modifiable) dictionary days holds all the data for the days tab NSMutableArray *trackerList; UITableView *tracerTableView; } @property (nonatomic, retain) NSMutableArray *trackerList; @property (nonatomic, retain) IBOutlet UITableView. *tracerTableView; //The addPackage: method is invoked when the user taps the addbutton created at runtime. -(void) addPackage : (id) sender; @end /////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////// .m file ////////////////////////////////////// @implementation TrackerListController @synthesize trackerList, tracerTableView; (void)viewDidLoad { [super viewDidLoad]; self.title = @"Package Tracker"; self.navigationItem.leftBarButtonItem = self.editButtonItem; UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addPackage:)]; // Set up the Add custom button on the right of the navigation bar self.navigationItem.rightBarButtonItem = addButton; [addButton release]; // Release the addButton from memory since it is no longer needed }

    Read the article

  • Why do bind1st and bind2nd require constant function objects?

    - by rlbond
    So, I was writing a C++ program which would allow me to take control of the entire world. I was all done writing the final translation unit, but I got an error: error C3848: expression having type 'const `anonymous-namespace'::ElementAccumulator<T,BinaryFunction>' would lose some const-volatile qualifiers in order to call 'void `anonymous-namespace'::ElementAccumulator<T,BinaryFunction>::operator ()(const point::Point &,const int &)' with [ T=SideCounter, BinaryFunction=std::plus<int> ] c:\program files (x86)\microsoft visual studio 9.0\vc\include\functional(324) : while compiling class template member function 'void std::binder2nd<_Fn2>::operator ()(point::Point &) const' with [ _Fn2=`anonymous-namespace'::ElementAccumulator<SideCounter,std::plus<int>> ] c:\users\****\documents\visual studio 2008\projects\TAKE_OVER_THE_WORLD\grid_divider.cpp(361) : see reference to class template instantiation 'std::binder2nd<_Fn2>' being compiled with [ _Fn2=`anonymous-namespace'::ElementAccumulator<SideCounter,std::plus<int>> ] I looked in the specifications of binder2nd and there it was: it took a const AdaptibleBinaryFunction. So, not a big deal, I thought. I just used boost::bind instead, right? Wrong! Now my take-over-the-world program takes too long to compile (bind is used inside a template which is instantiated quite a lot)! At this rate, my nemesis is going to take over the world first! I can't let that happen -- he uses Java! So can someone tell me why this design decision was made? It seems like an odd decision. I guess I'll have to make some of the elements of my class mutable for now...

    Read the article

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