Search Results

Search found 13135 results on 526 pages for 'actor model'.

Page 146/526 | < Previous Page | 142 143 144 145 146 147 148 149 150 151 152 153  | Next Page >

  • Generating JavaScript in C# and subsequent testing

    - by Codebrain
    We are currently developing an ASP.NET MVC application which makes heavy use of attribute-based metadata to drive the generation of JavaScript. Below is a sample of the type of methods we are writing: function string GetJavascript<T>(string javascriptPresentationFunctionName, string inputId, T model) { return @"function updateFormInputs(value){ $('#" + inputId + @"_SelectedItemState').val(value); $('#" + inputId + @"_Presentation').val(value); } function clearInputs(){ " + helper.ClearHiddenInputs<T>(model) + @" updateFormInputs(''); } function handleJson(json){ clearInputs(); " + helper.UpdateHiddenInputsWithJson<T>("json", model) + @" updateFormInputs(" + javascriptPresentationFunctionName + @"()); " + model.GetCallBackFunctionForJavascript("json") + @" }"; } This method generates some boilerplace and hands off to various other methods which return strings. The whole lot is then returned as a string and written to the output. The question(s) I have are: 1) Is there a nicer way to do this other than using large string blocks? We've considered using a StringBuilder or the Response Stream but it seems quite 'noisy'. Using string.format starts to become difficult to comprehend. 2) How would you go about unit testing this code? It seems a little amateur just doing a string comparison looking for particular output in the string. 3) What about actually testing the eventual JavaScript output? Thanks for your input!

    Read the article

  • Query Level 2 Caching throwing ClassCastException

    - by Sameer Malhotra
    Hi, I am using JPA and Hibernate for the database. I have configured (EHCacache) second level cache and query level cache, but just to make sure that caching is working I was trying to get the statistics which is throwing class cast exception.Any help will be highly appreciated. My main goal is to see all the objects which have been cached to make sure that the caching is working properly. Here is the code: public List<CodeValue> findByCodetype(String propertyName) { try { final String queryString = "select model from CodeValue model where model.codetype" + "= :propertyValue" + " order by model.code"; Query query = em.createQuery(queryString); query.setHint("org.hibernate.cacheable", true); query.setHint("org.hibernate.cacheRegion", "query.findByCodetype"); query.setParameter("propertyValue", propertyName); List resultList = query.getResultList(); org.hibernate.Session session = (Session) em.getDelegate(); SessionFactory sessionFactory = session.getSessionFactory(); Map cacheEntries = sessionFactory.getStatistics() .getSecondLevelCacheStatistics("query.findByCodetype") .getEntries(); logger.info("The statistics are: " + cacheEntries); return resultList; } catch (RuntimeException re) { logger.error("findByCodetype failed in trauma patient", re); throw re; } } The error is existing right when I am trying to print the statistics. Below is exception: [6/7/10 19:23:17:059 GMT] 00000034 SystemOut O java.lang.ClassCastException: org.hibernate.cache.QueryKey incompatible with org.hibernate.cache.CacheKey at org.hibernate.stat.SecondLevelCacheStatistics.getEntries(SecondLevelCacheStatistics.java:51) at com.idph.trauma.registry.service.TraumaPatientDAO.findByCodetype(TraumaPatientDAO.java:439) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:615) at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) at $Proxy209.findByCodetype(Unknown Source) Do you know what's going on?

    Read the article

  • reddit style voting with django

    - by dotty
    Hay i need to hand implemeneting a voting system into a model. I've had a huge helping hand from Mike DeSimone making this work in the first place, but i need to expand upon his work. Here is my current code View def show_game(request): game = Game.objects.get(pk=1) discussions = game.gamediscussion_set.filter(reply_to=None) d = { 'game':game, 'discussions':discussions } return render_to_response('show_game', d) Template <ul> {% for discussion in discussions %} {{ discussion.html }} {% endfor %} </ul> Model class GameDiscussion(models.Model): game = models.ForeignKey(Game) message = models.TextField() reply_to = models.ForeignKey('self', related_name='replies', null=True, blank=True) created_on = models.DateTimeField(blank=True, auto_now_add=True) userUpVotes = models.ManyToManyField(User, blank=True, related_name='threadUpVotes') userDownVotes = models.ManyToManyField(User, blank=True, related_name='threadDownVotes') def html(self): DiscussionTemplate = loader.get_template("inclusions/discussionTemplate") return DiscussionTemplate.render(Context({ 'discussion': self, 'replies': [reply.html() for reply in self.replies.all()] })) DiscussionTemplate <li> {{ discussion.message }} {% if replies %} <ul> {% for reply in replies %} {{ reply }} {% endfor %} </ul> {% endif %} </li> As you can see we have 2 fields userUpVotes and userDownVotes on the model, these will calculate how to order the discussions and replies. How would i implement these 2 fields to order the replies and discussions based on votes? Any help would be great!

    Read the article

  • How do I stop ValueConverters from firing when swapping the content of a ContentControl

    - by DanM
    I thought what I was doing was right out of the Josh Smith MVVM handbook, but I seem to be having a lot of problems with value converters firing when no data in the view-model has changed. So, I have a ContentControl defined in XAML like this: <ContentControl Grid.Row="0" Content="{Binding CurrentViewModel}" /> The Window containing this ContentControl references a resource dictionary that looks something like this: <ResourceDictionary ...> <DataTemplate DataType="{x:Type lib_vm:SetupPanelViewModel}"> <lib_v:SetupPanel /> </DataTemplate> <DataTemplate DataType="{x:Type lib_vm:InstructionsPanelViewModel}"> <lib_v:InstructionsPanel /> </DataTemplate> </ResourceDictionary> So, basically, the two data templates specify which view to show with which view-model. This switches the views as expected whenever the CurrentViewModel property on my window's view-model changes, but it also seems to cause value converters on the views to fire even when no data has changed. It's a particular problem with IMultiValueConverter classes, because the values in the value array get set to DependencyProperty.UnsetValue, which causes exceptions unless I specifically check for that. But I'm getting other weird side effects too. This has me wondering if I shouldn't just do everything manually, like this: Instantiate each view. Set the DataContext of each view to the appropriate view-model. Give the ContentControl a name and make it public. Handle the PropertyChanged event for the window. In the event handler, manually set the Content property of the ContentControl to the appropriate view, based the CurrentViewModel (using if statements). This seems to work, but it also seems very inelegant. I'm hoping there's a better way. Could you please advise me the best way to handle view switching so that value converters don't fire unnecessarily?

    Read the article

  • mvc post techniques

    - by user281180
    My form is as follows, how can I retrieve the values in my controller: <% using (Html.BeginForm("Create","Employee")) {% <%= Html.ValidationSummary()% <p><label for = "Name" >Name</label> <%= Html.TextBoxFor(model => model.EmployeeName)%> <%= Html.ValidationMessageFor(model => model.EmployeeName)%> </p> <label for = "ProName">Project</label> <table id="projectTable"> <tr> <td> <label for="Name" id = 1>UT1</label></td></tr> <tr> <td> <label for="Name" id= 2>UT2</label></td></tr> </table> <input type ="submit" value="Save" id="submit" /> <% }%>

    Read the article

  • What are the options for overriding Django's cascading delete behaviour?

    - by Tom
    Django models generally handle the ON DELETE CASCADE behaviour quite adequately (in a way that works on databases that don't support it natively.) However, I'm struggling to discover what is the best way to override this behaviour where it is not appropriate, in the following scenarios for example: ON DELETE RESTRICT (i.e. prevent deleting an object if it has child records) ON DELETE SET NULL (i.e. don't delete a child record, but set it's parent key to NULL instead to break the relationship) Update other related data when a record is deleted (e.g. deleting an uploaded image file) The following are the potential ways to achieve these that I am aware of: Override the model's delete() method. While this sort of works, it is sidestepped when the records are deleted via a QuerySet. Also, every model's delete() must be overridden to make sure Django's code is never called and super() can't be called as it may use a QuerySet to delete child objects. Use signals. This seems to be ideal as they are called when directly deleting the model or deleting via a QuerySet. However, there is no possibility to prevent a child object from being deleted so it is not usable to implement ON CASCADE RESTRICT or SET NULL. Use a database engine that handles this properly (what does Django do in this case?) Wait until Django supports it (and live with bugs until then...) It seems like the first option is the only viable one, but it's ugly, throws the baby out with the bath water, and risks missing something when a new model/relation is added. Am I missing something? Any recommendations?

    Read the article

  • Django generic relation field reports that all() is getting unexpected keyword argument when no args

    - by Joshua
    I have a model which can be attached to to other models. class Attachable(models.Model): content_type = models.ForeignKey(ContentType) object_pk = models.TextField() content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk") class Meta: abstract = True class Flag(Attachable): user = models.ForeignKey(User) flag = models.SlugField() timestamp = models.DateTimeField() I'm creating a generic relationship to this model in another model. flags = generic.GenericRelation(Flag) I try to get objects from this generic relation like so: self.flags.all() This results in the following exception: >>> obj.flags.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 105, in all return self.get_query_set() File "/usr/local/lib/python2.6/dist-packages/django/contrib/contenttypes/generic.py", line 252, in get_query_set return superclass.get_query_set(self).filter(**query) File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 498, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 516, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1675, in add_q can_reuse=used_aliases) File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1569, in add_filter negate=negate, process_extras=process_extras) File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1737, in setup_joins "Choices are: %s" % (name, ", ".join(names))) FieldError: Cannot resolve keyword 'object_id' into field. Choices are: content_type, flag, id, nestablecomment, object_pk, timestamp, user >>> obj.flags.all(object_pk=obj.pk) Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: all() got an unexpected keyword argument 'object_pk' What have I done wrong?

    Read the article

  • foreignkey problem

    - by realshadow
    Hey, Imagine you have this model: class Category(models.Model): node_id = models.IntegerField(primary_key = True) type_id = models.IntegerField(max_length = 20) parent_id = models.IntegerField(max_length = 20) sort_order = models.IntegerField(max_length = 20) name = models.CharField(max_length = 45) lft = models.IntegerField(max_length = 20) rgt = models.IntegerField(max_length = 20) depth = models.IntegerField(max_length = 20) added_on = models.DateTimeField(auto_now = True) updated_on = models.DateTimeField(auto_now = True) status = models.IntegerField(max_length = 20) node = models.ForeignKey(Category_info, verbose_name = 'Category_info', to_field = 'node_id' The important part is the foreignkey. When I try: Category.objects.filter(type_id = 15, parent_id = offset, status = 1) I get an error that get returned more than category, which is fine, because it is supposed to return more than one. But I want to filter the results trough another field, which would be type id (from the second Model) Here it is: class Category_info(models.Model): objtree_label_id = models.AutoField(primary_key = True) node_id = models.IntegerField(unique = True) language_id = models.IntegerField() label = models.CharField(max_length = 255) type_id = models.IntegerField() The type_id can be any number from 1 - 5. I am desparately trying to get only one result where the type_id would be number 1. Here is what I want in sql: SELECT c.*, ci.* FROM category c JOIN category_info ci ON (c.node_id = ci.node_id) WHERE c.type_id = 15 AND c.parent_id = 50 AND ci.type_id = 1 Any help is GREATLY appreciated. Regards

    Read the article

  • Why does this test fail?

    - by Tomas Lycken
    I'm trying to test/spec the following action method public virtual ActionResult ChangePassword(ChangePasswordModel model) { if (ModelState.IsValid) { if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword)) { return RedirectToAction(MVC.Account.Actions.ChangePasswordSuccess); } else { ModelState.AddModelError("", "The current password is incorrect or the new password is invalid."); } } // If we got this far, something failed, redisplay form return RedirectToAction(MVC.Account.Actions.ChangePassword); } with the following MSpec specification: public class When_a_change_password_request_is_successful : with_a_change_password_input_model { Establish context = () => { membershipService.Setup(s => s.ChangePassword(Param.IsAny<string>(), Param.IsAny<string>(), Param.IsAny<string>())).Returns(true); controller.SetFakeControllerContext("POST"); }; Because of = () => controller.ChangePassword(inputModel); ThenIt should_be_a_redirect_result = () => result.ShouldBeARedirectToRoute(); ThenIt should_redirect_to_success_page = () => result.ShouldBeARedirectToRoute().And().ShouldRedirectToAction<AccountController>(c => c.ChangePasswordSuccess()); } where with_a_change_password_input_model is a base class that instantiates the input model, sets up a mock for the IMembershipService etc. The test fails on the first ThenIt (which is just an alias I'm using to avoid conflict with Moq...) with the following error description: Machine.Specifications.SpecificationException: Should be of type System.RuntimeType but is [null] But I am returning something - in fact, a RedirectToRouteResult - in each way the method can terminate! Why does MSpec believe the result to be null?

    Read the article

  • How to best future proof my application that needs to connect to Outlook?

    - by Troy
    I have a contact management application written in Delphi which has a “Sync with Outlook” feature that I developed 10 years ago. Now, I’m going back to add some features and fix some bugs. This sync feature uses the Outlook object model to get started, but it has an optional mode called “Use MAPI Enhancements” where it uses pure MAPI to speed up how it looks for changes, and it allows notes to be synced w/ RTF instead of just plain text. I'm wondering if supporting two parallel paths of execution is a good idea or not. If I went with all MAPI, I believe I'd avoid some security prompts, and I'd avoid situations where anti-virus has "script-blocking" features which block my app from connecting to Outlook. But I believe that on the down side, my 32-bit app would not be able to to connect with 64-bit Outlook 2010 using MAPI. And I wonder about the future of MAPI in general. If I stick with the Outlook object model, will my 32-bit app be able to connect to the Outlook object model (since it's out of process COM)? If so, this is a compelling reason to keep my Outlook object model execution path in place. But if not, and if my app needs to be compiled for x64, then why not just go with pure MAPI?

    Read the article

  • Cascading DropDown List in MVC 4

    - by Misi
    I have a ASP.NET MVC 4 project with EF I have a table with Parteners. This table has 2 types of parteners : agents(part_type=1) and clients(part_type=2). In an Create view I have the first DropDownList that shows all my agents, a button and the second DDL that shows all my clients that correspond to the selected agent. Q1 : What button shoud I use ? , , @Html.ActionLink() ? Create.cshtml <div class="editor-field"> @Html.DropDownList("idagenti", ViewData["idagenti"] as List<SelectListItem>, String.Empty) </div> @*a button*@ <div class="editor-label"> @Html.LabelFor(model => model.id_parten, "Client") </div> <div class="editor-field"> @Html.DropDownList("id_parten", String.Empty) @Html.ValidationMessageFor(model => model.id_parten) </div> OrdersController.cs public ActionResult Create(int? id) // id is the selected agent { var agqry = db.partener.Where(p => p.part_type == 1).Where(p => p.activ == true); var cltqry = db.partener.Where(p => p.part_type == 2).Where(p => p.activ == true); List<SelectListItem> idagenti = new List<SelectListItem>(); foreach (partener ag in agqry) { idagenti.Add(new SelectListItem { Text = ag.den_parten, Value = ag.id_parten.ToString() }); } if (id != null) { cltqry = cltqry.Where(p => p.par_parten == id); } ViewData["idagenti"] = idagenti; ViewBag.id_parten = new SelectList(cltqry, "id_parten", "den_parten");// } Q: How can I pass the selected agent id from the first DDL to my controller ?

    Read the article

  • ASP.NET MVC jQuery autocomplete with url.action helper in a script included in a page.

    - by Boob
    I have been building my first ASP.NET MVC web app. I have been using the jQuery autocomplete widget in a number of places like this: <head> $("#model").autocomplete({ source: '<%= Url.Action("Model", "AutoComplete") %>' }); </head> The thing is I have this jQuery code in a number of different places through my web app. So i thought I would create a seperate javascript script (script.js) where I could put this code and then just include it in the master page. Then i can put all these repeated pieces of code in that script and just call them where I need too. So I did this. My code is shown below: In the site.js script I put this function: function doAutoComplete() { $("#model").autocomplete({ source: '<%= Url.Action("Model", "AutoComplete") %>' }); } On the page I have: <head> <script src="../../Scripts/site.js" type="text/javascript"></script> doAutoComplete(); </head> But when I do this I get an Invalid Argument exception and the autocomplete doesnt work. What am I doing wrong? Any ideas?Do i need to pass something to the doAutoComplete function?

    Read the article

  • Django Database design -- Is this a good stragety for overriding defaults

    - by rh0dium
    Hi SO's I have a question on good database design practices and I would like to leverage you guys for pointers. The project started out simple. Hey we have a bunch of questions we want answered for every project (no problem) Which turned into... Hey we have so many questions can we group them into sections (yup we can do that) Which lead into.. Can we weight these questions and I don't really want some of these questions for my project (Yes but we are getting difficult) And then I'm thinking they will want to have each section have it's own weight.. Requirements So there's the requirements - For n number of project Allow a admin member the ability select the questions for a project Allow the admin member to re-weigh or use the default weights for the questions Allow the admin member to re-weight the sections Allow team members to answer the questions. So here is what I came up with. Please feel free to comment and provide better examples models.py from django.db import models from django.contrib.sites.models import Site from django.conf import settings class Section(models.Model): """ This describes the various sections for a checklist: """ name = models.CharField(max_length=64) description = models.TextField() class Question(models.Model): """ This simply provides a simple way to list out the questions. """ question = models.CharField(max_length=255) answer_type = models.CharField(max_length=16) description = models.TextField() section = models.ForeignKey(Section) class ProjectQuestion(models.Model): """ These are the questions relevant to the project """ question = models.ForeignKey(Question) answer = models.CharField(max_length=255) required = models.BooleanField(default=True) weight = models.FloatField(default = XXX) class Project(models.Model): """ Here is where we want to gather our questions """ questions = models.ManyToManyField(ProjectQuestion) Immediate questions: - When I start a project - any ideas on how to "pre-populate" the questions (and ultimately the weights) for the project? - Is there a generally accepted method for doing this process that I am missing? Basically the idea that you refer to the questions overide your own default weight, and store the answer? - It appears that a good chuck of the work will be done in the views and that a lot of checking will need to occur there? Is that OK? Again - feel free to give me better strategies!! Thanks

    Read the article

  • NHibernate collections: many-to-many relationships

    - by Brad Heller
    I've got two models, a Product model and a ShoppingCart model. The ShoppingCart model has a collection of products as a property called Products (List). Here is the mapping for my ShoppingCart model. <class name="MyProject.ShoppingCart, MyProject" table="ShoppingCarts"> <id name="Id" column="Id"> <generator class="native" /> </id> <many-to-one name="Company" class="MyProject.Company, MyProject" column="CompanyId" /> <property name="ExternalId" column="GUID" generated="insert" /> <property name="Name" column="Name" /> <property name="Total" column="Total" /> <property name="CreationDate" column="CreationDate" generated="insert" /> <property name="UpdatedDate" column="UpdatedDate" generated="always" /> <bag name="Products" table="ShoppingCartContents" lazy="false"> <key column="ShoppingCartId" /> <many-to-many column="ProductId" class="MyProjectMyProject.Product, MyProject" fetch="join" /> </bag> </class> When I try to save to the DB, the ShoppingCart is saved, but the mapping rows in ShoppingCartContents aren't save, making me thing that there's an issue with the mapping. Where am I going wrong here?

    Read the article

  • Left/Right/Inner joins using C# and LINQ

    - by Keith Barrows
    I am trying to figure out how to do a series of queries to get the updates, deletes and inserts segregated into their own calls. I have 2 tables, one in each of 2 databases. One is a Read Only feeds database and the other is the T-SQL R/W Production source. There are a few key columns in common between the two. What I am doing to setup is this: List<model.AutoWithImage> feedProductList = _dbFeed.AutoWithImage.Where(a => a.ClientID == ClientID).ToList(); List<model.vwCompanyDetails> companyDetailList = _dbRiv.vwCompanyDetails.Where(a => a.ClientID == ClientID).ToList(); foreach (model.vwCompanyDetails companyDetail in companyDetailList) { List<model.Product> productList = _dbRiv.Product.Include("Company").Where(a => a.Company.CompanyId == companyDetail.CompanyId).ToList(); } Now that I have a (source) list of products from the feed, and an existing (target) list of products from my prod DB I'd like to do 3 things: Find all SKUs in the feed that are not in the target Find all SKUs that are in both, that are active feed products and update the target Find all SKUs that are in both, that are inactive and soft delete from the target What are the best practices for doing this without running a double loop? Would prefer a LINQ 4 Objects solution as I already have my objects. EDIT: BTW, I will need to transfer info from feed rows to target rows in the first 2 instances, just set a flag in the last instance. TIA

    Read the article

  • HTML Submit button vs AJAX based Post (ASP.NET MVC)

    - by Graham
    I'm after some design advice. I'm working on an application with a fellow developer. I'm from the Webforms world and he's done a lot with jQuery and AJAX stuff. We're collaborating on a new ASP.MVC 1.0 app. He's done some pretty amazing stuff that I'm just getting my head around, and used some 3rd party tools etc. for datagrids etc. but... He rarely uses Submit buttons whereas I use them most of the time. He uses a button but then attaches Javascript to it that calls an MVC action which returns a JSON object. He then parses the object to update the datagrid. I'm not sure how he deals with server-side validation - I think he adds a message property to the JSON object. A sample scenario would be to "Save" a new record that then gets added to the gridview. The user doesn't see a postback as such, so he uses jQuery to disable the UI whilst the controller action is running. TBH, it looks pretty cool. However, the way I'd do it would be to use a Submit button to postback, let the ModelBinder populate a typed model class, parse that in my controller Action method, update the model (and apply any validation against the model), update it with the new record, then send it back to be rendered by the View. Unlike him, I don't return a JSON object, I let the View (and datagrid) bind to the new model data. Both solutions "work" but we're obviously taking the application down different paths so one of us has to re-work our code... and we don't mind whose has to be done. What I'd prefer though is that we adopt the "industry-standard" way of doing this. I'm unsure as to whether my WebForms background is influencing the fact that his way just "doesn't feel right", in that a "submit" is meant to submit data to the server. Any advice at all please - many thanks.

    Read the article

  • How to create instances of related models in Django

    - by sevennineteen
    I'm working on a CMSy app for which I've implemented a set of models which allow for creation of custom Template instances, made up of a number of Fields and tied to a specific Customer. The end-goal is that one or more templates with a set of custom fields can be defined through the Admin interface and associated to a customer, so that customer can then create content objects in the format prescribed by the template. I seem to have gotten this hooked up such that I can create any number of Template objects, but I'm struggling with how to create instances - actual content objects - in those templates. For example, I can define a template "Basic Page" for customer "Acme" which has the fields "Title" and "Body", but I haven't figured out how to create Basic Page instances where these fields can be filled in. Here are my (somewhat elided) models... class Customer(models.Model): ... class Field(models.Model): ... class Template(models.Model): label = models.CharField(max_length=255) clients = models.ManyToManyField(Customer, blank=True) fields = models.ManyToManyField(Field, blank=True) class ContentObject(models.Model): label = models.CharField(max_length=255) template = models.ForeignKey(Template) author = models.ForeignKey(User) customer = models.ForeignKey(Customer) mod_date = models.DateTimeField('Modified Date', editable=False) def __unicode__(self): return '%s (%s)' % (self.label, self.template) def save(self): self.mod_date = datetime.datetime.now() super(ContentObject, self).save() Thanks in advance for any advice!

    Read the article

  • Get a selected radio button value after POST to set other fields enabled/disabled

    - by Redeemed1
    I have an MVC application with a simple control to all selection of All Dates or selecting a Date Range. The radio buttons have an onclick handler to enable/disable the dat pickers. All work well so far. When I try to set the correct context state for the datepickers after doing a POST I cannot get the jQuery selector to return the radio buttons checked value. The code is as follows: <%= Html.RadioButton("DateSelection.AllDates", "AllDates", Model.AllDates == "AllDates", new { onclick = "setReadOnly(this);" })%>ALL Dates&nbsp; <%= Html.RadioButton("DateSelection.AllDates", "Selection", Model.AllDates == "Selection", new { onclick = "setReadOnly(this);" })%>Selection <%= Html.DatePicker("DateSelection.startdate", Model.StartDate, "", "") %> &nbsp;To&nbsp;<%= Html.DatePicker("DateSelection.enddate", Model.EndDate, "", "") %><br /> The javascript is as follows: <script type="text/jscript" > function setReadOnly(obj) { if (obj.value == "Selection") { $('#DateSelection_startdate').css('backgroundColor', '#ffffff') .removeAttr('readonly') .datepicker('enable'); $('#DateSelection_enddate').css('backgroundColor', '#ffffff') .removeAttr('readonly') .datepicker('enable'); } else { $('#DateSelection_startdate').css('backgroundColor', '#eeeeee') .attr('readonly', 'readonly') .val('') .datepicker('disable'); $('#DateSelection_enddate').css('backgroundColor', '#eeeeee') .attr('readonly', 'readonly') .val('') .datepicker('disable'); } } <script type="text/jscript"> $(document).ready(function() { $('#DateSelection_startdate').datepicker('disable').css('backgroundColor', '#eeeeee') .attr('readonly', 'readonly') .val(''); $('#DateSelection_enddate').datepicker('disable').css('backgroundColor', '#eeeeee') .attr('readonly', 'readonly') .val(''); var selected = $('#DateSelection_AllDates:checked'); setReadOnly(selected); }); The javascript line that is causing the problem is var selected = $('#DateSelection_AllDates:checked'); which will NOT return the checked radio button. Using var selected = $('#DateSelection_AllDates'); will return the first radio button value as expected i.e. applying the ':checked' filter ALWAYS returns undefined. Can anyone see anything wrong here?

    Read the article

  • undefined returned for currentView object in Backbone.Marionette

    - by ontk
    I am testing how a layout can listen to its subviews's custom events. I created a jsFiddle here where I have a layout, 2 regions and I instantiated 2 ItemViews and showed them in the layout's regions. The fiddle is in CoffeeScript. <div id="region"></div> <script id="layout-tmpl" type="text/_"> <h3>Heading</h3> <div id="content"></div> <div id="content2"></div> </script> <script id="item-tmpl" type="text/_"> <form> <label>Firstname:</lable> <input type="text" name="firstname" value="<%= firstname %>" /> <input type="button" value="Save" id="save" /> </form> </script> And the CoffeeScript is: SimpleLayout = Backbone.Marionette.Layout.extend template: '#layout-tmpl' regions: main: '#content' other: '#content2' initialize: () -> console.log @ onShow: () -> _.each @.regionManagers, (region, name, something) => console.log region.currentView # @.bindTo region.currentView, "custom:event", @callback callback: () -> alert "HELL YEAH" SimpleItemView = Backbone.Marionette.ItemView.extend template: "#item-tmpl" events: 'click #save': 'save' save: (evt) -> evt.preventDefault() @.trigger "custom:event" region = new Backbone.Marionette.Region el: "#region" layout = new SimpleLayout() region.show layout layout.main.show new SimpleItemView model: (new Backbone.Model firstname: "Olivier") layout.other.show new SimpleItemView model: (new Backbone.Model firstname: "Travis") I want the layout to listen to the ItemViews's custom events. In the onShow, I am looping through the region managers and trying to access the currentView object but it returns undefined. If I attach the same event handlers outside of the SimpleLayout class and after I show the itemviews, then the layout handlers the custom events properly. Thanks for your help.

    Read the article

  • how to apply iddata into calculation?

    - by Sam
    I am trying to figure out how to combine the input and output data into the ARX model and then apply it into the BIC (Bayesian Information Criterion) formula. Below is the code that I am currently working on: for i=1:30; %% Set Model Order data=iddata(output,input,1); model = arx(data,[8 9 i]); yp = predict(model,data); ye = regress(data,yp{1,1}(1:4018,1)); M(i) = var(yp); BIC(i)=(N+i*(log(N)-1))/(N-i)*log(M(i)); end But it does not work. It keep on giving me an error something like below: "The syntax "Data{...}" is not supported. Use the "getexp" command to extract individual experiments from an IDDATA object." I did not understand what does that mean. Can someone explain it to me and where do I do wrong on my piece of code? Thanks in advance. Sam.

    Read the article

  • Using OpenGL vertex buffers in C++.

    - by Ren
    I've loaded a Wavefront .obj file and drawn it in immediate mode, and it works fine. I'm now trying to draw the same model with a vertex buffer, but I have a question. My model data is organized in the following structures: struct Vert { double x; double y; double z; }; struct Norm { double x; double y; double z; }; struct Texcoord { double u; double v; double w; }; struct Face { unsigned int v[3]; unsigned int n[3]; unsigned int t[3]; }; struct Model { unsigned int vertNumber; unsigned int normNumber; unsigned int texcoordNumber; unsigned int faceNumber; Vert * vertArray; Norm * normArray; Texcoord * texcoordArray; Face * faceArray; }; As it is now, I don't think there is any redundant data, since multiple face structures can point to the same vertex, normal, or texture coordinate. When I make vbo's for the vertex positions, normals, and texture coordinates, and assign data to them with glBufferData, do I have to have make arrays with redundant data so that they will all have the same number of elements in the same order? I'd like to know if there is a simpler way to fill the buffers with the way I already have the model's data organized.

    Read the article

  • Problem Render backbone collection using Mustache template

    - by RameshVel
    I am quite new to backbone js and Mustache. I am trying to load the backbone collection (Object array) on page load from rails json object to save the extra call . I am having troubles rendering the backbone collection using mustache template. My model & collection are var Item = Backbone.Model.extend({ }); App.Collections.Items= Backbone.Collection.extend({ model: Item, url: '/items' }); and view App.Views.Index = Backbone.View.extend({ el : '#itemList', initialize: function() { this.render(); }, render: function() { $(this.el).html(Mustache.to_html(JST.item_template(),this.collection )); //var test = {name:"test",price:100}; //$(this.el).html(Mustache.to_html(JST.item_template(),test )); } }); In the above view render, i can able to render the single model (commented test obeject), but not the collections. I am totally struck here, i have tried with both underscore templating & mustache but no luck. And this is the Template <li> <div> <div style="float: left; width: 70px"> <a href="#"> <img class="thumbnail" src="http://placehold.it/60x60" alt=""> </a> </div> <div style="float: right; width: 292px"> <h4> {{name}} <span class="price">Rs {{price}}</span></h4> </div> </div> </li> and my object array kind of looks like this

    Read the article

  • Backbone.js Collection Iteration Using .each()

    - by the_archer
    I've been doing some Backbone.js coding and have come across a particular problem where I am having trouble iterating over the contents of a collection. The line Tasker_TodoList.each(this.addOne, this);in the addAll function in AppView is not executing properly for some reason, throwing the error: Uncaught TypeError: undefined is not a function the code in question is: $(function() { var Todo = Backbone.Model.extend({ defaults: { title: "Some Title...", status: 0 //not completed } }); var TodoList = Backbone.Collection.extend({ model: Todo, localStorage: new Store('tasker') }); var Tasker_TodoList = new TodoList(); var TodoView = Backbone.View.extend({ tagName: 'li', template: _.template($('#todoTemplate').html()), events: { 'click .delbtn': 'delTodo' }, initialize: function(){ console.log("a new todo initialized"); //this.model.on('change', this.render, this); }, render: function(){ this.$el.html(this.template(this.model.toJSON())); return this; }, delTodo: function(){ console.log("deleted todo"); } }); var AppView = Backbone.View.extend({ el: 'body', events: { 'click #addBtn': 'createOnClick' }, initialize: function(){ Tasker_TodoList.fetch(); Tasker_TodoList.on('add', this.addAll); console.log(Tasker_TodoList); }, addAll: function(){ $('#tasksList').html(''); console.log("boooooooma"); Tasker_TodoList.each(this.addOne, this); }, addOne: function(todo){ console.log(todo); }, createOnClick: function(){ Tasker_TodoList.create(); } }); var Tasker = new AppView(); }); can somebody help me in finding out what I am doing wrong? Thank you all for your help :-)

    Read the article

  • CakePHP hasMany relationship with multiple columns

    - by Muhammad Yasir
    Hi, I am using CakePHP framework to build a web application. The simplest form of my problem is this: I have a users table and a messages table with corresponding models. Messages are sent from a user to another user. So messages table has columns from_id and to_id in it, both referencing to id of users. I am able to link Message model to User model by using $belongsTo but I am unable to link User model with Message model (in reverse direction) by using $hasMany in the same manner. var $hasMany = array( 'From' => array( 'className' => 'Message', 'foreignKey' => 'from_id', 'dependent' => false, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'exclusive' => '', 'finderQuery' => '', 'counterQuery' => '' ), 'To' => array( 'className' => 'Message', 'foreignKey' => 'to_id', 'dependent' => false, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'exclusive' => '', 'finderQuery' => '', 'counterQuery' => '' ) ); What can do here? Any ideas? Thanks for any help.

    Read the article

  • Problem in inferring instances that have integer cardinality constraint

    - by Mikae Combarado
    Hello, I have created an RDF/OWL file using Protege 4.1 alpha. I also created a defined class in Protege called CheapPhone. This class has a restriction which is shown below : (hasPrice some integer[< 350]) Whenever, a price of a phone is below 350, it is inferred as CheapPhone. There is no problem for inferring this in Protege 4.1 alpha. However, I cannot infer this using Jena. I also created a defined class called SmartPhone. This class also has a restriction which is shown below : (has3G value true) and (hasInternet value true) Whenever, a phone has 3G and Internet, it is inferred as SmartPhone. In this situation, there is no problem inferring this in both Protege and Jena. I have started to think that there is a problem in default inference engine of Jena. The code that I use in Java is below : Reasoner reasoner = ReasonerRegistry.getOWLReasoner(); reasoner = reasoner.bindSchema(ontModel); OntModelSpec ontModelSpec = OntModelSpec.OWL_MEM_MINI_RULE_INF; ontModelSpec.setReasoner(reasoner); // Create ontology model with reasoner support // ontModel was created and read before, so I don't share the code in order // not to create garbage here OntModel model = ModelFactory.createOntologyModel(ontModelSpec, ontModel); OntClass sPhone = model.getOntClass(ns + "SmartPhone"); ExtendedIterator s = sPhone.listInstances(); while(s.hasNext()) { OntResource mp = (OntResource)s.next(); System.out.println(mp.getURI()); } This code works perfectly and returns me the instances, but when I change the code below and make it appropriate for CheapPhone, it doesn't return anything. OntClass sPhone = model.getOntClass(ns + "CheapPhone"); Am I doing something wrong ?

    Read the article

< Previous Page | 142 143 144 145 146 147 148 149 150 151 152 153  | Next Page >