Search Results

Search found 296 results on 12 pages for 'validations'.

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

  • Is there a way to validates_presence_of only one time? (to skip that validation once the user's been

    - by GoodGets
    So, I'd like for a user to see an error message if he submits a comment and the :name is blank (typical error message, don't need help with that). However, I'd then like to allow the user to skip that validation once he's been notified that "we like all comments to have a name." So, he submits the comment once, sees the notification, then can submit the form again unchanged if he really doesn't want to add a name, and the validates_presences_of :name is skipped. But, I'm not sure how to go about doing this. I thought about checking to see where the request is coming from, but after a create, errors are handed off to the "new" action, which is the same as actual "new" comments. I then thought about checking to see if flash[errors] were present, but that won't work because there are other validations a comment has to pass. Finally, I thought about trying a validates_presences_of :name, :unless = :notified but wasn't sure how to define notified. I honestly hate asking such an open ended question, but wasn't sure where to get started. So, is there a way to just check a certain validation once?

    Read the article

  • How to perform Rails model validation checks within model but outside of filters using ledermann-rails-settings and extensions

    - by user1277160
    Background I'm using ledermann-rails-settings (https://github.com/ledermann/rails-settings) on a Rails 2/3 project to extend virtually the model with certain attributes that don't necessarily need to be placed into the DB in a wide table and it's working out swimmingly for our needs. An additional reason I chose this Gem is because of the post How to create a form for the rails-settings plugin which ties ledermann-rails-settings more closely to the model for the purpose of clean form_for usage for administrator GUI support. It's a perfect solution for addressing form_for support although... Something that I'm running into now though is properly validating the dynamic getters/setters before being passed to the ledermann-rails-settings module. At the moment they are saved immediately, regardless if the model validation has actually fired - I can see through script/console that validation errors are being raised. Example For instance I would like to validate that the attribute :foo is within the range of 0..100 for decimal usage (or even a regex). I've found that with the previous post that I can use standard Rails validators (surprise, surprise) but I want to halt on actually saving any values until those are addressed - ensure that the user of the GUI has given 61.43 as a numerical value. The following code has been borrowed from the quoted post. class User < ActiveRecord::Base has_settings validates_inclusion_of :foo, :in => 0..100 def self.settings_attr_accessor(*args) >>SOME SORT OF UNLESS MODEL.VALID? CHECK HERE args.each do |method_name| eval " def #{method_name} self.settings.send(:#{method_name}) end def #{method_name}=(value) self.settings.send(:#{method_name}=, value) end " end >>END UNLESS end settings_attr_accessor :foo end Anyone have any thoughts here on pulling the state of the model at this point outside of having to put this into a before filter? The goal here is to be able to use the standard validations and avoid rolling custom validation checks for each new settings_attr_accessor that is added. Thanks!

    Read the article

  • Queuing using table or MSMQ?

    - by Lieven Cardoen
    A part of the application I'm working on is an swf that shows a test with some 80 questions. Each question is saved to a sql server through WebORB and asp.net. If a candidate finisheds the test, the session needs to be validated. Problem now is that sometimes 350 candidates finish their test at the same moment, and cpu on webserver and sql server explodes (350 validations concurrently). Now, how would I implement queuing here? In the database, there's a table that has a record for each session. One column holds the status. 1 is finished, 2 is validated. I could implement queuing in two ways (as I see it, maybe you have other propositions): A process that checks the table for records with status 1. If it finds one, it validates the session. So, sessions are validated one after one. If a candidate finishes its session, a message is sent to a MSMQ queue. Another process listens to the queue and validates sessions one after one. Now, What would be the best approach? Where do you start the process that will validate sessions? In your global.asax (application_start)? As a windows service? As an exe on the root of the website that is started in application_start? To me, using the table and looking for records with status 1 seems the easiest way.

    Read the article

  • How to develop Online Shopping Portal Application using PHP ?

    - by Sarang
    I do not know PHP & I have to develop a Shopping Portal with following Definition : Scenario: Online Shopping Portal XYZ.com wants to create an online shopping portal for managing its registered customers and their shopping. The customers need to register themselves first before they do shopping using the shopping portal. However, everyone, whether registered or not, can view the various products along with the prices listed in the portal. The registered customers, after logging in, are allowed to place order for one or more products from the products listed in the portal. Once the order is placed, the customer gets a reference order number and the order status should be “order in process”. The customers can track their order using the given reference number. The management of XYZ.com should be able to modify the order status of a particular reference order number to “shipped” once the products are shipped to the shipping address entered by the customer at the time of placing the order. The Functionalities required are : Create the interface for the XYZ.com shopping portal using HTML/XHTML and CSS. Implement the client side validations using JavaScript. Create the tables using MySQL. Implement the functionality using the server side scripting language, PHP. Integrate all the above tasks and make the XYZ.com shopping portal functional. How do I develop this application with following proper steps of development ?

    Read the article

  • What pattern is layered architecture in asp.net ?

    - by haansi
    Hi, I am a asp.net developer and don't know much about patterns and architecture. I will very thankful if you can please guide me here. In my web applications I use 4 layers. Web site project (having web forms + code behind cs files, user controls + code behind cs files, master pages + code behind cs files) CustomTypesLayer a class library (having custom types, enumerations, DTOs, constructers, get, set and validations) BusinessLogicLayer a class library (having all business logic, rules and all calls to DAL functions) DataAccessLayer a class library( having just classes communicating to database.) -My user interface just calls BusinessLogicLayer. BusinessLogicLayer do proecessign in it self and for data it calls DataAccessLayer funtions. -Web forms do not calls directly DAL. -CustomTypesLayer is shared by all layers. Please guide me is this approach a pattern ? I though it may be MVC or MVP but pages have there code behind files as well which are confusing me. If it is no patren is it near to some patren ? pleaes guide thanks

    Read the article

  • How to pass a value from the Jquery validation

    - by user2963960
    How can i pass a value from the jquery validation. I have an input box named clubCardNumber it should validate the length of the inputted value. If the length is equal to 10 the value passes to the hidden field named else validated it if its null or empty if all validations are true then its a clubCard. Here is how i implemented it on Javascript function validateClubCardNumber() { var varClubCardNumber = $('#clubCardNumber').val(); $('#phoneNumber').val(""); var returnVal = true; if ((null == varClubCardNumber || '' == trim(varClubCardNumber)){ return false; } if( varClubCardNumber.length < 10 ){ return false; }else if( varClubCardNumber.length == 10 ) { //The Phone Number field should contains numbers only var pattern = /^[0-9 -]*$/ ; var flag = pattern.test(trim(varClubCardNumber)); if(flag == false){ return false; }else{ $('#phoneNumber').val(varClubCardNumber); returnVal = true; } } } return returnVal; } HTML <div > <label for="clubCardNumber" >Card or Phone Number:</label> <input id="clubCardNumber" name="clubCardNumber" type="text" placeholder="Card or Phone Number" value="" maxlength="20"/> </div> <input type="hidden" id="phoneNumber" name="phoneNumber" value=""/>

    Read the article

  • How to return output from .Net Dll to the calling Application

    - by sachin
    I have to create one VB.Net Dll for VB.Net Application.In DLL there will be function to calculate the fee based on some parameter which I pass when call the function from appllication, output of calculated fee would be this type **Validations are not selected. Rate information: IN:11/14/20113:12:38 PM; OUT:11/15/20113:12:38 PM; Fee:3; Description:$3 Fixed IN:11/14/20113:12:38 PM; OUT:11/15/20113:12:38 PM; Fee:1; Description:$1 Fixed Sub Total: IN: 11/14/20113:12:38 PM; OUT: 11/15/20113:12:38 PM; Fee:4; Description: Rate Group1 Rate information: IN:11/14/20113:12:38 PM; OUT:11/15/20113:12:38 PM; Fee:3; Description:$3 Fixed Sub Total: IN: 11/14/20113:12:38 PM; OUT: 11/15/20113:12:38 PM; Fee:3; Description: Rate Group1** Can anybody tell me how can I return output of this type to the application ,so that I can use it in that application.

    Read the article

  • What is the difference between these two linq implementations?

    - by Mahesh Velaga
    I was going through Jon Skeet's Reimplemnting Linq to Objects series. In the implementation of where article, I found the following snippets, but I don't get what is the advantage that we are gettting by splitting the original method into two. Original Method: // Naive validation - broken! public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { if (source == null) { throw new ArgumentNullException("source"); } if (predicate == null) { throw new ArgumentNullException("predicate"); } foreach (TSource item in source) { if (predicate(item)) { yield return item; } } } Refactored Method: public static IEnumerable<TSource> Where<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { if (source == null) { throw new ArgumentNullException("source"); } if (predicate == null) { throw new ArgumentNullException("predicate"); } return WhereImpl(source, predicate); } private static IEnumerable<TSource> WhereImpl<TSource>( this IEnumerable<TSource> source, Func<TSource, bool> predicate) { foreach (TSource item in source) { if (predicate(item)) { yield return item; } } } Jon says - Its for eager validation and then defferring for the rest of the part. But, I don't get it. Could some one please explain it in a little more detail, whats the difference between these 2 functions and why will the validations be performed in one and not in the other eagerly? Conclusion/Solution: I got confused due to my lack of understanding on which functions are determined to be iterator-generators. I assumed that, it is based on signature of a method like IEnumerable<T>. But, based on the answers, now I get it, a method is an iterator-generator if it uses yield statements.

    Read the article

  • what patern is layerd architechture in asp.net ?

    - by haansi
    Hi, I am a asp.net developer and don't know much about patterns and architecture. I will very thankful if you can please guide me here. In my web applications I use 4 layers. Web site project (having web forms + code behind cs files, user controls + code behind cs files, master pages + code behind cs files) CustomTypesLayer a class library (having custom types, enumerations, DTOs, constructers, get, set and validations) BusinessLogicLayer a class library (having all business logic, rules and all calls to DAL functions) DataAccessLayer a class library( having just classes communicating to database.) -My user interface just calls BusinessLogicLayer. BusinessLogicLayer do proecessign in it self and for data it calls DataAccessLayer funtions. -Web forms do not calls directly DAL. -CustomTypesLayer is shared by all layers. Please guide me is this approach a pattern ? I though it may be MVC or MVP but pages have there code behind files as well which are confusing me. If it is no patren is it near to some patren ? pleaes guide thanks

    Read the article

  • jquery form validation, and submit-on-change

    - by Bee
    I want to make all my settings forms across my site confirm that changes are saved, kinda like facebook does if you make changes in a form and then try to navigate away without saving. So I'm disabling the submit button on the forms only enabling if the values change. I then prompt the user to hit save before they leave the page in the case that they do have changes pending. var form = $('form.edit'); if(form.length > 0) { var orig_str = form.serialize(); $(':submit',form).attr('disabled','disabled'); form.on('change keyup', function(){ if(form.serialize() == orig_str) { setConfirmUnload(false); $(':submit',form).attr('disabled','disabled'); } else { setConfirmUnload(true); $(':submit',form).removeAttr('disabled') } }); $('input[type=submit]').click(function(){ setConfirmUnload(false); }); } function setConfirmUnload(on) { window.onbeforeunload = (on) ? unloadMessage : null; } function unloadMessage() { return 'If you navigate away from this page without saving your changes, they will be lost.'; } One of these forms needs some additional validation which I do using jQuery.validate library. e.g. if i wanted to ensure the user can't double submit the form on accident by double clicking on submit or somesuch (the actual validation in question is for a credit-card form and not this simple): $('form').validate({ submitHandler: function(form) { $(':submit', form).attr('disabled','disabled'); form.submit(); } }); Unfortunately both bits are trying to bind to submit button and they're interfering with each other such that the submit button remains disabled no matter what I do and it is impossible to submit the form at all. Is there some way to chain the validations together or something? Or some other way to avoid re-writing the validation code to repeat the "did you change anything in the form" business?

    Read the article

  • Entity Framework Validation & usage

    - by kmsellers
    I'm aware there is an AssociationChanged event, however, this event fires after the association is made. There is no AssociationChanging event. So, if I want to throw an exception for some validation reason, how do I do this and get back to my original value? Also, I would like to default values for my entity based on information from other entities but do this only when I know the entitiy is instanced for insertion into the database. How do I tell the difference between that and the object getting instanced because it is about to be populated based on existing data? Am I supposed to know? Is that considiered business logic that should be outside of my entity business logic? If that's the case, then should I be designing controller classes to wrap all these entities? My concern is that if I deliver back an entity, I want the client to get access to the properties, but I want to retain tight control over validations on how they are set, defaulted, etc. Every example I've seen references context, which is outside of my enity partial class validation, right? BTW, I looked at the EFPocoAdapter and for the life of me cannot determine how to populate lists of from within my POCO class... anyone know how I get to the context from a EFPoco Class?

    Read the article

  • how should i create my own 'now' / DateTime.Now ?

    - by Michel
    Hi all, i'm starting to build a part of a system which will hold a lot of DateTime validations, and a lot of 'if it was done before now' or 'if it will start in an hour etc'. Usual way to go is to use DateTime.Now to get the actual time. I predict however, that during unit test that will give me a real headache because i will have to setup my testdata for the time when the test will run in stead of use a default set of test data. So i thought: why not use my own 'now' so i can set the current datetime to any moment in time. As i don't want to set the testservers internal clock i was thinking about this solution, and i was wondering what you think of it. Base thought is that i use my own DateTime class. That class gives you the current datetime, but you can also set your own time from outside. public static class MyDateTime { private static TimeSpan _TimeDifference = TimeSpan.Zero; public static DateTime Now { get { return DateTime.Now + _TimeDifference; } } public static void SetNewNow(DateTime newNow) { _TimeDifference = newNow - DateTime.Now; } public static void AddToRealTime(TimeSpan timeSpan ) { _TimeDifference = timeSpan; } public static void SubtractFromRealTime(TimeSpan timeSpan) { _TimeDifference = - timeSpan; } }

    Read the article

  • How to render all records from a nested set into a real html tree

    - by Christoph Schiessl
    I'm using the awesome_nested_set plugin in my Rails project. I have two models that look like this (simplified): class Customer < ActiveRecord::Base has_many :categories end class Category < ActiveRecord::Base belongs_to :customer # Columns in the categories table: lft, rgt and parent_id acts_as_nested_set :scope => :customer_id validates_presence_of :name # Further validations... end The tree in the database is constructed as expected. All the values of parent_id, lft and rgt are correct. The tree has multiple root nodes (which is of course allowed in awesome_nested_set). Now, I want to render all categories of a given customer in a correctly sorted tree like structure: for example nested <ul> tags. This wouldn't be too difficult but I need it to be efficient (the less sql queries the better). Update: Figured out that it is possible to calculate the number of children for any given Node in the tree without further SQL queries: number_of_children = (node.rgt - node.lft - 1)/2. This doesn't solve the problem but it may prove to be helpful.

    Read the article

  • Ruby On Rails - Contact form not sending email via localhost

    - by anonymousxxx
    similar problem Rails contact form not working guides: https://github.com/thomasklemm/email_form_rails rails 3.2.x app\models\message.rb class Message include ActiveAttr::Model include ActiveModel::Validations attribute :name attribute :email attribute :subject attribute :body attr_accessible :name, :email, :subject, :body validates_presence_of :name validates_presence_of :email validates :email, email_format: { message: "is not looking like a valid email address"} validates_presence_of :subject validates_length_of :body, maximum: 500 end app\mailers\contact_form.rb class ContactForm < ActionMailer::Base default from: "[email protected]" default to: "[email protected]" def email_form(message) @message = message mail subject: "#{message.subject} #{message.name}" mail body: "#{message.body}" end end development.rb config.action_mailer.delivery_method = :smtp config.action_mailer.perform_deliveries = true config.action_mailer.smtp_settings = { :address => "smtp.gmail.com", :port => 587, :domain => "mydomain.com", :user_name => "[email protected]", :password => "mypassword", :authentication => :plain, :enable_starttls_auto => true } config.action_mailer.default_url_options = { :host => "localhost:3000" } output in command Started POST "/email" for 127.0.0.1 at 2012-09-04 22:10:40 +0700 Processing by HomeController#send_email_form as HTML Parameters: {"utf8"="v", "authenticity_token"="w39BLqCrjTMm4RRi/Sm5hZoEpcw46 npyRy/RS0h48x0=", "message"={"name"="anonymousxxx", "email"="[email protected]", "subject"="Test", "body"="send email"}, "commit"="Create Message"} Redirected to localhost:3000/home/contact Completed 302 Found in 1ms (ActiveRecord: 0.0ms) but email (message) no receive my email,..

    Read the article

  • Rails: update_attribute vs update_attributes

    - by Sam
    Object.update_attribute(:only_one_field, "Some Value") Object.update_attributes(:field1 => "value", :field2 => "value2", :field3 => "value3") Both of these will update an object without having to explicitly tell AR to update. Rails API says: for update_attribute Updates a single attribute and saves the record without going through the normal validation procedure. This is especially useful for boolean flags on existing records. The regular update_attribute method in Base is replaced with this when the validations module is mixed in, which it is by default. for update_attributes Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will fail and false will be returned. So if I don't want to have the object validated I should use update_attribute. What if I have this update on a before_save, will it stackoverflow? My question is does update_attribute also bypass the before save or just the validation. Also, what is the correct syntax to pass a hash to update_attributes... check out my example at the top.

    Read the article

  • Rails dealing with blank params at controller level

    - by stephenmurdoch
    I have a User model: class User < ActiveRecord::Base has_secure_password # validation lets users update accounts without entering password validates :password, presence: { on: :create }, allow_blank: { on: :update } validates :password_confirmation, presence: { if: :password_digest_changed? } end I also have a password_reset_controller: def update # this is emailed to the user by the create action - not shown @user=User.find_by_password_reset_token!(params[:id]) if @user.update_attributes(params[:user]) # user is signed in if password and confirmation pass validations sign_in @user redirect_to root_url, :notice => "Password has been reset." else flash.now[:error] = "Something went wrong, please try again." render :edit end end Can you see the problem here? A user can submit a blank a password/confirmation and rails will sign them in, because the User model allows blank on update. It's not a security concern, since an attacker would still need access to a user's email account before they could get anywhere near this action, but my problem is that a user submitting 6 blank chars would be signed in, and their password would not be changed for them, which could lead to confusion later on. So, I've come up with the following solution, and I'd like to check if there's a better way of doing it, before I push to production: def update @user=User.find_by_password_reset_token!(params[:id]) # if user submits blank password, add an error, and render edit action if params[:user][:password].blank? @user.errors.add(:password_digest, "can't be blank.") render :edit elsif @user.update_attributes(params[:user]) sign_in @user redirect_to root_url, :notice => "Password has been reset." else flash.now[:error] = "Something went wrong, please try again." render :edit end end Should I be checking for nil as well as blank? Are there any rails patterns or idiomatic ruby techniques for solving this? [Fwiw, I've got required: true on the html inputs, but want this handled server side too.]

    Read the article

  • User to be validated against nested security groups in Windows.

    - by user412272
    Hi, This is my first post here and after much looking around I have come here with my question. Will really appreciate a fast response. I am faced with a problem to validate user credentials of the currently logged on user against a group in Windows. The user membership to a group can be through other groups also ie nested membership. Eg. User U is a part of group G1. Group G1 is a part of another group G2. The requirement is that when the user is validated against group G2, the validations should succeed. The user can be a local or AD user but the group will always be a local group ( or domain local group if created directly on a DC). I have tried using WindowsPrincipal.IsInRole() method, but it seems to be checking only for direct membership to a group. I also tried UserPrincipal.GetAuthorizationGroups() for the current user, but it also doesnt seem to be doing recursive search. I am posting a code snippet of the working code below, but this code is taking much more than acceptable time. bool CheckUserPermissions(string groupName) { WindowsIdentity currentUserIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(); bool found = false; PrincipalContext context= new PrincipalContext(ContextType.Machine); GroupPrincipal group = GroupPrincipal.FindByIdentity(context, IdentityType.Name, groupName); if (group!= null) { foreach (Principal p in group.GetMembers(true)) { if (p.Sid == currentUserIdentity.User) { found = true; break; } } group.Dispose(); } return found; }

    Read the article

  • Jquery conditionals, window locations, and viewdata. Oh my!

    - by John Stuart
    I have one last thing left on a project and its a doozy. Not only is this my first web application, but its the first app i used Jquery, CSS and MVC. I have no idea on how to proceed with this. What i am trying to do is: In my controller, a waste item is validated, and based on the results one of these things can happen. The validation is completed, nothing bad happens, which sets ViewData["FailedWasteId"] to -9999. Its a new waste item and the validation did not pass, which sets ViewData["FailedWasteId"] to 0. Its an existing waste item and the validation did not pass, which sets ViewData["FailedWasteId"] to the id of the waste item. This ViewData["FailedWasteId"] is set on page load using <%=Html.Hidden("wFailId", int.Parse(ViewData["WasteFailID"].ToString()))%> When the validations do not pass, then the page zooms (by window.location) to an invisible div, opens the invisible div etc. Hopefully my intentions are clear with this poor attempt at jquery. The new waste div is and the existing item divs are dynamically generated (this i know works) " So my question here is... Help? I cant even get the data to parse correctly, nor can i even get the conditionals to work. And since this happens after post, i cant get firebug to help my step through the debugger, as the script isnt loaded yet. $(document).ready(function () { var wasteId = parseInt($('#wFailId').text()); if (wasteId == -9999) { //No Issue } else if (wasteId < 0) { //Waste not saved to database } else if (wasteId == 0) { //New Waste window.location = '#0'; $('.editPanel').hide(); $('#GeneratedWasteGrid:first').before(newRow); $('.editPanel').appendTo('#edit-panel-row').slideDown('slow'); } else if (wasteId > 0) { //Waste saved to database } });

    Read the article

  • Change object on client side or on server side

    - by Polina Feterman
    I'm not sure what is the best practice. I have some big and complex objects (NOT flat). In that object I have many related objects - for example Invoice is the main class and one of it's properties is invoiceSupervisor - a big class by it's own called User. User can also be not flat and have department property - also an object called Department. For example I want create new Invoice. First way: I can present to client several fields to fill in. Some of them will be combos that I will need to fill with available values. For example available invoiceSupervisors. Then all the chosen values I can send to server and on server I can create new Invoice and assign all chosen values to that new Invoice. Then I will need to assign new supervisor I will pull the chosen User by id that user picked up on server from combobox. I might do some verification on the User such as does the user applicable to be invoice supervisor. Then I will assign the User object to invoiceSupervisor. Then after filling all properties I will save the new invoice. Second way: In the beginning I can call to server to get a new Invoice. Then on client I can fill all chosen values , for example I can call to server to get new User object and then fill it's id from combobox and assign the User as invoiceSupervisor. After filling the Invoice object on client I can send it to server and then the server will save the new invoice. Before saving server can run some validations as well. So what is the best approach - to make the object on client and send it to server or to collect all values from client and to make a new object on server using those values ?

    Read the article

  • how to send on previous page where a part of html was loaded

    - by I Like PHP
    hello all, i m using Jquery ajax post method to edit a form on same page, but if there is some mistake then how do i send user back on that page where data were loaded. now i describe u what i do? i have a page manageMovies.php there are list of movie name, now when i click on a name of any movie, then i load editMovie.php on same page now when i do some mistakes( i.e when validations fails) then i want to go back on same page manageMovies.php loaded with editunit.php regarding that movie on the page. here is my page structure manageMovies.php <div id="display"></div> <div id="movieList"> <table > <tr><td id="mov_10">Apharan</td></tr> <tr><td id="mov_11">Gangaajal</td></tr> <tr><td id="mov_12">Rajniti</td></tr> </table> </div> <script type="text/javascript"> jQuery('td').click(function () { jQuery('#movieList').hide(); // hide the div 'movielist' jQuery.post('editMovie.php', { idForEdit: jQuery(this).attr('id') }, function (data) { jQuery("#display").html(data); //display the editMovie.php page on 'display' div }); }); </script> now when i do some mistakes on editunit.php and go further for post, then i need to go back on same page (manageMovies.php) where editMovie.php is shown on display div and movielist div should be hidden

    Read the article

  • Rails 2.3.4 and jquery form plugin works on development, not in production?

    - by hemajang
    Hello, i'm trying to build a contact form in Rails 2.3.4. I'm using the jQuery Form plugin along with this (http://bassistance.de/jquery-plugins/jquery-plugin-validation/) for validations. Everything works in my development environment (mac os x snow leopard), the loading gif appears and on my log the email gets sent and the "request completed" notice shows. But on my production machine the loading gif just keeps going and the form doesn't get sent. I've waited as long as I could, nothing. Here is my code: /public/javascripts/application.js // client-side validation and ajax submit contact form $('#contactForm').validate( { rules: { 'email[name]': { required: true }, 'email[address]': { required: true, email: true }, 'email[subject]': { required: true }, 'email[body]': { required: true } }, messages: { 'email[name]': "Please enter your name.", 'email[address]': "Please enter a valid email address.", 'email[subject]': "Please enter a subject.", 'email[body]': "Please enter a message." }, submitHandler: function(form) { $(form).ajaxSubmit({ dataType: 'script', beforeSend: function() { $(".loadMsg").show(); } }); return false; } }); I'm using the submitHandler to send the actual ajaxSubmit. I added the "dataType: "script" and the "beforeSubmit" for the loading graphic. def send_mail if request.post? respond_to do |wants| ContactMailer.deliver_contact_request(params[:email]) flash[:notice] = "Email was successfully sent." wants.js end end end Everything works fine on development, but not in production. What am I missing or did wrong?

    Read the article

  • has_many through and saving to join table

    - by Paul
    I have the following: class Invite < ActiveRecord::Base belongs_to :user has_many :invite_recipients has_many :recipients, :through => :invite_recipients end class InviteRecipient < ActiveRecord::Base belongs_to :invite belongs_to :user_comm validates_associated :user_comm, :invite validates_uniqueness_of :user_comm_id, :scope => :invite_id end class UserComm < ActiveRecord::Base end I'd like to create a method for Invite with invite_text and a list of UserComms as the variables and then have it create a new invite with the following validations: 1. All UserComms are unique 2. The invite isn't saved unless all the associated InviteRecipients are saved as well (in other words, the invite isn't valid unless all the created InviteRecipients are valid) I'm not familiar with how to create model functions. Moreover, when I try something like this: i = Invite.new(:invite_text => 'come join') ir1 = InviteRecipient.new(:invite => i, :user_comm => user_comm1) ir2 = InviteRecipient.new(:invite => i, :user_comm => user_comm2) i.invite_recipients = [uc1, uc2] i.save! I get: SystemStackError: stack level too deep

    Read the article

  • Your thoughts on Best Practices for Scientific Computing?

    - by John Smith
    A recent paper by Wilson et al (2014) pointed out 24 Best Practices for scientific programming. It's worth to have a look. I would like to hear opinions about these points from experienced programmers in scientific data analysis. Do you think these advices are helpful and practical? Or are they good only in an ideal world? Wilson G, Aruliah DA, Brown CT, Chue Hong NP, Davis M, Guy RT, Haddock SHD, Huff KD, Mitchell IM, Plumbley MD, Waugh B, White EP, Wilson P (2014) Best Practices for Scientific Computing. PLoS Biol 12:e1001745. http://www.plosbiology.org/article/info%3Adoi%2F10.1371%2Fjournal.pbio.1001745 Box 1. Summary of Best Practices Write programs for people, not computers. (a) A program should not require its readers to hold more than a handful of facts in memory at once. (b) Make names consistent, distinctive, and meaningful. (c) Make code style and formatting consistent. Let the computer do the work. (a) Make the computer repeat tasks. (b) Save recent commands in a file for re-use. (c) Use a build tool to automate workflows. Make incremental changes. (a) Work in small steps with frequent feedback and course correction. (b) Use a version control system. (c) Put everything that has been created manually in version control. Don’t repeat yourself (or others). (a) Every piece of data must have a single authoritative representation in the system. (b) Modularize code rather than copying and pasting. (c) Re-use code instead of rewriting it. Plan for mistakes. (a) Add assertions to programs to check their operation. (b) Use an off-the-shelf unit testing library. (c) Turn bugs into test cases. (d) Use a symbolic debugger. Optimize software only after it works correctly. (a) Use a profiler to identify bottlenecks. (b) Write code in the highest-level language possible. Document design and purpose, not mechanics. (a) Document interfaces and reasons, not implementations. (b) Refactor code in preference to explaining how it works. (c) Embed the documentation for a piece of software in that software. Collaborate. (a) Use pre-merge code reviews. (b) Use pair programming when bringing someone new up to speed and when tackling particularly tricky problems. (c) Use an issue tracking tool. I'm relatively new to serious programming for scientific data analysis. When I tried to write code for pilot analyses of some of my data last year, I encountered tremendous amount of bugs both in my code and data. Bugs and errors had been around me all the time, but this time it was somewhat overwhelming. I managed to crunch the numbers at last, but I thought I couldn't put up with this mess any longer. Some actions must be taken. Without a sophisticated guide like the article above, I started to adopt "defensive style" of programming since then. A book titled "The Art of Readable Code" helped me a lot. I deployed meticulous input validations or assertions for every function, renamed a lot of variables and functions for better readability, and extracted many subroutines as reusable functions. Recently, I introduced Git and SourceTree for version control. At the moment, because my co-workers are much more reluctant about these issues, the collaboration practices (8a,b,c) have not been introduced. Actually, as the authors admitted, because all of these practices take some amount of time and effort to introduce, it may be generally hard to persuade your reluctant collaborators to comply them. I think I'm asking your opinions because I still suffer from many bugs despite all my effort on many of these practices. Bug fix may be, or should be, faster than before, but I couldn't really measure the improvement. Moreover, much of my time has been invested on defence, meaning that I haven't actually done much data analysis (offence) these days. Where is the point I should stop at in terms of productivity? I've already deployed: 1a,b,c, 2a, 3a,b,c, 4b,c, 5a,d, 6a,b, 7a,7b I'm about to have a go at: 5b,c Not yet: 2b,c, 4a, 7c, 8a,b,c (I could not really see the advantage of using GNU make (2c) for my purpose. Could anyone tell me how it helps my work with MATLAB?)

    Read the article

  • Anti-Forgery Request in ASP.NET MVC and AJAX

    - by Dixin
    Background To secure websites from cross-site request forgery (CSRF, or XSRF) attack, ASP.NET MVC provides an excellent mechanism: The server prints tokens to cookie and inside the form; When the form is submitted to server, token in cookie and token inside the form are sent by the HTTP request; Server validates the tokens. To print tokens to browser, just invoke HtmlHelper.AntiForgeryToken():<% using (Html.BeginForm()) { %> <%: this.Html.AntiForgeryToken(Constants.AntiForgeryTokenSalt)%> <%-- Other fields. --%> <input type="submit" value="Submit" /> <% } %> which writes to token to the form:<form action="..." method="post"> <input name="__RequestVerificationToken" type="hidden" value="J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP" /> <!-- Other fields. --> <input type="submit" value="Submit" /> </form> and the cookie: __RequestVerificationToken_Lw__=J56khgCvbE3bVcsCSZkNVuH9Cclm9SSIT/ywruFsXEgmV8CL2eW5C/gGsQUf/YuP When the above form is submitted, they are both sent to server. [ValidateAntiForgeryToken] attribute is used to specify the controllers or actions to validate them:[HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult Action(/* ... */) { // ... } This is very productive for form scenarios. But recently, when resolving security vulnerabilities for Web products, I encountered 2 problems: It is expected to add [ValidateAntiForgeryToken] to each controller, but actually I have to add it for each POST actions, which is a little crazy; After anti-forgery validation is turned on for server side, AJAX POST requests will consistently fail. Specify validation on controller (not on each action) Problem For the first problem, usually a controller contains actions for both HTTP GET and HTTP POST requests, and usually validations are expected for HTTP POST requests. So, if the [ValidateAntiForgeryToken] is declared on the controller, the HTTP GET requests become always invalid:[ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public class SomeController : Controller { [HttpGet] public ActionResult Index() // Index page cannot work at all. { // ... } [HttpPost] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] public ActionResult PostAction2(/* ... */) { // ... } // ... } If user sends a HTTP GET request from a link: http://Site/Some/Index, validation definitely fails, because no token is provided. So the result is, [ValidateAntiForgeryToken] attribute must be distributed to each HTTP POST action in the application:public class SomeController : Controller { [HttpGet] public ActionResult Index() // Works. { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction1(/* ... */) { // ... } [HttpPost] [ValidateAntiForgeryToken(Salt = Constants.AntiForgeryTokenSalt)] public ActionResult PostAction2(/* ... */) { // ... } // ... } Solution To avoid a large number of [ValidateAntiForgeryToken] attributes (one attribute for one HTTP POST action), I created a wrapper class of ValidateAntiForgeryTokenAttribute, where HTTP verbs can be specified:[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class ValidateAntiForgeryTokenWrapperAttribute : FilterAttribute, IAuthorizationFilter { private readonly ValidateAntiForgeryTokenAttribute _validator; private readonly AcceptVerbsAttribute _verbs; public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs) : this(verbs, null) { } public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs, string salt) { this._verbs = new AcceptVerbsAttribute(verbs); this._validator = new ValidateAntiForgeryTokenAttribute() { Salt = salt }; } public void OnAuthorization(AuthorizationContext filterContext) { string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride(); if (this._verbs.Verbs.Contains(httpMethodOverride, StringComparer.OrdinalIgnoreCase)) { this._validator.OnAuthorization(filterContext); } } } When this attribute is declared on controller, only HTTP requests with the specified verbs are validated:[ValidateAntiForgeryTokenWrapper(HttpVerbs.Post, Constants.AntiForgeryTokenSalt)] public class SomeController : Controller { // Actions for HTTP GET requests are not affected. // Only HTTP POST requests are validated. } Now one single attribute on controller turns on validation for all HTTP POST actions. Submit token via AJAX Problem For AJAX scenarios, when request is sent by JavaScript instead of form:$.post(url, { productName: "Tofu", categoryId: 1 // Token is not posted. }, callback); This kind of AJAX POST requests will always be invalid, because server side code cannot see the token in the posted data. Solution The token must be printed to browser then submitted back to server. So first of all, HtmlHelper.AntiForgeryToken() must be called in the page where the AJAX POST will be sent. Then jQuery must find the printed token in the page, and post it:$.post(url, { productName: "Tofu", categoryId: 1, __RequestVerificationToken: getToken() // Token is posted. }, callback); To be reusable, this can be encapsulated in a tiny jQuery plugin:(function ($) { $.getAntiForgeryToken = function () { // HtmlHelper.AntiForgeryToken() must be invoked to print the token. return $("input[type='hidden'][name='__RequestVerificationToken']").val(); }; var addToken = function (data) { // Converts data if not already a string. if (data && typeof data !== "string") { data = $.param(data); } data = data ? data + "&" : ""; return data + "__RequestVerificationToken=" + encodeURIComponent($.getAntiForgeryToken()); }; $.postAntiForgery = function (url, data, callback, type) { return $.post(url, addToken(data), callback, type); }; $.ajaxAntiForgery = function (settings) { settings.data = addToken(settings.data); return $.ajax(settings); }; })(jQuery); Then in the application just replace $.post() invocation with $.postAntiForgery(), and replace $.ajax() instead of $.ajaxAntiForgery():$.postAntiForgery(url, { productName: "Tofu", categoryId: 1 }, callback); // Token is posted. This solution looks hard coded and stupid. If you have more elegant solution, please do tell me.

    Read the article

  • XBRL - Moving from Production to Consumption

    - by jmorourke
    Here's an update on what’s new with XBRL and how it can actually benefit your organization versus adding extra time and costs to financial reporting.  On February 29th (leap day) of 2012 I attended the XBRL and Financial Analysis Technology Conference at Baruch College in NYC.  The event, which attracted over 300 XBRL gurus and fans was presented by XBRL US, The New York Society of Security Analysts’ Improved Corporate Reporting Committee, and Baruch College’s Robert Zicklin Center for Corporate Integrity.  The event featured keynotes from the U.S. Securities and Exchange Commission (SEC), and the CFA Institute as well as panels covering alternative research tools and data, corporate reporting to stakeholders and a demonstration of XBRL analysis tools.  The program culminated in a presentation of the finalists and the winner of the $20,000 XBRL Challenge.    Some of the key points made in the sessions included: The focus of XBRL tools is moving from production to consumption. As of February 2012, over 9000 companies are reporting in XBRL, with over 10 million facts filed to date XBRL taxonomy extensions have dropped from 27% to 11% making comparisons easier The SEC reports that XBRL makes it easier to analyze disclosures, focus on accounting issues XBRL is helping standards-setters like the FASB speed their analysis of impacts of proposed accounting rule changes Companies like Thomson Reuters report that XBRL is helping speed the delivery of data to clients The most interesting part of the program though, was the session highlighting the 5 finalists in the XBRL Challenge competition and the winning solution.  The XBRL Challenge was launched in 2011 as a means of spurring the development of more end-user tools to help with the consumption of XBRL-based financial information.       Over an 8-month process handled by 5 judges, there were 84 registrants, 15 completed submissions, 5 finalists and one winner of the challenge.  All of the solutions are open-sourced tools and most of them focus on consuming XBRL-based data.  The 5 finalists included: Advanced XBRL Processing from Oxide solutions – XBRL viewer for taxonomies, filings and company data with peer comparison capabilities. Arrelle – API for XBRL processes, supports SEC Validations, RSS Feeds to access filings etc. Calcbench – XBRL data analysis tool that can be embedded in other web applications.  This tool can combine XBRL filings with real-time market data. XBRL to XL – allows the importing of XBRL data into Microsoft Excel for analysis, comparisons.  Users start on the web and populate Excel with XBRL data. XBurble – allows users to search and view XBRL filings, export to Excel, merge for comparison, and includes a workflow interface. The winner of the $20,000 XBRL Challenge prize was CalcBench.  More information about the XBRL Challenge and the finalists can be found at www.XBRLUS.org/challenge XBRL for Sustainability Reporting – other recent news on the XBRL front was the announcement by the Global Reporting Initiative (GRI) of an XBRL taxonomy for Sustainability Reporting.  This taxonomy was co-developed by the GRI and Deloitte and is designed to make the consumption of data found in Sustainability Reports much easier.  Although there is no government mandate to file Sustainability Reports in XBRL format, organizations that do use the GRI guidelines for Sustainability Reporting are encouraged to tag and submit their data voluntarily to the GRI – who will populate a database with Sustainability Reporting data and make this available to the public.  For more information about this initiative, you can go to the GRI web site:  www.globalreporting.org. So how does all of this benefit corporate filers and investors?  Since its introduction, the consensus in the market is that XBRL has mainly benefited the regulators and investment analysts who need to consume and analyze large volumes of financial data.  But with the emergence of more end-user tools for consuming and analyzing XBRL-based data, and the ability to perform quick comparisons of one company versus its peers and competitors in an industry group, will soon accelerate the benefits to corporate finance staff, as well as individual investors.  This could apply to financial results tagged in XBRL, as well as non-financial information such as Sustainability Reporting – which over the long-term will likely be integrated with financial reporting.   And as multiple regulators and agencies in a country adopt the XBRL standard for corporate filings, more benefits will accrue as companies will be able to leverage one set of XBRL-based financial data for multiple regulatory filings.     For more information about the latest developments in XBRL, check out the XBRL US or XBRL International web sites:  www.xbrl.org, www.xbrlus.org. For more information about what Oracle is doing to support XBRL, here are some links: http://www.oracle.com/us/solutions/ent-performance-bi/disclosure-management-065892.html http://www.oracle.com/technetwork/database/features/xmldb/index-087631.html Feel free to contact me if you have any questions or need more information:  [email protected]

    Read the article

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