Search Results

Search found 996 results on 40 pages for 'ryan hayes'.

Page 39/40 | < Previous Page | 35 36 37 38 39 40  | Next Page >

  • How to add and remove nested model fields dynamically using Haml and Formtastic

    - by Brightbyte8
    We've all seen the brilliant complex forms railscast where Ryan Bates explains how to dynamically add or remove nested objects within the parent object form using Javascript. Has anyone got any ideas about how these methods need to be modified so as to work with Haml Formtastic? To add some context here's a simplified version of the problem I'm currently facing: # Teacher form (which has nested subject forms) [from my application] - semantic_form_for(@teacher) do |form| - form.inputs do = form.input :first_name = form.input :surname = form.input :city = render 'subject_fields', :form => form = link_to_add_fields "Add Subject", form, :subjects # Individual Subject form partial [from my application] - form.fields_for :subjects do |ff| #subject_field = ff.input :name = ff.input :exam = ff.input :level = ff.hidden_field :_destroy = link_to_remove_fields "Remove Subject", ff # Application Helper (straight from Railscasts) def link_to_remove_fields(name, f) f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)") end def link_to_add_fields(name, f, association) new_object = f.object.class.reflect_on_association(association).klass.new fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder| render(association.to_s.singularize + "_fields", :f => builder) end link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)} \")")) end #Application.js (straight from Railscasts) function remove_fields(link) { $(link).previous("input[type=hidden]").value = "1"; $(link).up(".fields").hide(); } function add_fields(link, association, content) { var new_id = new Date().getTime(); var regexp = new RegExp("new_" + association, "g") $(link).up().insert({ before: content.replace(regexp, new_id) }); } The problem with implementation seems to be with the javascript methods - the DOM tree of a Formtastic form differs greatly from a regular rails form. I've seen this question asked online a few times but haven't come across an answer yet - now you know that help will be appreciated by more than just me! Jack

    Read the article

  • iOS iPad UIActionSheet Issue

    - by hart1994
    I am currently developing an application which needs an option to 'share' using multiple services; such as email, twitter. To to this, I have a UIBarButtonItem coded in and when touched, it triggers this: UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil]; [sheet addButtonWithTitle:@"Email"]; [sheet addButtonWithTitle:@"Tweet"]; [sheet addButtonWithTitle:@"Cancel"]; sheet.cancelButtonIndex = sheet.numberOfButtons-1; [sheet showFromRect:self.view.bounds inView:self.view animated:YES]; [sheet release]; In conjunction with this to detect which button is selected: clickedButtonAtIndex:(NSInteger)buttonIndex { if (buttonIndex == actionSheet.cancelButtonIndex) { return; } switch (buttonIndex) { case 0: { [self emailThis]; break; } case 1: { [self tweetThis]; break; } } This works a treat on the iPhone. But unfortunately it displays incorrectly on the iPad. It looks like it is trying to display the UIPopoverController, but it is positioned center of the navbar with practically no height. I have looked into using the UIPopoverController, but I cannot seem to find out how to use it with buttons. Is there anyway I can adapt the code above to properly display the buttons, as it's trying to already. Many thanks, Ryan PS: I'm new to objective-c/iOS coding, so please be specific. Thank you :)

    Read the article

  • Using Lambda Expressions trees with IEnumerable

    - by Loathian
    I've been trying to learn more about using Lamba expression trees and so I created a simple example. Here is the code, this works in LINQPad if pasted in as a C# program. void Main() { IEnumerable<User> list = GetUsers().Where(NameContains("a")); list.Dump("Users"); } // Methods public IEnumerable<User> GetUsers() { yield return new User{Name = "andrew"}; yield return new User{Name = "rob"}; yield return new User{Name = "chris"}; yield return new User{Name = "ryan"}; } public Expression<Func<User, bool>> NameContains(string namePart) { return u => u.Name.Contains(namePart); } // Classes public class User { public string Name { get; set; } } This results in the following error: The type arguments for method 'System.Linq.Enumerable.Where(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly. However if I just substitute the first line in main with this: IEnumerable<User> list = GetUsers().Where(u => u.Name.Contains("a")); It works fine. Can tell me what I'm doing wrong, please?

    Read the article

  • accepts_nested_attributes_for and nested_form plugin

    - by Denis
    Hi folks, I've the following code in a _form.html.haml partial, it's used for new and edit actions. (fyi I use the Ryan Bates' plugin nested_form) .fields - f.fields_for :transportations do |builder| = builder.collection_select :person_id, @people, :id, :name, {:multiple => true} = builder.link_to_remove 'effacer' = f.link_to_add "ajouter", :transportations works fine for the new action... for the edit action, as explain in the doc, I've to add the :id of already existing associations, so, I've to add something like = builder.hidden_field :id, ?the value? if ?.new_record? How can I get the value? Here is the doc of accepts_nested_attributes_for for reference (source: http://github.com/rails/rails/blob/master/activerecord/lib/active_record/nested_attributes.rb#L332) # Assigns the given attributes to the collection association. # # Hashes with an <tt>:id</tt> value matching an existing associated record # will update that record. Hashes without an <tt>:id</tt> value will build # a new record for the association. Hashes with a matching <tt>:id</tt> # value and a <tt>:_destroy</tt> key set to a truthy value will mark the # matched record for destruction. # # For example: # # assign_nested_attributes_for_collection_association(:people, { # '1' => { :id => '1', :name => 'Peter' }, # '2' => { :name => 'John' }, # '3' => { :id => '2', :_destroy => true } # }) # # Will update the name of the Person with ID 1, build a new associated # person with the name `John', and mark the associatied Person with ID 2 # for destruction. # # Also accepts an Array of attribute hashes: # # assign_nested_attributes_for_collection_association(:people, [ # { :id => '1', :name => 'Peter' }, # { :name => 'John' }, # { :id => '2', :_destroy => true } # ]) Thanks for your help.

    Read the article

  • Python Twitter library: which one?

    - by Parand
    I realize this is a bit of a lazyweb question, but I wanted to see which python library for Twitter people have had good experiences with. I've used Python Twitter Tools and like its brevity and beauty of interface, but it doesn't seem to be one of the popular ones - it's not even listed on the Twitter Libraries page. There are, however, plenty of others listed: oauth-python-twitter2 by Konpaku Kogasa. Combines python-twitter and oauth-python-twitter to create an evolved OAuth Pokemon. python-twitter by DeWitt Clinton. This library provides a pure Python interface for the Twitter API. python-twyt by Andrew Price. BSD licensed Twitter API interface library and command line client. twitty-twister by Dustin Sallings. A Twisted interface to Twitter. twython by Ryan McGrath. REST and Search library inspired by python-twitter. Tweepy by Josh Roesslein. Supports OAuth, Search API, Streaming API. My requirements are fairly simple: Be able to use OAuth Be able to follow a user Be able to send a direct message Be able to post Streaming API would be nice Twisted one aside (I'm not using twisted in this case), have you used any of the others, and if so, do you recommend them? [Update] FWIW, I ended up going with Python Twitter Tools again. The new version supported OAuth nicely, and it's a very clever API, so I stuck to it.

    Read the article

  • jQuery accordion - different image for active sections

    - by Andrew Cassidy
    Hi, I'm using Ryan Stemkoski's "Stupid Simple Jquery Accordion Menu" which is available here: stemkoski.com/stupid-simple-jquery-accordion-menu/ Here is the javascript $(document).ready(function() { //ACCORDION BUTTON ACTION (ON CLICK DO THE FOLLOWING) $('.accordionButton').click(function() { //REMOVE THE ON CLASS FROM ALL BUTTONS $('.accordionButton').removeClass('on'); //NO MATTER WHAT WE CLOSE ALL OPEN SLIDES $('.accordionContent').slideUp('normal'); //IF THE NEXT SLIDE WASN'T OPEN THEN OPEN IT if($(this).next().is(':hidden') == true) { //ADD THE ON CLASS TO THE BUTTON $(this).addClass('on'); //OPEN THE SLIDE $(this).next().slideDown('normal'); } }); /*** REMOVE IF MOUSEOVER IS NOT REQUIRED ***/ //ADDS THE .OVER CLASS FROM THE STYLESHEET ON MOUSEOVER $('.accordionButton').mouseover(function() { $(this).addClass('over'); //ON MOUSEOUT REMOVE THE OVER CLASS }).mouseout(function() { $(this).removeClass('over'); }); /*** END REMOVE IF MOUSEOVER IS NOT REQUIRED ***/ /******************************************************************************************************************** CLOSES ALL S ON PAGE LOAD ********************************************************************************************************************/ $('.accordionContent').hide(); }); and the CSS #wrapper { width: 800px; margin-left: auto; margin-right: auto; } .accordionButton { width: 800px; float: left; _float: none; /* Float works in all browsers but IE6 */ background: #003366; border-bottom: 1px solid #FFFFFF; cursor: pointer; } .accordionContent { width: 800px; float: left; _float: none; /* Float works in all browsers but IE6 */ background: #95B1CE; } /*********************************************************************************************************************** EXTRA STYLES ADDED FOR MOUSEOVER / ACTIVE EVENTS ************************************************************************************************************************/ .on { background: #990000; } .over { background: #CCCCCC; } There is an "on" class which allows the style of the accordionButton class when it is active but I would like to be able to have each active accordionButton class have a different image. http://www.thepool.ie For example, in the above site the word "WORK" should be a darker grey image when the work section is selected, so should COLLAB when it is selected etc. I can't figure out how to do this, any help would be greatly appreciated. Thanks, Andrew

    Read the article

  • Core Data - How to check if a managed object's properties have been deallocated?

    - by georryan
    I've created a program that uses core data and it works beautifully. I've since attempted to move all my core data methods calls and fetch routines into a class that is self contained. My main program then instantiates that class and makes some basic method calls into that class, and the class then does all the core data stuff behind the scenes. What I'm running into, is that sometimes I'll find that when I grab a managed object from the context, I'll have a valid object, but its properties have been deallocated, and I'll cause a crash. I've played with the zombies and looked for memory leaks, and what I have gathered is it seems that the run loop is probably responsible for deallocating the memory, but I'm not sure. Is there a way to determine if that memory has been deallocated and force the core data to get it back if I need to access it? My managedObjectContext never gets deallocated, and the fetchedResultsController never does, either. I thought maybe I needed to use the [managedObjectContext refreshObject:mergeData:] method, or the [managedObjectContext setRetainsRegisteredObjects:] method. Although, I'm under the impression that last one may not be the best bet since it will be more memory intensive (from what I understand). These errors only popped up when I moved the core data calls into another class file, and they are random when they show up. Any insight would be appreciated. -Ryan

    Read the article

  • Updating multiple divs w/ RJS/AJAX

    - by bgadoci
    I am successfully using RJS to implement AJAX on a page.replace.html create.js.rjs. I am attempting to update two locations instead of one and after watching Ryan Bates Railscast I am very close (I think) but have a problem in the syntax of my /views/likes/create.js.rjs file. Here is the situation: located at /views/likes/create.js.rjs is the following code: page.replace_html "votes_#{ @site.id }", :partial => @like page.replace_html "counter", 10 - (@question.likes.count :conditions => {:user_id => current_user.id}) page[@like].visual_effect :highlight My problem lies in the second line. The div "counter" displays the following code in the /views/question/show.html.erb page: <div id="counter"> You have <%= 10 - (@question.likes.count :conditions => {:user_id => current_user.id}) %> votes remaining for this question </div> From watching the screen cast I believe that my error has to do w/ the syntax of the second line. Specifically he mentions that you cannot use a local instance variable but not sure how to make the change. Thoughts?

    Read the article

  • How can I search an XML file without a dynamic language?

    - by jeph perro
    Let me try to explain my situation: We are using a CMS which 'bakes' a website, and you publish it to a webserver. The published site contains only static HTML ( or XML ) pages ( generated from the content in the CMS database ). I imported an XML file with the names and phone numbers from the company phone directory. Using only XSLT, can I create a way to search that directory? For example, if my XML file, directory.xml looks like this: <directory> <person> <fname>Ryan</fname> <lname>Purple</lname> <phone>887 778 5544</phone> </person> <person> <fname>Tanya</fname> <lname>Orange</lname> <phone>887 998 5541</phone> </person> <directory> Can I create a way to search for a person with the last name starting with "Pur" ? Can I pass a parameter to the XSLT? Can I search the XML tree to match the string in the parameter?

    Read the article

  • Problem with Railscast #197 - Nested Model Form Part 2

    - by sscirrus
    I'm trying to implement Ryan's Railscast #197 in a system with Questions, Answers, and (multiple choice) Options. http://railscasts.com/episodes/197-nested-model-form-part-2. I have successfully implemented the nesting among these forms/partials. The simpler 'check box' way to delete records works properly. The problem occurs when I try to add/delete records. I have copied the code exactly as it appears in his Railscast: #new.html.erb <%= javascript_include_tag :defaults, :cache => true %> <% f.fields_for :in_options do |builder| %> <%= render "option_fields", :f => builder %> <% end %> #_option_fields.html.erb partial <%= f.hidden_field :_destroy %> <%= link_to_function "remove", "remove_fields(this)" %> #application_helper.rb (exact same as #197) def link_to_remove_fields(name, f) f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)") end def link_to_add_fields(name, f, association) new_object = f.object.class.reflect_on_association(association).klass.new fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder| render(association.to_s.singularize + "_fields", :f => builder) end link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")) end #application.js (exact same as #197. I have an Event.addbehavior below this code.) function remove_fields(link) { $(link).previous("input[type=hidden]").value = "1"; $(link).up(".fields").hide(); } function add_fields(link, association, content) { var new_id = new Date().getTime(); var regexp = new RegExp("new_" + association, "g") $(link).up().insert({ before: content.replace(regexp, new_id) }); } 2 problems: When I click on the 'remove' link it doesn't remove - it just shifts the page up or down. When I include link_to_add_fields "Add Answer", f, :answers, I get undefined method `klass' for nil:NilClass. Thanks everyone.

    Read the article

  • Rails: Multi-Step New User Signup Form (FSM?)

    - by neezer
    I've read the "Create Multi-Step Wizard" in Advanced Rails Recipes. I've also read and re-read the documentation for the updated FSM I'm using called Workflow, and looked here and here. The Advanced Rails Recipe focuses on records (quizzes) that already exist, and doesn't cover creating new ones. The Workflow docs don't cover any code for controllers or views, so I've no idea what to do with all this model magic, and the last two links barely touch on implementation either. From the aforementioned resources, I have a good understanding of what a FSM in Rails is and how to play with it in the console or IRB, but I've got very little direction or understanding how to implement one into my Rails app. What I would like is this: a simple, multi-step user signup process. Step 1: User enters in their critical details (with validations). Step 2: User enters in their search criteria, for their profile (with validations). Step 3: User agrees to the Terms of Service (with validations). Step 4: User is greeted by a confirmation page, including a link that takes them to their newly created account. I'd also like full navigation between the steps and full capture (saves to the database) with each transition. Can someone please give me a clear implementation of something similar to this? I would LOVE an example app that includes a multi-step signup process where I can look at the code (FULL source code--models AND controllers and views) under the hood, but I've been unable to find anything like that. Any guidance would be appreciated! EDIT: Please help make this a Railscast! Ryan B. (a.k.a. Superman), if you're reading this, we need you! http://feedback.railscasts.com/forums/77-episode-suggestions/suggestions/35553-multi-step-forms-and-wizards

    Read the article

  • Dynamic select menu Rails, Javascript HABTM

    - by Jack
    Hi, I am following a tutorial in one of Ryan Bates' Railscasts here. Basically I want a form where there are 2 drop down menus, the contents of one are dependent on the other. I have Years and Courses, where Years HABMT Courses and Courses HABTM Years. In the tutorial, the javascript is as follows: var states = new Array(); <% for state in @states -%> states.push(new Array(<%= state.country_id %>, '<%=h state.name %>', <%= state.id %>)); <% end -%> function countrySelected() { country_id = $('person_country_id').getValue(); options = $('person_state_id').options; options.length = 1; states.each(function(state) { if (state[0] == country_id) { options[options.length] = new Option(state[1], state[2]); } }); if (options.length == 1) { $('state_field').hide(); } else { $('state_field').show(); } } document.observe('dom:loaded', function() { countrySelected(); $('person_country_id').observe('change', countrySelected); }); Where I guess country has many states and state belongs to country. I think what I need to do is edit the first for statement to somehow loop through all of the courses for each year_id, but don't know how to do this. Any ideas? Thanks

    Read the article

  • How do I perform this MutliArray setup in Java?

    - by Andy Barlow
    I come from a PHP background and I'm just getting my teeth into some Java. I was wondering how I could implement the following in Java as simply as possible, just echoing the results to a terminal via the usual "System.out.print()" method. <?php $Results[0]['title'] = "No Country for Old Men"; $Results[0]['run_time'] = "122 mins"; $Results[0]['cert'] = "15"; $Results[1]['title'] = "Old School"; $Results[1]['run_time'] = "88 mins"; $Results[1]['cert'] = "18"; // Will basically show the above in order. foreach($Results as value) { echo $Results[$value]['title']; echo $Results[$value]['run_time']; echo $Results[$value]['cert']; } // Lets add some more as I need to do this in Java too $Results[2]['title'] = "Saving Private Ryan"; $Results[2]['run_time'] = "153 mins"; $Results[2]['cert'] = "15"; // Lets remove the first one as an example of another need $Results[0] = null; ?> I hear there are "list iterators" or something that are really good for rolling through data like this. Perhaps it could be implemented with that? A fully working .java file would be most handy in this instance, including how to add and remove items from the array like the above. P.S. I do plan on using this for an Android App in the distant future, so, hopefully it should all work on Android fine too, although, I imagine this sort of thing works on anything Java related :).

    Read the article

  • How to do HABTM management with auto completion in Rails?

    - by Andrei
    I am looking for a good solution for a probably typical problem of managing models with HABTM association in Rails. Let's assume that we have two models -- products and categories: Products has_many :categorizations has_many :categories, :through => :categorizations Categories has_many :categorizations has_many :products, :through => :categorizations Categorization belongs_to :product belongs_to :category Pat Shaughnessy is developing modified auto_complete plugin which can allow to manage one-to-many (and many-to-many) association: For someone that would be enough, but I don't really like so many text fields. I guess it is possible to combine the Ryan Bates' screencasts used by Pat in a slightly different way, namely, using one text field with autocomplete: Also it would be better to remove from the list of suggested tasks (one-to-many), or products|categories (many-to-many) those which have been already added. In the case of products-categories relationship, such auto completion would be used both in the form for product, and in the form for category. I hope that there is an existing plugin for that. I am not very experienced in Ruby, and don't really know how to implement such logic by myself. Any help is appreciated!

    Read the article

  • Rails can't find my route but it exists!

    - by DJTripleThreat
    Ok I have events that I want to publish/unpublish with an extra action (nonRESTful) I watched Ryan Bates' railscast on this: http://railscasts.com/episodes/35-custom-rest-actions and it got me most of the way. I think the problem is that my route is nested in an /admin section so even though when I run rake routes and get: publish_admin_event PUT /admin/events/:id/publish(.:format) {:controller=>"event_services", :action=>"publish"} This won't work in my /views/admin/index.html.erb file: <%= link_to 'Publish', publish_admin_event(event), :method => :put %> because it claims that path doesn't exist! And neither will this: <%= link_to 'Publish', {:controller => :event_services, :action => :publish}, {:method => :put, :id => event} %> and says that "No route matches {:controller=>"event_services", :action=>"publish"}" so what gives? (And I've tried restarting my server so that isn't it.) EDIT: This DOES work: <%= link_to 'Publish', "/admin/events/" + event.id.to_s + "/publish", :method => :put %> But I'd rather NOT do this.

    Read the article

  • Read quicktime movie from servlet in a webpage?

    - by khue
    Hi, I have a servlet that construct response to a media file request by reading the file from server: File uploadFile = new File("C:\\TEMP\\movie.mov"); FileInputStream in = new FileInputStream(uploadFile); Then write that stream to the response stream. My question is how do I play the media file in the webpage using embed or object tag to read the media stream from the response? Here is my code in the servlet: public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.getParameter("location"); uploadFile(response); } private void uploadFile(HttpServletResponse response) { File transferFile = new File("C:/TEMP/captured.mov"); FileInputStream in = null; try { in = new FileInputStream(transferFile); } catch (FileNotFoundException e) { System.out.println("File not found"); } try { System.out.println("in byes i s" + in.available()); } catch (IOException e) { } DataOutputStream responseStream = null; try { responseStream = new DataOutputStream(response.getOutputStream()); } catch (IOException e) { System.out.println("Io exception"); } try { Util.copyStream(in, responseStream); } catch (CopyStreamException e) { System.out.println("copy Stream exception"); } try { responseStream.flush(); } catch (IOException e) { } try { responseStream.close(); } catch (IOException e) { } } And here is html page as Ryan suggested: <embed SRC="http://localhost:7101/movies/transferservlet" WIDTH=100 HEIGHT=196 AUTOPLAY=true CONTROLLER=true LOOP=false PLUGINSPAGE="http://www.apple.com/quicktime/"> Any ideas?

    Read the article

  • PHP: json_decode dumping NULL, BOM not found

    - by SerEnder
    I've been trying to find out why this 'json_encode'd string isn't parsing out correctly, and came across previously answered questions that had the UTF BOM sequence that was throwing the error, but didn't help me here. Here's the code that isn't currently working: //Decode the notes attached to the sig $aNotes = json_decode($rule->getNotes(),true); $bom = pack("CCC",0xef,0xbb,0xbf); if(0 == strncmp($rule->getNotes(),$bom,3)) { print('BOM detected - json encoding in UTF-8<br/>'); } else { print('BOM NOT detected - json encoding correctly<br/>'); } print('rule->getNotes:<br/>' . $rule->getNotes() .'<br/>'); var_dump($aNotes); Which generates this result: BOM NOT detected - json encoding correctly rule->getNotes: [{"lDate":"Unknown","sAuthor":"Unknown","sNote":"This is a general purpose Russian spam rule that matches anything starting with 2, 3 or 4 hex digits followed by a domain name ending with .ru -RSK 2010-05-10"},{"lDate":"1295031463082","sAuthor":"Drew Thorstenson","sNote":"this is Ryan's ru rule"}] NULL I've run it through JSON Lint, which said it was valid, and An Online JSON Parser which parsed it correctly too. Any insight would be greatly appreciated.

    Read the article

  • iOS Cell Label link

    - by hart1994
    Hi I am new to iOS programming and I need a little help. I have a table view cell which is populated by data from a .plist file. I need to be able to make a link within one of the cells. How could I do this? Here is the code which is loading the data into the cells: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"CustomTableCell"; static NSString *CellNib = @"DetailViewCell"; DetailViewCell *cell = (DetailViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellNib owner:self options:nil]; cell = (DetailViewCell *)[nib objectAtIndex:0]; } cell.accessoryType = UITableViewCellAccessoryNone; cell.cellTitleLabel.textColor = [UIColor blackColor]; cell.cellTitleLabel.font = [UIFont systemFontOfSize:20.0]; cell.cellSubtitleLabel.textColor = [UIColor darkGrayColor]; informations = [[NSArray alloc] initWithObjects:@"City", @"Country", @"State", @"History", @"Link", nil]; subtitles = [[NSArray alloc] initWithObjects:titleString, subtitleString, stateString, populationString, @"Link", nil]; cell.cellTitleLabel.text = [informations objectAtIndex:indexPath.row]; cell.cellSubtitleLabel.text = [subtitles objectAtIndex:indexPath.row]; return (DetailViewCell *) cell; } For the cell "Link" I need it to open a url which is stored in the .plist file. How could i do this? Many thanks Ryan PS: I'm a newbie at this stuff, so be descriptive. Thanks

    Read the article

  • NullPointerException with Servlet

    - by RonaDona
    I am calling a Servlet using its URL address. This is the URL I am typing http://localhost:7001/ryan/olympics?action=selectCatalog&id=1 This is the Servlet's URL for sure; if I change the address I get page not found This is the code for the Servlet. public class Servlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { private static final long serialVersionUID = 1L; public Servlet() { super(); } public void init(ServletConfig config) throws ServletException { System.out.println("*** initializing controller servlet."); super.init(config); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if (action.equals("selectCatalog")) { String categoryId = request.getParameter("id"); ProductModelDAO dao4 = new ProductModelDAOImpl("jpac"); if (categoryId != null && !categoryId.trim().equals("")) { CategoryDAO dao1 = new CategoryDAOImpl("jpac"); try { Category category = dao1.getCategoryName(categoryId); request.setAttribute("category", category); } catch (Exception e) { e.printStackTrace(); } } try { @SuppressWarnings("unchecked") List<Product> products = dao4 .getProductsByCategory(categoryId); request.setAttribute("products", products); } catch (Exception e) { e.printStackTrace(); } url = "SelectCatalog.jsp"; RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(url); requestDispatcher.forward(request, response); I get the NullPointerException pointing to the RequestDispatcher's line. Any help?

    Read the article

  • Client-Side Dynamic Removal of <script> Tags in <head>

    - by merv
    Is it possible to remove script tags in the <head> of an HTML document client-side and prior to execution of those tags? On the server-side I am able to insert a <script> above all other <script> tags in the <head>, except one, and I would like to be able to remove all subsequent scripts. I do not have the ability to remove <script> tags from the server side. What I've tried: (function (c,h) { var i, s = h.getElementsByTagName('script'); c.log("Num scripts: " + s.length); i = s.length - 1; while(i > 1) { h.removeChild(s[i]); i -= 1; } })(console, document.head); However, the logged number of scripts comes out to only 1, since (as @ryan pointed out) the code is being executed prior to the DOM being ready. Although wrapping the code above in a document.ready event callback does enable proper calculation of the number of <script> tags in the <head>, waiting until the DOM is ready fails to prevent the scripts from loading. Is there a reliable means of manipulating the HTML prior to the DOM being ready? Background If you want more context, this is part of an attempt to consolidate scripts where no option for server-side aggregation is available. Many of the JS libraries being loaded are from a CMS with limited configuration options. The content is mostly static, so there is very little concern about manually aggregating the JavaScript and serving it from a different location. Any suggestions for alternative applicable aggregation techniques would also be welcome.

    Read the article

  • rails 3 actionmailer cannot send email

    - by lkahtz
    I am following Ryan Bates's tutorial on Rails 3 ActionMailer. I generate the mailer in terminal and then establish a setup_mail.rb under config/initializers. I keyed in the following code: ActionMailer::Base.smtp_settings={ :address => "smtp.gmail.com", :port => 587, :domail => "gmail.com", :user_name => "my_account_at_gmail", :password => "my_password", :authentication => "plain" , :enable_starttls_auto => true } My user_mailer.rb file goes like: class UserMailer < ActionMailer::Base default :from => "[email protected]" def registration_confirmation(user) mail(:to => user.email,:subject => "registered") end end I tested in rails console: u=User.first UserMailer.registration_confirmation(u).deliver it displays: #<Mail::Message:2194479560, Multipart: false, Headers: <Date: Sat, 26 Feb 2011 14:42:06 +0800>, <From: [email protected]>, <To: [email protected]>, <Message-ID: <[email protected]>>, <Subject: registered>, <Mime-Version: 1.0>, <Content-Type: text/plain>, <Content-Transfer-Encoding: 7bit>> BUT I never received the email here... Why? How can I solve this? I guess it is some problem on send_mail.rb file..

    Read the article

  • Improved technique to store a filename in a variable?

    - by SDGuero
    Greetings, I need to store the filename of a log into a variable so my script can perform some checks on the daily log files. These logs always have a different name because they have a timestamp in the name. Currently I'm using a hodge podged method that pipes an ls command to sed, sort, cut, and tail in order to get the name out. CRON_LOG=$(ls -1 $LOGS_DIR/fetch_cron_{true,false}_$CRON_DATE*.log 2> /dev/null | sed 's/^[^0-9][^0-9]*\([0-9][0-9]*\).*/\1 &/' | sort -n | cut -d ' ' -f2- | tail -1 ) UPDATE: $CRON_DATE is supplied as an argument to the script. It is the date (to the day) that the log was created on. Sometimes multiple logs will exist for the same day so I want this to get the most recent one. A typical filename is fetch_cron_false_031810090452.log I'm pretty sure I kluged this together from some stuff I found google a few months ago. it works now but I'm not really happy with the technique. I have some ideas about how to do this better but I have had great success on this site before and thought it might be best to refer to the stackoverflow gods first. All answers are greatly appreciated. Thanks, Ryan

    Read the article

  • java.awt -- when java outputs an image to my monitor (screen), where is the file that is output to the monitor card?

    - by user1405870
    Suppose that I am drawing a set of images using java graphics objects. Suppose that I java is outputting these images to my monitor. Where is the file or files that are sent to the monitor card (the graphical representation files). How can I take this file and save it to disk, or how can I take this file and write it to an array, or how can I take these files and combine the results of their output (to the monitor) into a single file for saving? I don't want to use a screen shot feature, I want to be able to redirect (xor capture also) the output to the monitor to some sort of byte-stream. I note that monitors are much better than semaphores, when you are talking about display capabilities; I don't need a counter example. I might not be asking the correct question. It might be that I want to capture the file while it is still in User Space, before it is put into 'Device Space'. I would like to try and capture the byte stream so that I can convert it to MPEG-4 format. I either need a streaming output from the MPEG-4 converter, coming from the streaming input, or else, I need to take static images at discrete times and convert the images. What format will the output from User Space be in? What format will the Device Space output be in? Try to keep speculation to a minimum. http://docs.oracle.com/javame/config/cdc/opt-pkgs/api/jsr927/index.html I guess that Java has made a means of displaying AWT objects on a television screen. Thank you. Ryan Zoerner

    Read the article

  • Complex Forms Generating Error

    - by user1648020
    I am working on an application that allows students to create a catalog of courses they are taking for a semester. I have created models for user; course; subject and category. Users can have many courses. Each course can have many subjects and categories. The tables for courses, subjects and categories include the following: Catalog: user_id; subject_id, category_id and course_id Courses: user_id; coursedetail_id Coursedetail: name; description Subject: name; description Category: name; description The idea is that an Admin can create a list of courses; subjects and categories and that the user can select the courses they want to add to their catalog. I have seperated courses and coursedetails because I envision that the coursedetails will grow overtime and the courses table will allow me to join the user_id and cousres details to rreport on if necessary. I attempted to follow Ryan's railscast on Complex Forms thinking that that I should use a complex form and has many relationship to get things working -- but I get an error in the catalog controller - cannot locate catalog_id which I know is in the table. I am now not sure if complex forms is the way to go or I should be looking at another direction to get the appropriate form in place. Any assistance would be appreciated.

    Read the article

  • Communication with HyperTerminal [ QT and WINApi ]

    - by javaAmator
    Hi! I write program to communicate with modem (it useing Hayes commands) and this is working. GUI is programmed with QT, but communication with COM port is write with winapi library. I have problem when I want to send with my program message from one computer to another, i can't send Polish chars (they are repleaced by '?'), how can I fix it ? Does anyone have idea ?? And I have one more problem, I can't send message from my program to Microsoft HyperTerminal, HyperTerminal receive something, but not that what I send. Thx for any help :) Important pieces of code: Connect with port: portHandle = CreateFile (portName, GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); GetCommState (portHandle, &dcb); switch(ui->comboBox->currentIndex()) { case 0 : dcb.BaudRate=CBR_110; break; case 1 : dcb.BaudRate=CBR_300; break; case 2 : dcb.BaudRate=CBR_600; break; case 3 : dcb.BaudRate=CBR_1200; break; case 4 : dcb.BaudRate=CBR_2400; break; case 5 : dcb.BaudRate=CBR_4800; break; case 6 : dcb.BaudRate=CBR_9600; break; case 7 : dcb.BaudRate=CBR_14400; break; case 8 : dcb.BaudRate=CBR_19200; break; case 9 : dcb.BaudRate=CBR_38400; break; case 10 : dcb.BaudRate=CBR_56000; break; case 11 : dcb.BaudRate=CBR_57600; break; case 12 : dcb.BaudRate=CBR_115200; break; case 13 : dcb.BaudRate=CBR_128000; break; case 14 : dcb.BaudRate=CBR_256000; break; } dcb.fBinary = TRUE; dcb.fParity = TRUE; dcb.fOutxCtsFlow = FALSE; dcb.fOutxDsrFlow = FALSE; dcb.fDtrControl = DTR_CONTROL_ENABLE; dcb.fDsrSensitivity = FALSE; dcb.fTXContinueOnXoff = TRUE; dcb.fOutX = FALSE; dcb.fInX = FALSE; dcb.fErrorChar = FALSE; dcb.fNull = FALSE; dcb.fRtsControl = RTS_CONTROL_ENABLE; dcb.fAbortOnError = FALSE; //dcb.ByteSize = dataBits; dcb.DCBlength = sizeof (DCB); switch(ui->comboBox_3->currentIndex()) { case 1 : dcb.Parity = EVENPARITY; break; case 3 : dcb.Parity = MARKPARITY; break; case 2 : dcb.Parity = ODDPARITY; break; case 4 : dcb.Parity = SPACEPARITY; break; case 0 : dcb.Parity = NOPARITY; break; } switch (ui->comboBox_4->currentIndex()) { case 0 : dcb.StopBits = ONESTOPBIT; break; case 1 : dcb.StopBits = ONE5STOPBITS;break; case 2 : dcb.StopBits = TWOSTOPBITS; break; } switch (ui->comboBox_2->currentIndex()) { case 0 : dcb.ByteSize = 5; break; case 1 : dcb.ByteSize = 6;break; case 2 : dcb.ByteSize= 7; break; case 3 : dcb.ByteSize = 8; break; } SetCommState (portHandle, &dcb); GetCommTimeouts (portHandle, &CommTimeouts); CommTimeouts.ReadIntervalTimeout = MAXDWORD; CommTimeouts.ReadTotalTimeoutMultiplier = 0; CommTimeouts.ReadTotalTimeoutConstant = 0; CommTimeouts.WriteTotalTimeoutMultiplier = 10; CommTimeouts.WriteTotalTimeoutConstant = 1000; SetCommTimeouts (portHandle, &CommTimeouts); Send MSG: void MainWindow::Send(char c) { do {WriteFile(portHandle, &c, 1, &cbWritten, NULL); } while (!(cbWritten)); } void MainWindow::on_pushButton_clicked() { QString str = ui->lineEdit->text(); std::string str2; ui->lineEdit->clear(); str2 = str.toStdString(); for(int i=0; i < str2.size();i++) { Send(str2[i]); //qDebug()<< str2[i]; } Send(char(13)); } Receive MSG: void ReaderThread::run() { char c; while(1) { c = Receive(); if(c==13) { emit insertPlainText("\n"); } else { emit insertPlainText(QString(c)); } } } char ReaderThread::Receive() { char c; do{ ReadFile(portHandle, &c, 1, &cbRead, NULL); } while (!(cbRead)); return c; }

    Read the article

< Previous Page | 35 36 37 38 39 40  | Next Page >