Search Results

Search found 195 results on 8 pages for 'annotate'.

Page 7/8 | < Previous Page | 3 4 5 6 7 8  | Next Page >

  • ProgrammingError when aggregating over an annotated & grouped Django ORM query

    - by ento
    I'm trying to construct a query to get the "average, maximum, minimum number of items purchased by a single user". The data source is this simple sales record table: class SalesRecord(models.Model): id = models.IntegerField(primary_key=True) user_id = models.IntegerField() product_code = models.CharField() price = models.IntegerField() created_at = models.DateTimeField() A new record is inserted into this table for every item purchased by a user. Here's my attempt at building the query: q = SalesRecord.objects.all() q = q.values('user_id').annotate( # group by user and count the # of records count=Count('id'), # (= # of items) ).order_by() result = q.aggregate(Max('count'), Min('count'), Avg('count')) When I try to execute the code, a ProgrammingError is raised at the last line: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM (SELECT sales_records.user_id AS user_id, COUNT(sales_records.`' at line 1") Django's error screen shows that the SQL is SELECT FROM (SELECT `sales_records`.`player_id` AS `player_id`, COUNT(`sales_records`.`id`) AS `count` FROM `sales_records` WHERE (`sales_records`.`created_at` >= %s AND `sales_records`.`created_at` <= %s ) GROUP BY `sales_records`.`player_id` ORDER BY NULL) subquery It's not selecting anything! Can someone please show me the right way to do this? Hacking Django I've found that clearing the cache of selected fields in django.db.models.sql.BaseQuery.get_aggregation() seems to solve the problem. Though I'm not really sure this is a fix or a workaround. @@ -327,10 +327,13 @@ # Remove any aggregates marked for reduction from the subquery # and move them to the outer AggregateQuery. + self._aggregate_select_cache = None + self.aggregate_select_mask = None for alias, aggregate in self.aggregate_select.items(): if aggregate.is_summary: query.aggregate_select[alias] = aggregate - del obj.aggregate_select[alias] + if alias in obj.aggregate_select: + del obj.aggregate_select[alias] ... yields result: {'count__max': 267, 'count__avg': 26.2563, 'count__min': 1}

    Read the article

  • How should I handle persistence in a Java MUD? OptimisticLockException handling

    - by Chase
    I'm re-implementing a old BBS MUD game in Java with permission from the original developers. Currently I'm using Java EE 6 with EJB Session facades for the game logic and JPA for the persistence. A big reason I picked session beans is JTA. I'm more experienced with web apps in which if you get an OptimisticLockException you just catch it and tell the user their data is stale and they need to re-apply/re-submit. Responding with "try again" all the time in a multi-user game would make for a horrible experience. Given that I'd expect several people to be targeting a single monster during a fight I think the chance of an OptimisticLockException would be high. My view code, the part presenting a telnet CLI, is the EJB client. Should I be catching the PersistenceExceptions and TransactionRolledbackLocalExceptions and just retrying? How do you decide when to stop? Should I switch to pessimistic locking? Is persisting after every user command overkill? Should I be loading the entire world in RAM and dumping the state every couple of minutes? Do I make my session facade a EJB 3.1 singleton which would function as a choke point and therefore eliminating the need to do any type of JPA locking? EJB 3.1 singletons function as a multiple reader/single writer design (you annotate the methods as readers and writers). Basically, what is the best design and java persistence API for highly concurrent data changes in an application where it is not acceptable to present resubmit/retry prompts to the user?

    Read the article

  • Junit: splitting integration test and Unit tests.

    - by jeff porter
    Hello all, I've inherited a load of Junit test, but these tests (apart from most not working) are a mixture of actual unit test and integration tests (requiring external systems, db etc). So I'm trying to think of a way to actually separate them out, so that I can run the unit test nice and quickly and the integration tests after that. The options are.. 1: Split them into separate directories. 2: Move to Junit4 and annotate the classes to separate them. 3: Use a file naming convention to tell what a class is , i.e. AdapterATest and AdapterAIntergrationTest. 3 has the issue that Eclipse has the option to "Run all tests in the selected project/package or folder". So it would make it very hard to just run the integration tests. 2: runs the risk that developers might start writing integration tests in unit test classes and it just gets messy. 1: Seems like the neatest solution, but my gut says there must be a better solution out there. So that is my question, how do you lot break apart integration tests and proper unit tests?

    Read the article

  • Is it possible to handle User Defined Exception using JAX WS Dispatch API ?

    - by snowflake
    Hello, I'm performing dynamic webservices call using following code snippet: JAXBContext jc = getJAXBContext(requestClass, responseClass, jaxbContextExtraClasses); Dispatch<Object> dispatch = service.createDispatch(portQName, jc, Service.Mode.PAYLOAD); Object requestValue = getRequestValue(requestClass, pOrderedParameters); JAXBElement<?> request = new JAXBElement(new QName(serviceQNameStr, pOperationName), requestValue.getClass(), null, requestValue); Object tmpResponse = dispatch.invoke(request); Invocation works perfectly, except if I add a user defined exception on the service (a basic UserException extends java.lang.Exception). First I get: javax.xml.bind.UnmarshalException: unexpected element (uri:"http://schemas.xmlsoap.org/soap/envelope/", local:"Fault"). Expected elements are <{http://my.namespace/}myMethod,<{http://my.namespace/}myResponse Then I added the UserException_Exception JAX-WS generated type to my JAXB Context, and then get: Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions java.lang.StackTraceElement does not have a no-arg default constructor. this problem is related to the following location: at java.lang.StackTraceElement at public java.lang.StackTraceElement[] java.lang.Throwable.getStackTrace() at java.lang.Throwable at java.lang.Exception Only solution available I found are: dispatch directly a Soap message and handle Soap fault directly (this is the way Jboss JAX-WS implementation performs a standard JAX-WS call using services interfaces). This is not an available solution for me, I want to use a high level implementation (the more I get close to Soap message the less dynamic my code can be) usage of JAXBRIContext.ANNOTATION_READER, which is implementation specific and not an available solution for me, in order to annotate annotates java.lang.Exception as @XmlTransient The service with a user defined exception performs well using the JAX-WS generated standard client stubs and using a tool such Soap UI. Problem occurs in deserialization of the message when I have no user defined exception artifact in the JAXB context, and during invocation when I add those non JAXB compatible artifacts in the JAXB context. I'm usign Jboss WS webservice stack within Jboss 4.2.3.GA Any elegant solution to this problem is welcomed !

    Read the article

  • Intercepting method with Spring AOP using only annotations

    - by fish
    In my Spring context file I have something like this: <bean id="userCheck" class="a.b.c.UserExistsCheck"/> <aop:config> <aop:aspect ref="userCheck"> <aop:pointcut id="checkUser" expression="execution(* a.b.c.d.*.*(..)) &amp;&amp; args(a.b.c.d.RequestObject)"/> <aop:around pointcut-ref="checkUser" method="checkUser"/> </aop:aspect> </aop:config> a.b.c.UserExistsCheck looks like this: @Aspect public class UserExistsCheck { @Autowired private UserInformation userInformation; public Object checkUser(ProceedingJoinPoint pjp) throws Throwable { int userId = ... //get it from the RequestObject passed as a parameter if (userExists(userId)) { return pjp.proceed(); } else { return new ResponseObject("Invalid user); } } And the class that is being intercepted with this stuff looks like this: public class Klazz { public ResponseObject doSomething(RequestObject request) {...} } This works. UserExistCheck is executed as desired before the call is passed to Klazz. The problem is that this is the only way I got it working. To get this working by using annotations instead of the context file seems to be just too much for my small brain. So... how exactly should I annotate the methods in UserExistsCheck and Klazz? And do I still need something else too? Another class? Still something in the context file?

    Read the article

  • Mathematical annotations in a PDF file

    - by kvaruni
    I like to annotate papers I read in a digital way. Numerous programs exist to help in this process. For example, on OS X one can use programs such as Skim or even Preview. However, making annotations is dreadful when one wishes to add mathematical annotations, such as formulas or greek letters. A cumbersome "solution" is to select the desired symbol one by one using the Special Characters palette, though this considerably slows down the annotation process. Is there any way to add mathematical annotations to a PDF? The only two limitations that I would impose on a solution is that 1) the mathematical text needs to be selectable, i.e. it must be text and 2) I want to limit the number of programs I need to make the process as painless as possible. Some of the more promising solutions I have tried include generating LaTeX with LaTeXiT, but it seems to be impossible to add a PDF on top of another PDF. Another attempt was to use jsMath to generate the symbols and copy-paste these as annotation using one of the jsMath fonts. This results in unreadable, incorrect characters.

    Read the article

  • How to preprocess text to do OCR error correction

    - by eaglefarm
    Here is what I'm trying to accomplish: I need to get a several large text files from a computer that is not networked and has no other output except a printer. I tried printing the text, then scanning the printout with OCR to recover the text on another computer but the OCR gets lots of errors (1 vs l, o vs 0, O vs D, etc). To solve this I am thinking of writing a program to process (annotate?) the text file, before printing it, so that the errors can be corrected from the text output of the OCR program. For example, for 1 (number one) vs l (letter L), I could change the text like this: sample inserting \nnn after characters that are frequently wrong in the OCR results: sampl\108e Then I can write another program to examine the file, looking for \nnn and check the character before the \nnn (where nnn is the ascii code in decimal) and fix it if necessary. Of course the program will have to recognize that the \nnn may have errors too but at least it knows that the nnn are digits and can easily correct them. I think I would add a CRC on each line so that any line that isn't corrected perfectly can be flagged as having a problem. Has anyone done anything like this? If there is an existing way of doing this I'd rather not reinvent the wheel. Or any suggestions for annotation format that would help solve this problem would be helpful too.

    Read the article

  • JAXB - Beans to XSD or XSD to beans?

    - by bajafresh4life
    I have an existing data model. I would like to express this data model in terms of XML. It looks like I have two options if I'm to use JAXB: Create an XSD that mirrors my data model, and use xjc to create binding objects. Marshalling and unmarshalling will involve creating a "mapping" class that would take my existing data objects and map them to the objects that xjc created. For example, in my data model I have a Doc class, and JAXB would create another Doc class with basically the same exact fields, and I would have to map from my Doc class to xjc's Doc class. Annotate my existing data model with JAXB annotations, and use schemagen to generate an XSD from my annotated classes. I can see advantanges and disadvantages of both approaches. It seems that most people using JAXB start with the XSD file. It makes sense that the XSD should be the gold standard truth, since it expresses the data model in a truly cross-platform way. I'm inclined to start with the XSD first, but it seems icky that I have to write and maintain a separate mapping class that shuttles data in between my world and JAXB world. Any recommendations?

    Read the article

  • django: grouping in an order_by query?

    - by AP257
    Hi all, I want to allocate rankings to users, based on a points field. Easy enough you'd think with an order_by query. But how do I deal with the situation where two users have the same number of points and need to share the same ranking? Should I use annotate to find users with the same number of points? My current code, and a pseudocode description of what I'd like to do, are below. top_users = User.objects.filter(problem_user=False).order_by('-points_total') # Wrong - in pseudocode, this should be # Get the highest points_total, find all the users with that points_total, # if there is more than one user, set status to 'Joint first prize', # otherwise set status to 'First prize' top_users[0].status = "First prize" if (top_users[1]): top_users[1].status = "Second prize" if (top_users[2]): top_users[2].status = "Third prize" if (top_users[3]): top_users[3:].status = "Highly commended" The code above doesn't deal with the situation where two users have the same number of points and need to share second prize. I guess I need to create a query that looks for unique values of points_total, and does some kind of nested ranking? It also doesn't cope with the fact that sometimes there are fewer than 4 users - does anyone know how I can do (in pseudocode) 'if top_users[1] is not null...' in Python?

    Read the article

  • How can I filter these Django records?

    - by mipadi
    I have a set of Django models as shown in the following diagram (the names of the reverse relationships are shown in the yellow bubbles): In each relationship, a Person may have 0 or more of the items. Additionally, the slug field is (unfortunately) not unique; multiple Person records may have the same slug fields. Essentially these records are duplicates. I want to obtain a list of all records that meet the following criteria: All duplicate records (that is, having the same slug) with at least one Entry OR at least one Audio OR at least one Episode OR at least one Article. So far, I have the following query: Person.objects.values('slug').annotate(num_records=Count('slug')).filter(num_records__gt=1) This groups all records by slug, then adds a num_records attribute that says how many records have that slug, but the additional filtering is not performed (and I don't even know if this would work right anyway, since, given a set of duplicate records, one may have, e.g., and Entry and the other may have an Article). In a nutshell, I want to find all duplicate records and collapse them, along with their associated models, into one record. What's the best way to do this with Django?

    Read the article

  • Help regarding composite pattern with hibernate

    - by molleman
    Hello, So i am stuck, i am creating a gwt web application, i will be using a tree(gwt Tree and TreeItems) structure to show a list of folders(class Folder) and files(class FileLocation), the folder and filelocation class will all implement a Hierarchy interface basing the classes on the composite pattern. but i am using hibernate to store my data , and i am using annotations for the mapping of the data to the database. my trouble is i do not know how to annotate my interface. have any of you guys used the composite pattern while persisting the data with hibernate public interface Hierarchy(){ // a few abstract methods that will be implemented by the sub classes } @Entity @Table() public class Folder extends Hierarchy implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "folder_id", updatable = false, nullable = false) private int id; @OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER) @JoinTable(name = "FOLDER_FILELOCATION", joinColumns = { @JoinColumn(name = "folder_id") }, inverseJoinColumns = { @JoinColumn(name = "file_information_id") }) private List<Hierarchy> children = new ArrayList<Hierarchy>() ; @Column(name = "folder_name") private String folderName; @Column(name = "tree_item") private TreeItem item; @Column (name = "parent") private Hierarchy parent; @Entity @Table(name = "FILE_INFORMATION_TABLE") public class FileInformation extends Hierarchy implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "file_information_id", updatable = false, nullable = false) private int fiId; @Column (name = "location") private String location; @Column(name = "tree_item") private TreeItem item; @Column (name = "parent") private Hierarchy parent;

    Read the article

  • Disassembler that tracks what value is where

    - by Martin C. Martin
    So lately I've been looking at the disassembly of my C++ code, and having to manually track what's in each register, like this: 95: 48 8b 16 mov (%rsi),%rdx ; %rdx = raggedCross.sink 98: 48 8b 42 38 mov 0x38(%rdx),%rax ; %rax = sink.table 9c: 8b 4a 10 mov 0x10(%rdx),%ecx ; %ecx = sink.baseCol 9f: 48 8b 70 50 mov 0x50(%rax),%rsi ; %rsi = table.starts a3: 89 c8 mov %ecx,%eax ; %eax = baseCol a5: 83 c1 1c add $0x1c,%ecx ; %ecx = baseCol + 1 And so on. The comments are mine, added by hand, from looking up the offset of various fields (e.g. sink, table, baseCol, starts) in the C++ classes. It's straight forward to do, but tedius and time consuming: the perfect thing for a program to be doing. gdb seems to know the offset of various fields within a struct: I can do &((Table *)0x1200)-starts and it tells the the right address. So, this information is around. Is there some disassembler that can use this info to annotate the code for me? Failing that, I could write my own. Where does gdb get the offsets?

    Read the article

  • Is it possible to add JPA annotation to superclass instance variables?

    - by Kristofer Borgstrom
    Hi, I am creating entities that are the same for two different tables. In order do table mappings etc. different for the two entities but only have the rest of the code in one place - an abstract superclass. The best thing would be to be able to annotate generic stuff such as column names (since the will be identical) in the super class but that does not work because JPA annotations are not inherited by child classes. Here is an example: public abstract class MyAbstractEntity { @Column(name="PROPERTY") //This will not be inherited and is therefore useless here protected String property; public String getProperty() { return this.property; } //setters, hashCode, equals etc. methods } Which I would like to inherit and only specify the child-specific stuff, like annotations: @Entity @Table(name="MY_ENTITY_TABLE") public class MyEntity extends MyAbstractEntity { //This will not work since this field does not override the super class field, thus the setters and getters break. @Column(name="PROPERTY") protected String property; } Any ideas or will I have to create fields, getters and setters in the child classes? Thanks, Kris

    Read the article

  • NullPointerException in NetBeans 6.5 IDE itself

    - by titaniumdecoy
    When I use NetBeans for almost any task (in particular, attempting to open a project), a red minus sign in the bottom right corner of the IDE starts blinking and I get the following NullPointerException error when I click it. Unfortunately I cannot reinstall NetBeans since I am using a shared computer lab account. java.lang.NullPointerException at org.openide.util.Exceptions.attachMessage(Unknown Source) at org.netbeans.modules.project.ant.Util$ErrHandler.annotate(Unknown Source) at org.netbeans.modules.project.ant.Util$ErrHandler.fatalError(Unknown Source) at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:177) at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:388) at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1414) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:925) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648) at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:807) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107) at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:225) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283) at org.openide.xml.XMLUtil.parse(Unknown Source) at org.netbeans.modules.project.ant.AntBasedProjectFactorySingleton.loadProjectXml(Unknown Source) at org.netbeans.modules.project.ant.AntBasedProjectFactorySingleton.loadProject(Unknown Source) at org.netbeans.api.project.ProjectManager.createProject(Unknown Source) at org.netbeans.api.project.ProjectManager.access$300(Unknown Source) at org.netbeans.api.project.ProjectManager$2.run(Unknown Source) at org.netbeans.api.project.ProjectManager$2.run(Unknown Source) at org.openide.util.Mutex.readAccess(Unknown Source) at org.netbeans.api.project.ProjectManager.findProject(Unknown Source) at org.netbeans.modules.project.ui.OpenProjectList.fileToProject(Unknown Source) at org.netbeans.modules.project.ui.ProjectChooserAccessory$ProjectFileView.run(Unknown Source) at org.openide.util.RequestProcessor$Task.run(Unknown Source) [catch] at org.openide.util.RequestProcessor$Processor.run(Unknown Source) I have recently had problems with going over my disk space quota on this computer lab account. I cleaned up my files and I now have about 10MB free. I'm not sure whether or not this is related to the problem with NetBeans.

    Read the article

  • Using ControllerClassNameHandlerMapping with @Controller and extending AbstractController

    - by whiskerz
    Hey there, actually I thought I was trying something really simple. ControllerClassNameHandlerMapping sounded great to produce a small spring webapp using a very lean configuration. Just annotate the Controller with @Controller, have it extend AbstractController and the configuration shouldn't need more than this <context:component-scan base-package="test.mypackage.controller" /> <bean id="urlMapping" class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" /> to resolve my requests and map them to my controllers. I've mapped the servlet to "*.spring", and calling <approot>/hello.spring All I ever get is an error stating that no mapping was found. If however I extend the MultiActionController, and do something like <approot>/hello/hello.spring it works. Which somehow irritates me, as I would have thought that if that is working, why didn't my first try? Does anyone have any idea? The two controllers I used looked like this @Controller public class HelloController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView modelAndView = new ModelAndView("hello"); modelAndView.addObject("message", "Hello World!"); return modelAndView; } } and @Controller public class HelloController extends MultiActionController { public ModelAndView hello(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView modelAndView = new ModelAndView("hello"); modelAndView.addObject("message", "Hello World!"); return modelAndView; } }

    Read the article

  • Is there a pattern for initializing objects created wth a DI container

    - by Igor Zevaka
    I am trying to get Unity to manage the creation of my objects and I want to have some initialization parameters that are not known until run-time: At the moment the only way I could think of the way to do it is to have an Init method on the interface. interface IMyIntf { void Initialize(string runTimeParam); string RunTimeParam { get; } } Then to use it (in Unity) I would do this: var IMyIntf = unityContainer.Resolve<IMyIntf>(); IMyIntf.Initialize("somevalue"); In this scenario runTimeParam param is determined at run-time based on user input. The trivial case here simply returns the value of runTimeParam but in reality the parameter will be something like file name and initialize method will do something with the file. This creates a number of issues, namely that the Initialize method is available on the interface and can be called multiple times. Setting a flag in the implementation and throwing exception on repeated call to Initialize seems way clunky. At the point where I resolve my interface I don't want to know anything about the implementation of IMyIntf. What I do want, though, is the knowledge that this interface needs certain one time initialization parameters. Is there a way to somehow annotate(attributes?) the interface with this information and pass those to framework when the object is created? Edit: Described the interface a bit more.

    Read the article

  • Return 0 where django quersyet is none

    - by gramware
    I have a django queryset in my views whose values I pack before passing to my template. There is a problem when the queryset returns none since associated values are not unpacked. the quersyet is called comments. Here is my views.py def forums(request ): post_list = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0').order_by('postDate')) user = UserProfile.objects.get(pk=request.session['_auth_user_id']) newpostform = PostForm(request.POST) deletepostform = PostDeleteForm(request.POST) DelPostFormSet = modelformset_factory(forum, exclude=('child','postSubject','postBody','postPoster','postDate','childParentId')) readform = ReadForumForm(request.POST) comments =list( forum.objects.filter(deleted='0').filter(child='1').order_by('childParentId').values('childParentId').annotate(y=Count('childParentId'))) if request.user.is_staff== True : staff = 1 else: staff = 0 staffis = 1 if newpostform.is_valid(): topic = request.POST['postSubject'] poster = request.POST['postPoster'] newpostform.save() return HttpResponseRedirect('/forums') else: newpostform = PostForm(initial = {'postPoster':user.id}) if request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] post_list = list((forum.objects.filter(child='0')&forum.objects.filter(deleted='0')&forum.objects.filter(Q(postSubject__icontains=query)|Q(postBody__icontains=query)|Q(postDate__icontains=query)))or(forum.objects.filter(deleted='0')&forum.objects.filter(Q(postSubject__icontains=query)|Q(postBody__icontains=query)|Q(postDate__icontains=query)).values('childParentId'))) if request.method == 'POST': delpostformset = DelPostFormSet(request.POST) if delpostformset.is_valid(): delpostformset.save() return HttpResponseRedirect('/forums') else: delpostformset = DelPostFormSet(queryset=forum.objects.filter(child='0', deleted='0')) """if readform.is_valid(): user=get_object_or_404(UserProfile.objects.all()) readform.save() else: readform = ReadForumForm()""" post= zip( post_list,comments, delpostformset.forms) paginator = Paginator(post, 10) # Show 10 contacts per page # Make sure page request is an int. If not, deliver first page. try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 # If page request (9999) is out of range, deliver last page of results. try: post = paginator.page(page) except (EmptyPage, InvalidPage): post = paginator.page(paginator.num_pages) return render_to_response('forum.html', {'post':post, 'newpostform': newpostform,'delpost':delpostformset, 'username':user.username, 'comments':comments, 'user':user, },context_instance = RequestContext( request ))

    Read the article

  • Django: Applying Calculations To A Query Set

    - by TheLizardKing
    I have a QuerySet that I wish to pass to a generic view for pagination: links = Link.objects.annotate(votes=Count('vote')).order_by('-created')[:300] This is my "hot" page which lists my 300 latest submissions (10 pages of 30 links each). I want to now sort this QuerySet by an algorithm that HackerNews uses: (p - 1) / (t + 2)^1.5 p = votes minus submitter's initial vote t = age of submission in hours Now because applying this algorithm over the entire database would be pretty costly I am content with just the last 300 submissions. My site is unlikely to be the next digg/reddit so while scalability is a plus it is required. My question is now how do I iterate over my QuerySet and sort it by the above algorithm? For more information, here are my applicable models: class Link(models.Model): category = models.ForeignKey(Category, blank=False, default=1) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) url = models.URLField(max_length=1024, unique=True, verify_exists=True) name = models.CharField(max_length=512) def __unicode__(self): return u'%s (%s)' % (self.name, self.url) class Vote(models.Model): link = models.ForeignKey(Link) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) def __unicode__(self): return u'%s vote for %s' % (self.user, self.link) Notes: I don't have "downvotes" so just the presence of a Vote row is an indicator of a vote or a particular link by a particular user.

    Read the article

  • C++ Declarative Parsing Serialization

    - by Martin York
    Looking at Java and C# they manage to do some wicked processing based on special languaged based anotation (forgive me if that is the incorrect name). In C++ we have two problems with this: 1) There is no way to annotate a class with type information that is accessable at runtime. 2) Parsing the source to generate stuff is way to complex. But I was thinking that this could be done with some template meta-programming to achieve the same basic affect as anotations (still just thinking about it). Like char_traits that are specialised for the different types an xml_traits template could be used in a declaritive way. This traits class could be used to define how a class is serialised/deserialized by specializing the traits for the class you are trying to serialize. Example Thoughs: template<typename T> struct XML_traits { typedef XML_Empty Children; }; template<> struct XML_traits<Car> { typedef boost::mpl::vector<Body,Wheels,Engine> Children; }; template<typename T> std::ostream& Serialize(T const&) { // my template foo is not that strong. // but somthing like this. boost::mpl::for_each<typename XML_Traits<T>::Children,Serialize>(data); } template<> std::ostream& Serialize<XML_Empty>(T const&) { /* Do Nothing */ } My question is: Has anybody seen any projects/decumentation (not just XML) out there that uses techniques like this (template meta-programming) to emulate the concept of annotation used in languges like Java and C# that can then be used in code generation (to effectively automate the task by using a declaritive style). At this point in my research I am looking for more reading material and examples.

    Read the article

  • Firefox extension: How to inject javascript into page and run it?

    - by el griz
    I'm writing a Firefox extension to allow users to annotate any page with text and/or drawings and then save an image of the page including the annotations. Use cases would be clients reviewing web pages, adding feedback to the page, saving the image of this and emailing it back to the web developer or testers taking annotated screenshots of GUI bugs etc. I wrote the annotation/drawing functionality in javascript before developing the extension. This script adds a <canvas> element to the page to draw upon as well as a toolbar (in a <div>) that contains buttons (each <canvas> elements) for the different draw tools e.g. line, box, ellipse, text, etc. This works fine when manually included in a page. I now need a way for the extension to: Inject this script into any page including pages I don't control. This needs to occur when the user invokes the extension, which can be after the page has loaded. Once injected the init() function in this script that adds the canvas and toolbar elements etc. needs to be run somehow, but I can't determine how to call this from the extension. Note that once injected I don't need this script to interact with the extension (as the extension just takes a screenshot of the entire document (and removes the added page elements) when the user presses the save button in the extension chrome).

    Read the article

  • Django: Determining if a user has voted or not

    - by TheLizardKing
    I have a long list of links that I spit out using the below code, total votes, submitted by, the usual stuff but I am not 100% on how to determine if the currently logged in user has voted on a link or not. I know how to do this from within my view but do I need to alter my below view code or can I make use of the way templates work to determine it? I have read http://stackoverflow.com/questions/1528583/django-vote-up-down-method but I don't quite understand what's going on ( and don't need any ofjavascriptery). Models (snippet): class Link(models.Model): category = models.ForeignKey(Category, blank=False, default=1) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) url = models.URLField(max_length=1024, unique=True, verify_exists=True) name = models.CharField(max_length=512) def __unicode__(self): return u'%s (%s)' % (self.name, self.url) class Vote(models.Model): link = models.ForeignKey(Link) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) def __unicode__(self): return u'%s vote for %s' % (self.user, self.link) Views (snippet): def hot(request): links = Link.objects.select_related().annotate(votes=Count('vote')).order_by('-created') for link in links: delta_in_hours = (int(datetime.now().strftime("%s")) - int(link.created.strftime("%s"))) / 3600 link.popularity = ((link.votes - 1) / (delta_in_hours + 2)**1.5) if request.user.is_authenticated(): try: link.voted = Vote.objects.get(link=link, user=request.user) except Vote.DoesNotExist: link.voted = None links = sorted(links, key=lambda x: x.popularity, reverse=True) links = paginate(request, links, 15) return direct_to_template( request, template = 'links/link_list.html', extra_context = { 'links': links, }) The above view actually accomplishes what I need but in what I believe to be a horribly inefficient way. This causes the dreaded n+1 queries, as it stands that's 33 queries for a page containing just 29 links while originally I got away with just 4 queries. I would really prefer to do this using Django's ORM or at least .extra(). Any advice?

    Read the article

  • Need a workaround to filter on related model and aggregated fields in Django

    - by parxier
    I opened a ticket for this problem. In a nutshell here is my model: class Plan(models.Model): cap = models.IntegerField() class Phone(models.Model): plan = models.ForeignKey(Plan, related_name='phones') class Call(models.Model): phone = models.ForeignKey(Phone, related_name='calls') cost = models.IntegerField() I want to run a query like this one: Phone.objects.annotate(total_cost=Sum('calls__cost')).filter(total_cost__gte=0.5*F('plan__cap')) Unfortunately Django generates bad SQL: SELECT "app_phone"."id", "app_phone"."plan_id", SUM("app_call"."cost") AS "total_cost" FROM "app_phone" INNER JOIN "app_plan" ON ("app_phone"."plan_id" = "app_plan"."id") LEFT OUTER JOIN "app_call" ON ("app_phone"."id" = "app_call"."phone_id") GROUP BY "app_phone"."id", "app_phone"."plan_id" HAVING SUM("app_call"."cost") >= 0.5 * "app_plan"."cap" and errors with: ProgrammingError: column "app_plan.cap" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...."plan_id" HAVING SUM("app_call"."cost") >= 0.5 * "app_plan".... Is there any workaround apart from running raw SQL?

    Read the article

  • Can't get gravity to work with RMagick and 'caption'

    - by mph
    I'm using RMagick 2.12.2 with ImageMagick 6.5.6-10 on Snow Leopard. I'm trying to put captions on a collection of photos, and I'm getting the caption to work (i.e. it appears on the image), but I can't get the gravity parameter to work correctly. No matter what I set it to, I end up with some variation on NorthGravity. For instance: Setting it to SouthWestGravity gives me NorthWestGravity. Setting it to SouthEastGravity gives me NorthEastGravity. Setting it to CenterGravity gives me NorthGravity. In other words, I can't get the caption to come down off the top of the image. I'd consider using "annotate," but I need "caption" so the lengthy caption text for each image will wrap. What am I doing wrong? Here's the code: #!/usr/bin/env ruby require "rubygems" require "yaml" require "RMagick" include Magick base_dir = "/Users/mike/Desktop/caption_test" photo_log = File.open("#{base_dir}/photo_log.yaml" ) YAML::load_documents(photo_log) do |doc| caption = doc["photo-caption"] filename = doc["file"] canvas = ImageList.new.from_blob(open("#{base_dir}/#{filename}") { |f| f.read } ) canvas << Magick::Image.read("caption:#{caption}") { self.gravity = SouthWestGravity self.size = "#{canvas.first.columns}" self.font = "Helvetica Neue" self.pointsize = 12 self.background_color = "#fff" }.first canvas.flatten_images.write("#{base_dir}/images/#{filename}") end

    Read the article

  • Django Aggregation Across Reverse Relationship

    - by Tom
    Given these two models: class Profile(models.Model): user = models.ForeignKey(User, unique=True, verbose_name=_('user')) about = models.TextField(_('about'), blank=True) zip = models.CharField(max_length=10, verbose_name='zip code', blank=True) website = models.URLField(_('website'), blank=True, verify_exists=False) class ProfileView(models.Model): profile = models.ForeignKey(Profile) viewer = models.ForeignKey(User, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) I want to get all profiles sorted by total views. I can get a list of profile ids sorted by total views with: ProfileView.objects.values('profile').annotate(Count('profile')).order_by('-profile__count') But that's just a dictionary of profile ids, which means I then have to loop over it and put together a list of profile objects. Which is a number of additional queries and still doesn't result in a QuerySet. At that point, I might as well drop to raw SQL. Before I do, is there a way to do this from the Profile model? ProfileViews are related via a ForeignKey field, but it's not as though the Profile model knows that, so I'm not sure how to tie the two together. As an aside, I realize I could just store views as a property on the Profile model and that may turn out to be what I do here, but I'm still interested in learning how to better use the Aggregation functions.

    Read the article

  • How can I qualify an autowired property with a variable from a config file using annotations?

    - by jiggy
    My specific problem is that I have configured two beans that implement the same interface and I have a third bean that has a property of that interface's type. I inject the property using a config property. So, assuming RemoteDataSource and LocalDataSource implement IDataSource and dao1 has a property of type IDataSource, my XML config might look like this: <bean id="datasource1" class="com.foo.RemoteDataSource"> <property name="url">${url}</property> </bean> <bean id="datasource2" class="com.foo.LocalDataSource"> <property name="path">${filepath}</property> </bean> <bean id="dao1" class="com.foo.MyDAO"> <property name="dataSource">${datasource}</property> </bean> With url, filepath and datasource being defined in an included properties file. We are now making a push for annotation-driven configuration and I'm not sure how to annotate my dao to put the data source configured in the property file. I want to do something like this, but it is evidently not allowed: @Autowired @Qualifier("${datasource}") public void setDataSource(IDataSource datasource) {...}

    Read the article

< Previous Page | 3 4 5 6 7 8  | Next Page >