Search Results

Search found 1546 results on 62 pages for 'lazy sequences'.

Page 4/62 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Doctrine lazy loading classes takes 100 ms?!

    - by ropstah
    I'm lazy loading my Doctrine classes in my website. Benchmarking has showed that Doctrine::loadModels('models') takes over 100 ms to complete! I have 118 tables in total, but still... setting attribute to conservative loading: Doctrine_Manager::getInstance()->setAttribute(Doctrine::ATTR_MODEL_LOADING, Doctrine::MODEL_LOADING_CONSERVATIVE); running the benchmark part: $CI->benchmark->mark('Doctrineload_start'); Doctrine::loadModels(APPPATH.'models'); $CI->benchmark->mark('Doctrineload_end'); And the result: Doctrineload 0.1085 (seconds) Is this 'normal'? 'context': Loading Time Base Classes 0.0233 Doctrineinit 0.0435 //doctrine_pi.php file, doctrine configuration + db account Doctrineload 0.1085 Masterpageset 0.0001 Userload 0.1208 //1 db query Masterpageaddcontent 0.1565 //1 db query, loading view with some <?=?> php parsing Masterpageshow 0.0203 //loading view Controller Execution Time ( Home / Index ) 0.3591 Total Execution Time 0.3826

    Read the article

  • Lazy loading of child throwing session error

    - by Thomas Buckley
    I'm the following error when calling purchaseService.updatePurchase(purchase) inside my TagController: SEVERE: Servlet.service() for servlet [PurchaseAPIServer] in context with path [/PurchaseAPIServer] threw exception [Request processing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.app.model.Purchase.tags, no session or session was closed] with root cause org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.app.model.Purchase.tags, no session or session was closed at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383) at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375) at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:368) at org.hibernate.collection.PersistentSet.add(PersistentSet.java:212) at com.app.model.Purchase.addTags(Purchase.java:207) at com.app.controller.TagController.createAll(TagController.java:79) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:212) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789) at javax.servlet.http.HttpServlet.service(HttpServlet.java:641) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:662) TagController: @RequestMapping(value = "purchases/{purchaseId}/tags", method = RequestMethod.POST, params = "manyTags") @ResponseStatus(HttpStatus.CREATED) public void createAll(@PathVariable("purchaseId") final Long purchaseId, @RequestBody final Tag[] entities) { Purchase purchase = purchaseService.getById(purchaseId); Set<Tag> tags = new HashSet<Tag>(Arrays.asList(entities)); purchase.addTags(tags); purchaseService.updatePurchase(purchase); } Purchase: @Entity @XmlRootElement public class Purchase implements Serializable { /** * */ private static final long serialVersionUID = 6603477834338392140L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @OneToMany(mappedBy = "purchase", fetch = FetchType.LAZY, cascade={CascadeType.ALL}) private Set<Tag> tags; @JsonIgnore public Set<Tag> getTags() { if (tags == null) { tags = new LinkedHashSet<Tag>(); } return tags; } public void setTags(Set<Tag> tags) { this.tags = tags; } ... } Tag: @Entity @XmlRootElement public class Tag implements Serializable { /** * */ private static final long serialVersionUID = 5165922776051697002L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumns({@JoinColumn(name = "PURCHASEID", referencedColumnName = "ID")}) private Purchase purchase; @JsonIgnore public Purchase getPurchase() { return purchase; } public void setPurchase(Purchase purchase) { this.purchase = purchase; } } PurchaseService: @Service public class PurchaseService implements IPurchaseService { @Autowired private IPurchaseDAO purchaseDAO; public PurchaseService() { } @Transactional public List<Purchase> getAll() { return purchaseDAO.findAll(); } @Transactional public Purchase getById(Long id) { return purchaseDAO.findOne(id); } @Transactional public void addPurchase(Purchase purchase) { purchaseDAO.save(purchase); } @Transactional public void updatePurchase(Purchase purchase) { purchaseDAO.update(purchase); } } TagService: @Service public class TagService implements ITagService { @Autowired private ITagDAO tagDAO; public TagService() { } @Transactional public List<Tag> getAll() { return tagDAO.findAll(); } @Transactional public Tag getById(Long id) { return tagDAO.findOne(id); } @Transactional public void addTag(Tag tag) { tagDAO.save(tag); } @Transactional public void updateTag(Tag tag) { tagDAO.update(tag); } } Any ideas on how I can fix this? (I want to avoid using EAGER loading). Do I need to setup some form of session management for transactions? Thanks

    Read the article

  • Lazy Tables app from iphone

    - by Warrior
    I am new to iphone development. I have parsed a youtube file and displaying its contents with the image in the table view. But the scrolling has become slower because of displaying image.So i want to display the image as the lazy tables program from apple docs.Since they have used navigation based application , their rootviewcontroller loads first and then the delegate class call the parsing ,and when they reload the table view, the contents are displayed. The data array count shows 25. I am using a view controller to display the tables on the present modal view, more over when i run my application, first delegate methods call the parsing. So when i click the youtube icon in my landing page it navigates to table view. So by this time data array count shows 0. I have created table view in interface builder and set the outlets to the file owner properly. Please help me out. I want to increasing the scrolling performance. Thanks.

    Read the article

  • Checking lazy loaded properties have been instantiated

    - by PaulG
    In a class which has a lazy loaded property, such as: private Collection<int> someInts; public Collection<int> SomeInts { get { if (this.someInts == null) this.someInts = new Collection<int>(); return this.someInts; } } Is it worth also having a property such as: public bool SomeIntsExist { get { return (this.someInts != null && this.someInts.Count > 0); } } And then using that property.. eg: if (thatClass.SomeIntsExist) { // do something with thatClass.SomeInts collection } or is this premature optimisation. Its certainly easier to roll with something like below, but it will instantiate the collection needlessly: if (thatClass.SomeInts.Count > 0) { // do something with thatClass.SomeInts collection } Is the compiler smart enough to figure things like this out? Is there a better way?

    Read the article

  • Lazy evaluation with ostream C++ operators

    - by SavinG
    I am looking for a portable way to implement lazy evaluation in C++ for logging class. Let's say that I have a simple logging function like void syslog(int priority, const char *format, ...); then in syslog() function we can do: if (priority < current_priority) return; so we never actually call the formatting function (sprintf). On the other hand, if we use logging stream like log << LOG_NOTICE << "test " << 123; all the formating is always executed, which may take a lot of time. Is there any possibility to actually use all the goodies of ostream (like custom << operator for classes, type safety, elegant syntax...) in a way that the formating is executed AFTER the logging level is checked ?

    Read the article

  • using lazy C++ for stub generation

    - by Abruzzo Forte e Gentile
    Hi all Have you ever used lazy C++? I am trying to create .CPP files out of .H files. In forum I read that it is possible with your tool but I tried touse it and I didn't succeed. Can you help me? I used the option -c with a Test.h file with exactly the following declaration. class TEST_A { public: TEST_A(); ~TEST_A(); void fooA( MyNamespace::String& aName ); }; The only thing I have is a Cpp file with written #define LZZ_INLINE #undef LZZ_INLINE and the .h file modified with before the class #define LZZ_LINE inline class TEST_A { public: TEST_A(); ~TEST_A(); void fooA( MyNamespace::String& aName ); }; #undef LZZ_LINE What I am doing wrong?

    Read the article

  • boost.serialization and lazy initialization

    - by niXman
    i need to serialize directory tree. i have no trouble with this type: std::map< std::string, // string(path name) std::vector<std::string> // string array(file names in the path) > tree; but for the serialization the directory tree with the content i need other type: std::map< std::string, // string(path name) std::vector< // files array std::pair< std::string, // file name std::vector< // array of file pieces std::pair< // <<<<<<<<<<<<<<<<<<<<<< for this i need lazy initialization std::string, // piece buf boost::uint32_t // crc32 summ on piece > > > > > tree; how can i serialize the object of type "std::pair" in the moment of its serialization?

    Read the article

  • Can someone please explain this lazy evaluation code?

    - by Tejs
    So, this question was just asked on SO: http://stackoverflow.com/questions/2740001/how-to-handle-an-infinite-ienumerable My sample code: public static void Main(string[] args) { foreach (var item in Numbers().Take(10)) Console.WriteLine(item); Console.ReadKey(); } public static IEnumerable<int> Numbers() { int x = 0; while (true) yield return x++; } Can someone please explain why this is lazy evaluated? I've looked up this code in Reflector, and I'm more confused than when I began. Reflector outputs: public static IEnumerable<int> Numbers() { return new <Numbers>d__0(-2); } For the numbers method, and looks to have generated a new type for that expression: [DebuggerHidden] public <Numbers>d__0(int <>1__state) { this.<>1__state = <>1__state; this.<>l__initialThreadId = Thread.CurrentThread.ManagedThreadId; } This makes no sense to me. I would have assumed it was an infinite loop until I put that code together and executed it myself.

    Read the article

  • Entity Framework lazy loading doesn't work from other thread

    - by Thomas Levesque
    Hi, I just found out that lazy loading in Entity Framework only works from the thread that created the ObjectContext. To illustrate the problem, I did a simple test, with a simple model containing just 2 entities : Person and Address. Here's the code : private static void TestSingleThread() { using (var context = new TestDBContext()) { foreach (var p in context.Person) { Console.WriteLine("{0} lives in {1}.", p.Name, p.Address.City); } } } private static void TestMultiThread() { using (var context = new TestDBContext()) { foreach (var p in context.Person) { Person p2 = p; // to avoid capturing the loop variable ThreadPool.QueueUserWorkItem( arg => { Console.WriteLine("{0} lives in {1}.", p2.Name, p2.Address.City); }); } } } The TestSingleThread method works fine, the Address property is lazily loaded. But in TestMultiThread, I get a NullReferenceException on p2.Address.City, because p2.Address is null. It that a bug ? Is this the way it's supposed to work ? If so, is there any documentation mentioning it ? I couldn't find anything on the subject on MSDN or Google... And more importantly, is there a workaround ? (other than explicitly calling LoadProperty from the worker thread...) Any help would be very appreciated PS: I'm using VS2010, so it's EF 4.0. I don't know if it was the same in the previous version of EF...

    Read the article

  • Haskell lazy I/O and closing files

    - by Jesse
    I've written a small Haskell program to print the MD5 checksums of all files in the current directory (searched recursively). Basically a Haskell version of md5deep. All is fine and dandy except if the current directory has a very large number of files, in which case I get an error like: <program>: <currentFile>: openBinaryFile: resource exhausted (Too many open files) It seems Haskell's laziness is causing it not to close files, even after its corresponding line of output has been completed. The relevant code is below. The function of interest is getList. import qualified Data.ByteString.Lazy as BS main :: IO () main = putStr . unlines =<< getList "." getList :: FilePath -> IO [String] getList p = let getFileLine path = liftM (\c -> (hex $ hash $ BS.unpack c) ++ " " ++ path) (BS.readFile path) in mapM getFileLine =<< getRecursiveContents p hex :: [Word8] -> String hex = concatMap (\x -> printf "%0.2x" (toInteger x)) getRecursiveContents :: FilePath -> IO [FilePath] -- ^ Just gets the paths to all the files in the given directory. Are there any ideas on how I could solve this problem? The entire program is available here: http://haskell.pastebin.com/PAZm0Dcb

    Read the article

  • [EF + Oracle] Inserting Data (Sequences) (2/2)

    - by JTorrecilla
    Prologue In the previous chapter we have see how to create DB records with EF, now we are going to Some Questions about Oracle.   ORACLE One characteristic from SQL Server that differs from Oracle is “Identity”. To all that has not worked with SQL Server, this property, that applies to Integer Columns, lets indicate that there is auto increment columns, by that way it will be filled automatically, without writing it on the insert statement. In EF with SQL Server, the properties whose match with Identity columns, will be filled after invoking SaveChanges method. In Oracle DB, there is no Identity Property, but there is something similar. Sequences Sequences are DB objects, that allow to create auto increment, but there are not related directly to a Table. The syntax is as follows: name, min value, max value and begin value. 1: CREATE SEQUENCE nombre_secuencia 2: INCREMENT BY numero_incremento 3: START WITH numero_por_el_que_empezara 4: MAXVALUE valor_maximo | NOMAXVALUE 5: MINVALUE valor_minimo | NOMINVALUE 6: CYCLE | NOCYCLE 7: ORDER | NOORDER 8:    How to get sequence value? To obtain the next val from the sequence: 1: SELECT nb_secuencia.Nextval 2: From Dual Due to there is no direct way to indicate that a column is related to a sequence, there is several ways to imitate the behavior: Use a Trigger (DB), Use Stored Procedures or Functions(…) or my particularly option. EF model, only, imports Table Objects, Stored Procedures or Functions, but not sequences. By that, I decide to create my own extension Method to invoke Next Val from a sequence: 1: public static class EFSequence 2: { 3: public static int GetNextValue(this ObjectContext contexto, string SequenceName) 4: { 5: string Connection = ConfigurationManager.ConnectionStrings["JTorrecillaEntities2"].ConnectionString; 6: Connection=Connection.Substring(Connection.IndexOf(@"connection string=")+19); 7: Connection = Connection.Remove(Connection.Length - 1, 1); 8: using (IDbConnection con = new Oracle.DataAccess.Client.OracleConnection(Connection)) 9: { 10: using (IDbCommand cmd = con.CreateCommand()) 11: { 12: con.Open(); 13: cmd.CommandText = String.Format("Select {0}.nextval from DUAL", SequenceName); 14: return Convert.ToInt32(cmd.ExecuteScalar()); 15: } 16: } 17:  18: } 19: } This Object Context’s extension method are going to invoke a query with the Sequence indicated by parameter. It takes the connection strings from the App settings, removing the meta data, that was created by VS when generated the EF model. And then, returns the next value from the Sequence. The next value of a Sequence is unique, by that, when some concurrent users are going to create records in the DB using the sequence will not get duplicates. This is my own implementation, I know that it could be several ways to do and better ways. If I find any other way, I promise to post it. To use the example is needed to add a reference to the Oracle (ODP.NET) dll.

    Read the article

  • Eager/Lazy loaded member always empty with JPA one-to-many relationship

    - by Kaleb Pederson
    I have two entities, a User and Role with a one-to-many relationship from user to role. Here's what the tables look like: mysql> select * from User; +----+-------+----------+ | id | name | password | +----+-------+----------+ | 1 | admin | admin | +----+-------+----------+ 1 row in set (0.00 sec) mysql> select * from Role; +----+----------------------+---------------+----------------+ | id | description | name | summary | +----+----------------------+---------------+----------------+ | 1 | administrator's role | administrator | Administration | | 2 | editor's role | editor | Editing | +----+----------------------+---------------+----------------+ 2 rows in set (0.00 sec) And here's the join table that was created: mysql> select * from User_Role; +---------+----------+ | User_id | roles_id | +---------+----------+ | 1 | 1 | | 1 | 2 | +---------+----------+ 2 rows in set (0.00 sec) And here's the subset of orm.xml that defines the tables and relationships: <entity class="User" name="User"> <table name="User" /> <attributes> <id name="id"> <generated-value strategy="AUTO" /> </id> <basic name="name"> <column name="name" length="100" unique="true" nullable="false"/> </basic> <basic name="password"> <column length="255" nullable="false" /> </basic> <one-to-many name="roles" fetch="EAGER" target-entity="Role" /> </attributes> </entity> <entity class="Role" name="Role"> <table name="Role" /> <attributes> <id name="id"> <generated-value strategy="AUTO"/> </id> <basic name="name"> <column name="name" length="40" unique="true" nullable="false"/> </basic> <basic name="summary"> <column name="summary" length="100" nullable="false"/> </basic> <basic name="description"> <column name="description" length="255"/> </basic> </attributes> </entity> Yet, despite that, when I retrieve the admin user, I get back an empty collection. I'm using Hibernate as my JPA provider and it shows the following debug SQL: select user0_.id as id8_, user0_.name as name8_, user0_.password as password8_ from User user0_ where user0_.name=? limit ? When the one-to-many mapping is lazy loaded, that's the only query that's made. This correctly retrieves the one admin user. I changed the relationship to use eager loading and then the following query is made in addition to the above: select roles0_.User_id as User1_1_, roles0_.roles_id as roles2_1_, role1_.id as id9_0_, role1_.description as descript2_9_0_, role1_.name as name9_0_, role1_.summary as summary9_0_ from User_Role roles0_ left outer join Role role1_ on roles0_.roles_id=role1_.id where roles0_.User_id=? Which results in the following results: +----------+-----------+--------+----------------------+---------------+----------------+ | User1_1_ | roles2_1_ | id9_0_ | descript2_9_0_ | name9_0_ | summary9_0_ | +----------+-----------+--------+----------------------+---------------+----------------+ | 1 | 1 | 1 | administrator's role | administrator | Administration | | 1 | 2 | 2 | editor's role | editor | Editing | +----------+-----------+--------+----------------------+---------------+----------------+ 2 rows in set (0.00 sec) Hibernate obviously knows about the roles, yet getRoles() still returns an empty collection. Hibernate also recognized the relationship sufficiently to put the data in the first place. What problems can cause these symptoms?

    Read the article

  • Approaches for generic, compile-time safe lazy-load methods

    - by Aaronaught
    Suppose I have created a wrapper class like the following: public class Foo : IFoo { private readonly IFoo innerFoo; public Foo(IFoo innerFoo) { this.innerFoo = innerFoo; } public int? Bar { get; set; } public int? Baz { get; set; } } The idea here is that the innerFoo might wrap data-access methods or something similarly expensive, and I only want its GetBar and GetBaz methods to be invoked once. So I want to create another wrapper around it, which will save the values obtained on the first run. It's simple enough to do this, of course: int IFoo.GetBar() { if ((Bar == null) && (innerFoo != null)) Bar = innerFoo.GetBar(); return Bar ?? 0; } int IFoo.GetBaz() { if ((Baz == null) && (innerFoo != null)) Baz = innerFoo.GetBaz(); return Baz ?? 0; } But it gets pretty repetitive if I'm doing this with 10 different properties and 30 different wrappers. So I figured, hey, let's make this generic: T LazyLoad<T>(ref T prop, Func<IFoo, T> loader) { if ((prop == null) && (innerFoo != null)) prop = loader(innerFoo); return prop; } Which almost gets me where I want, but not quite, because you can't ref an auto-property (or any property at all). In other words, I can't write this: int IFoo.GetBar() { return LazyLoad(ref Bar, f => f.GetBar()); // <--- Won't compile } Instead, I'd have to change Bar to have an explicit backing field and write explicit getters and setters. Which is fine, except for the fact that I end up writing even more redundant code than I was writing in the first place. Then I considered the possibility of using expression trees: T LazyLoad<T>(Expression<Func<T>> propExpr, Func<IFoo, T> loader) { var memberExpression = propExpr.Body as MemberExpression; if (memberExpression != null) { // Use Reflection to inspect/set the property } } This plays nice with refactoring - it'll work great if I do this: return LazyLoad(f => f.Bar, f => f.GetBar()); But it's not actually safe, because someone less clever (i.e. myself in 3 days from now when I inevitably forget how this is implemented internally) could decide to write this instead: return LazyLoad(f => 3, f => f.GetBar()); Which is either going to crash or result in unexpected/undefined behaviour, depending on how defensively I write the LazyLoad method. So I don't really like this approach either, because it leads to the possibility of runtime errors which would have been prevented in the first attempt. It also relies on Reflection, which feels a little dirty here, even though this code is admittedly not performance-sensitive. Now I could also decide to go all-out and use DynamicProxy to do method interception and not have to write any code, and in fact I already do this in some applications. But this code is residing in a core library which many other assemblies depend on, and it seems horribly wrong to be introducing this kind of complexity at such a low level. Separating the interceptor-based implementation from the IFoo interface by putting it into its own assembly doesn't really help; the fact is that this very class is still going to be used all over the place, must be used, so this isn't one of those problems that could be trivially solved with a little DI magic. The last option I've already thought of would be to have a method like: T LazyLoad<T>(Func<T> getter, Action<T> setter, Func<IFoo, T> loader) { ... } This option is very "meh" as well - it avoids Reflection but is still error-prone, and it doesn't really reduce the repetition that much. It's almost as bad as having to write explicit getters and setters for each property. Maybe I'm just being incredibly nit-picky, but this application is still in its early stages, and it's going to grow substantially over time, and I really want to keep the code squeaky-clean. Bottom line: I'm at an impasse, looking for other ideas. Question: Is there any way to clean up the lazy-loading code at the top, such that the implementation will: Guarantee compile-time safety, like the ref version; Actually reduce the amount of code repetition, like the Expression version; and Not take on any significant additional dependencies? In other words, is there a way to do this just using regular C# language features and possibly a few small helper classes? Or am I just going to have to accept that there's a trade-off here and strike one of the above requirements from the list?

    Read the article

  • Expected time for lazy evaluation with nested functions?

    - by Matt_JD
    A colleague and I are doing a free R course, although I believe this is a more general lazy evaluation issue, and have found a scenario that we have discussed briefly and I'd like to find out the answer from a wider community. The scenario is as follows (pseudo code): wrapper => function(thing) { print => function() { write(thing) } } v = createThing(1, 2, 3) w = wrapper(v) v = createThing(4, 5, 6) w.print() // Will print 4, 5, 6 thing. v = create(7, 8, 9) w.print() // Will print 4, 5, 6 because "thing" has now been evaluated. Another similar situation is as follows: // Using the same function as above v = createThing(1, 2, 3) v = wrapper(v) w.print() // The wrapper function incestuously includes itself. Now I understand why this happens but where my colleague and I differ is on what should happen. My colleague's view is that this is a bug and the evaluation of the passed in argument should be forced at the point it is passed in so that the returned "w" function is fixed. My view is that I would prefer his option myself, but that I realise that the situation we are encountering is down to lazy evaluation and this is just how it works and is more a quirk than a bug. I am not actually sure of what would be expected, hence the reason I am asking this question. I think that function comments could express what will happen, or leave it to be very lazy, and if the coder using the function wants the argument evaluated then they can force it before passing it in. So, when working with lazy evaulation, what is the practice for the time to evaluate an argument passed, and stored, inside a function?

    Read the article

  • Haskell Lazy Evaluation and Reuse

    - by Jonathan Sternberg
    I know that if I were to compute a list of squares in Haskell, I could do this: squares = [ x ** 2 | x <- [1 ..] ] Then when I call squares like this: print $ take 4 squares And it would print out [1.0, 4.0, 9.0, 16.0]. This gets evaluated as [ 1 ** 2, 2 ** 2, 3 ** 2, 4 ** 2 ]. Now since Haskell is functional and the result would be the same each time, if I were to call squares again somewhere else, would it re-evaluate the answers it's already computed? If I were to re-use squares after I had already called the previous line, would it re-calculate the first 4 values? print $ take 5 squares Would it evaluate [1.0, 4.0, 9.0, 16.0, 5 ** 2]?

    Read the article

  • Thread safe lazy contruction of a singleton in C++

    - by pauldoo
    Is there a way to implement a singleton object in C++ that is: Lazily constructed in a thread safe manner (two threads might simultaneously be the first user of the singleton - it should still only be constructed once). Doesn't rely on static variables being constructed beforehand (so the singleton object is itself safe to use during the construction of static variables). (I don't know my C++ well enough, but is it the case that integral and constant static variables are initialized before any code is executed (ie, even before static constructors are executed - their values may already be "initialized" in the program image)? If so - perhaps this can be exploited to implement a singleton mutex - which can in turn be used to guard the creation of the real singleton..) Excellent, it seems that I have a couple of good answers now (shame I can't mark 2 or 3 as being the answer). There appears to be two broad solutions: Use static initialisation (as opposed to dynamic initialisation) of a POD static varible, and implementing my own mutex with that using the builtin atomic instructions. This was the type of solution I was hinting at in my question, and I believe I knew already. Use some other library function like pthread_once or boost::call_once. These I certainly didn't know about - and am very grateful for the answers posted.

    Read the article

  • IconDownloader, problem with lazy downloading

    - by Junior B.
    My problem is simple to be described but it seems to be hard to solve. The problem is loading icons, with a custom class like IconDownloader.m provided by an official example from Apple, avoiding crashes if I release the view. I've added the IconDownloader class to my app, but it's clear that this approach is good only if the tableview is the root. The big problem is when the view is not the root one. F.e: if I start to scroll my second view (the app now load the icons) and, without leaving it the time to finish the download, I go back to root, the app crash because the view that have to be updated with new icons doesn't exist anymore. One possible solution could be implement an OperationQueue in the view, but with this approach I've to stop the queue when I change the view and restart it when I come back and the idea to have N queues don't make me enthusiastic. Anyone found a good solution for this problem?

    Read the article

  • How to lazy load a data structure (python)

    - by Anton Geraschenko
    I have some way of building a data structure (out of some file contents, say): def loadfile(FILE): return # some data structure created from the contents of FILE So I can do things like puppies = loadfile("puppies.csv") # wait for loadfile to work kitties = loadfile("kitties.csv") # wait some more print len(puppies) print puppies[32] In the above example, I wasted a bunch of time actually reading kitties.csv and creating a data structure that I never used. I'd like to avoid that waste without constantly checking if not kitties whenever I want to do something. I'd like to be able to do puppies = lazyload("puppies.csv") # instant kitties = lazyload("kitties.csv") # instant print len(puppies) # wait for loadfile print puppies[32] So if I don't ever try to do anything with kitties, loadfile("kitties.csv") never gets called. Is there some standard way to do this? After playing around with it for a bit, I produced the following solution, which appears to work correctly and is quite brief. Are there some alternatives? Are there drawbacks to using this approach that I should keep in mind? class lazyload: def __init__(self,FILE): self.FILE = FILE self.F = None def __getattr__(self,name): if not self.F: print "loading %s" % self.FILE self.F = loadfile(self.FILE) return object.__getattribute__(self.F, name) What might be even better is if something like this worked: class lazyload: def __init__(self,FILE): self.FILE = FILE def __getattr__(self,name): self = loadfile(self.FILE) # this never gets called again # since self is no longer a # lazyload instance return object.__getattribute__(self, name) But this doesn't work because self is local. It actually ends up calling loadfile every time you do anything.

    Read the article

  • ExtJS (4.0) dynamic / lazy loading

    - by Paul
    Given a border layout with a west (navigation) and a center region. Let say I click on topic A in the west region, I want to replace (replace as in 'delete last topic') the center region with 'extjs' program code named topic_a.js I succeed in loading with this code: dynamicPanel = new Ext.Component({ loader: { url: '/www/file.htm', renderer: 'html', autoLoad: true, scripts: true } }); var oMainContainer = Ext.getCmp('maincontainer'); oMainContainer.show(); oMainContainer.add(dynamicPanel); But calling this the second time 'adds' things up in the center region and of course fails short in 'deleting', what would be a good approach?

    Read the article

  • C#: System.Lazy&lt;T&gt; and the Singleton Design Pattern

    - by James Michael Hare
    So we've all coded a Singleton at one time or another.  It's a really simple pattern and can be a slightly more elegant alternative to global variables.  Make no mistake, Singletons can be abused and are often over-used -- but occasionally you find a Singleton is the most elegant solution. For those of you not familiar with a Singleton, the basic Design Pattern is that a Singleton class is one where there is only ever one instance of the class created.  This means that constructors must be private to avoid users creating their own instances, and a static property (or method in languages without properties) is defined that returns a single static instance. 1: public class Singleton 2: { 3: // the single instance is defined in a static field 4: private static readonly Singleton _instance = new Singleton(); 5:  6: // constructor private so users can't instantiate on their own 7: private Singleton() 8: { 9: } 10:  11: // read-only property that returns the static field 12: public static Singleton Instance 13: { 14: get 15: { 16: return _instance; 17: } 18: } 19: } This is the most basic singleton, notice the key features: Static readonly field that contains the one and only instance. Constructor is private so it can only be called by the class itself. Static property that returns the single instance. Looks like it satisfies, right?  There's just one (potential) problem.  C# gives you no guarantee of when the static field _instance will be created.  This is because the C# standard simply states that classes (which are marked in the IL as BeforeFieldInit) can have their static fields initialized any time before the field is accessed.  This means that they may be initialized on first use, they may be initialized at some other time before, you can't be sure when. So what if you want to guarantee your instance is truly lazy.  That is, that it is only created on first call to Instance?  Well, there's a few ways to do this.  First we'll show the old ways, and then talk about how .Net 4.0's new System.Lazy<T> type can help make the lazy-Singleton cleaner. Obviously, we could take on the lazy construction ourselves, but being that our Singleton may be accessed by many different threads, we'd need to lock it down. 1: public class LazySingleton1 2: { 3: // lock for thread-safety laziness 4: private static readonly object _mutex = new object(); 5:  6: // static field to hold single instance 7: private static LazySingleton1 _instance = null; 8:  9: // property that does some locking and then creates on first call 10: public static LazySingleton1 Instance 11: { 12: get 13: { 14: if (_instance == null) 15: { 16: lock (_mutex) 17: { 18: if (_instance == null) 19: { 20: _instance = new LazySingleton1(); 21: } 22: } 23: } 24:  25: return _instance; 26: } 27: } 28:  29: private LazySingleton1() 30: { 31: } 32: } This is a standard double-check algorithm so that you don't lock if the instance has already been created.  However, because it's possible two threads can go through the first if at the same time the first time back in, you need to check again after the lock is acquired to avoid creating two instances. Pretty straightforward, but ugly as all heck.  Well, you could also take advantage of the C# standard's BeforeFieldInit and define your class with a static constructor.  It need not have a body, just the presence of the static constructor will remove the BeforeFieldInit attribute on the class and guarantee that no fields are initialized until the first static field, property, or method is called.   1: public class LazySingleton2 2: { 3: // because of the static constructor, this won't get created until first use 4: private static readonly LazySingleton2 _instance = new LazySingleton2(); 5:  6: // Returns the singleton instance using lazy-instantiation 7: public static LazySingleton2 Instance 8: { 9: get { return _instance; } 10: } 11:  12: // private to prevent direct instantiation 13: private LazySingleton2() 14: { 15: } 16:  17: // removes BeforeFieldInit on class so static fields not 18: // initialized before they are used 19: static LazySingleton2() 20: { 21: } 22: } Now, while this works perfectly, I hate it.  Why?  Because it's relying on a non-obvious trick of the IL to guarantee laziness.  Just looking at this code, you'd have no idea that it's doing what it's doing.  Worse yet, you may decide that the empty static constructor serves no purpose and delete it (which removes your lazy guarantee).  Worse-worse yet, they may alter the rules around BeforeFieldInit in the future which could change this. So, what do I propose instead?  .Net 4.0 adds the System.Lazy type which guarantees thread-safe lazy-construction.  Using System.Lazy<T>, we get: 1: public class LazySingleton3 2: { 3: // static holder for instance, need to use lambda to construct since constructor private 4: private static readonly Lazy<LazySingleton3> _instance 5: = new Lazy<LazySingleton3>(() => new LazySingleton3()); 6:  7: // private to prevent direct instantiation. 8: private LazySingleton3() 9: { 10: } 11:  12: // accessor for instance 13: public static LazySingleton3 Instance 14: { 15: get 16: { 17: return _instance.Value; 18: } 19: } 20: } Note, you need your lambda to call the private constructor as Lazy's default constructor can only call public constructors of the type passed in (which we can't have by definition of a Singleton).  But, because the lambda is defined inside our type, it has access to the private members so it's perfect. Note how the Lazy<T> makes it obvious what you're doing (lazy construction), instead of relying on an IL generation side-effect.  This way, it's more maintainable.  Lazy<T> has many other uses as well, obviously, but I really love how elegant and readable it makes the lazy Singleton.

    Read the article

  • Hidden divs for "lazy javascript" loading? Possible security/other issues?

    - by xyld
    I'm curious about people's opinion's and thoughts about this situation. The reason I'd like to lazy load javascript is because of performance. Loading javascript at the end of the body reduces the browser blocking and ends up with much faster page loads. But there is some automation I'm using to generate the html (django specifically). This automation has the convenience of allowing forms to be built with "Widgets" that output content it needs to render the entire widget (extra javascript, css, ...). The problem is that the widget wants to output javascript immediately into the middle of the document, but I want to ensure all javascript loads at the end of the body. When the following widget is added to a form, you can see it renders some <script>...</script> tags: class AutoCompleteTagInput(forms.TextInput): class Media: css = { 'all': ('css/jquery.autocomplete.css', ) } js = ( 'js/jquery.bgiframe.js', 'js/jquery.ajaxQueue.js', 'js/jquery.autocomplete.js', ) def render(self, name, value, attrs=None): output = super(AutoCompleteTagInput, self).render(name, value, attrs) page_tags = Tag.objects.usage_for_model(DataSet) tag_list = simplejson.dumps([tag.name for tag in page_tags], ensure_ascii=False) return mark_safe(u'''<script type="text/javascript"> jQuery("#id_%s").autocomplete(%s, { width: 150, max: 10, highlight: false, scroll: true, scrollHeight: 100, matchContains: true, autoFill: true }); </script>''' % (name, tag_list,)) + output What I'm proposing is that if someone uses a <div class=".lazy-js">...</div> with some css (.lazy-js { display: none; }) and some javascript (jQuery('.lazy-js').each(function(index) { eval(jQuery(this).text()); }), you can effectively force all javascript to load at the end of page load: class AutoCompleteTagInput(forms.TextInput): class Media: css = { 'all': ('css/jquery.autocomplete.css', ) } js = ( 'js/jquery.bgiframe.js', 'js/jquery.ajaxQueue.js', 'js/jquery.autocomplete.js', ) def render(self, name, value, attrs=None): output = super(AutoCompleteTagInput, self).render(name, value, attrs) page_tags = Tag.objects.usage_for_model(DataSet) tag_list = simplejson.dumps([tag.name for tag in page_tags], ensure_ascii=False) return mark_safe(u'''<div class="lazy-js"> jQuery("#id_%s").autocomplete(%s, { width: 150, max: 10, highlight: false, scroll: true, scrollHeight: 100, matchContains: true, autoFill: true }); </div>''' % (name, tag_list,)) + output Nevermind all the details of my specific implementation (the specific media involved), I'm looking for a consensus on whether the method of using lazy-loaded javascript through hidden a hidden tags can pose issues whether security or other related? One of the most convenient parts about this is that it follows the DRY principle rather well IMO because you don't need to hack up a specific lazy-load for each instance in the page. It just "works". UPDATE: I'm not sure if django has the ability to queue things (via fancy template inheritance or something?) to be output just before the end of the </body>?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >