Search Results

Search found 4141 results on 166 pages for 'render'.

Page 32/166 | < Previous Page | 28 29 30 31 32 33 34 35 36 37 38 39  | Next Page >

  • jQuery RJS inserting string vs dom.

    - by Dmitriy Likhten
    So I am trying to use jQuery to insert data from an ajax call. I actually use the jquery.form plugin, and have the ajax form submitted with a dataType: 'script'. The response is a jquery expression which contains a <%= javascript_escape(render ...) %> erb tag (similar to what the railscasts episode 136 instructs to do). However the end result is that the full text of the render is inserted as if that was the content to be inserted into the page, as text, not as dom elements. Could the fact that the render had some newlines at the beginning be the cause? Dom text: "\n \n &lt;li>....&lt;/li>" I also tried having jQuery just read the response as a script and execute it, and used the prototype-based rjs stuff, same effect, the text is inserted into the dom. Are there any reasons why such a behavior would be experienced? A bit of clarification: My response.js.erb is jQuery("#content").append("<%= escape_javascript(render(:partial => "widgets")) %>"); jQuery("#information").text("Finally, something happened!"); The full text inside the append() call is inserted as text into #content.

    Read the article

  • ContentControl + RenderTargetBitmap + empty image

    - by Kellls
    Im trying to create some chart images without ever displaying those charts on the screen. I'v been at this for quite a while and tried a lot of different things but nothing seems to work. The code works perfectly if I display the chart in a window first, but if I don't display it in a window, the bitmap is just white with a black border (no idea why). I have tried adding the chart to a border before rendering and giving the border a green borderBrush. In the bitmap, I see the green borderBrush then the black border and white background but no chart. I don't know where the black border is coming from as the chart is not contained in a black border. I have tried adding the chart to a window without calling window.Show() and again just the black boarder and white background. However if I call window.Show() the bitmap contains the chart. I have tried using a drawingVisual as explained here, same result. Here is the code (not including adding the element to a border or window): private static BitmapSource CreateElementScreenshot(FrameworkElement element, int dpi) { if (!element.IsMeasureValid) { Size size = new Size(element.Width, element.Height); element.Measure(size); element.Arrange(new Rect(size)); } element.UpdateLayout(); var scale = dpi/96.0; var renderTargetBitmap = new RenderTargetBitmap ( (int)(scale * element.RenderSize.Width),(int)(scale * element.RenderSize.Height),dpi,dpi,PixelFormats.Default ); // this is waiting for dispatcher to perform measure, arrange and render passes element.Dispatcher.Invoke(((Action)(() => renderTargetBitmap.Render(element))), DispatcherPriority.Render); return renderTargetBitmap; } Note: The chart is a ContentControl. Is there anyway I can get the chart to render without displaying it in a window first?

    Read the article

  • iPhone Rendering Question

    - by slythic
    Hi all, I'm new to iPhone/Objective-C development. I "jumped the gun" and started reading and implementing some chapters from O'Reilly's iPhone Development. I was following the ebook's code exactly and my code was generating the following error: CGContextSetFillColorWithColor: invalid context CGContextFillRects: invalid context CGContextSetFillColorWithColor: invalid context CGContextGetShouldSmoothFonts: invalid context However, when I downloaded the sample code for the same chapter the code is different. Book Code: - (void) Render { CGContextRef g = UIGraphicsGetCurrentContext(); //fill background with gray CGContextSetFillColorWithColor(g, [UIColor grayColor].CGColor); CGContextFillRect(g, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)); //draw text in black. CGContextSetFillColorWithColor(g, [UIColor blackColor].CGColor); [@"O'Reilly Rules!" drawAtPoint:CGPointMake(10.0, 20.0) withFont:[UIFont systemFontOfSize:[UIFont systemFontSize]]]; } Actual Project Code from the website (works): - (void) Render { [self setNeedsDisplay]; //this sets up a deferred call to drawRect. } - (void)drawRect:(CGRect)rect { CGContextRef g = UIGraphicsGetCurrentContext(); //fill background with gray CGContextSetFillColorWithColor(g, [UIColor grayColor].CGColor); CGContextFillRect(g, CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)); //draw text in black. CGContextSetFillColorWithColor(g, [UIColor blackColor].CGColor); [@"O'Reilly Rules!" drawAtPoint:CGPointMake(10.0, 20.0) withFont:[UIFont systemFontOfSize:[UIFont systemFontSize]]]; } What is it about these lines of code that make the app render correctly? - (void) Render { [self setNeedsDisplay]; //this sets up a deferred call to drawRect. } - (void)drawRect:(CGRect)rect { Thanks in advance for helping out a newbie!

    Read the article

  • Rails and Prawn PDF - add current item ID to filename?

    - by dannymcc
    Hi Everyone, I have two PDFs that are made "on the fly" using Prawn PDF. The PDFs are called jobsheet.pdf and discharge.pdf - their URL's are: railsroot/kases/IDNO/jobsheet.pdf railsroot/kases/IDNO/discharge.pdf I am trying to work out how to automagically append the filename with the ID number: railsroot/kases/IDNO/jobsheet_IDNO.pdf railsroot/kases/IDNO/discharge_IDNO.pdf To create the PDFs the code is as follows: Kases Controller def jobsheet @kase = Kase.find(params[:id]) respond_to do |format| format.html {} # jobsheet.html.erb format.xml { render :xml => @kase } format.pdf { render :layout => false } prawnto :prawn => { :background => "#{RAILS_ROOT}/public/images/jobsheet.png", :left_margin => 0, :right_margin => 0, :top_margin => 0, :bottom_margin => 0, :page_size => 'A4' } end end # GET /kases/1 # GET /kases/1.xml def discharge @kase = Kase.find(params[:id]) respond_to do |format| format.html { } # discharge.html.erb format.xml { render :xml => @kase } format.pdf { render :layout => false } prawnto :prawn => { :background => "#{RAILS_ROOT}/public/images/discharge.png", :left_margin => 0, :right_margin => 0, :top_margin => 0, :bottom_margin => 0, :page_size => 'A4' } end end Routes map.resources :kases, :member => { :discharge => :get } map.resources :kases, :member => { :jobsheet => :get } To view the PDF's I use the following links: jobsheet_kase_path(@kase, :format => 'pdf') discharge_kase_path(@kase, :format => 'pdf') Is this even possible? Thanks, Danny

    Read the article

  • Help me understand dynamic layouts in Sinatra

    - by thermans
    Help me understand this; I'm learning Sinatra (and Rails for that matter, er, and Ruby). Say I'm doing a search app. The search form is laid out in one div, and the results will be laid out in another. The search form is rendered into the div by a previous view (maybe from a login form). I want to process the form params, perform the search, and render the results into the results div. If I have a single "yield" in the layout and render the divs from different views, the results div erases the search div when it renders. If I define the divs in the default layout, then just render the content, obviously the layout will be messed up: there would have to be two "yields" and I don't think Sinatra supports passing blocks in to yields. I tried foca's sinatra-content-for plugin, and that seems closer to what I need. But I can't figure out where to place the "yield_content" statements. If I have this haml in my layout: #search -# search form = yield_content :search #results -# search results = yield_content :results ... this in my search view: - content_for :search do %form{:method => "post"... etc. ... and this in the results view: - content_for :results do %table{:class => 'results'... etc. This sort of works but when I render the results view, the search div is emptied out. I would like to have it remain. Am I doing something wrong? How should I set this up?

    Read the article

  • How should backbone.js handle a GET request that returns no results?

    - by Nyxynyx
    I have a number of text input elements that when its values are changed, will trigger a fetch on listingListView's collection listingCollection, which then updates listingListView with the new data via the function listingListView.refreshList as shown below. I am using PHP/Codeigniter to expose a RESTful API. Problem: Everything works fine if there are results retrieved from the fetch(). However, when the filters results in no result being returned, how should the server side and the client side handle it? Currently Chrome's javascript console displays a 404 error and in the Network tab, the XHR request is highlighted in red. All I want to do in the event of zero results returned, is to blank the listingListView and show a message like (No results returned) and not throw any errors in the javascript console. Thanks! PHP Code function listings_get() { // Get filters $price_min = $this->get('price_min'); $this->load->model('app_model'); $results = $this->app_model->get_listings($price_min); if($results) $this->response($results); else $this->response(NULL); } JS Code window.ListingListView = Backbone.View.extend({ tagName: 'table', initialize: function() { this.model.bind('reset', this.refreshList, this); this.model.bind('add', function(listing) { $(this.el).append(new ListingListItemView({ model: listing }).render().el); }, this); }, render: function() { _.each(this.model.models, function(listing) { $(this.el).append(new ListingListItemView({ model: listing }).render().el); }, this); return this; }, close: function() { $(this.el).unbind(); $(this.el).empty(); }, refreshList: function() { $(this.el).empty(); this.render(); } });

    Read the article

  • duplicate rows in join table with has_many => through and accepts_nested_attributes_for

    - by shalako
    An event has many artists, and an artist has many events. The join of an artist and an event is called a performance. I want to add artists to an event. This works except that I'm getting duplicate entries into my join table when creating a new event. This causes problems elsewhere. event.rb has_many :performances, :dependent => :destroy has_many :artists, :through => :performances accepts_nested_attributes_for :artists, :reject_if => proc {|a| a['name'].blank?} accepts_nested_attributes_for :performances, :reject_if => proc { |a| a['artist_id'].blank? }, :allow_destroy => true artist.rb has_many :performances, :dependent => :destroy has_many :artists, :through => :performances performance.rb belongs_to :artist belongs_to :event events_controller.rb def new @event = Event.new @event.artists.build respond_to do |format| format.html # new.html.erb format.xml { render :xml => @event } end end def create @event = Event.new(params[:event]) respond_to do |format| if @event.save flash[:notice] = 'Event was successfully created.' format.html { redirect_to(admin_events_url) } format.xml { render :xml => @event, :status => :created, :location => @event } else format.html { render :action => "new" } format.xml { render :xml => @event.errors, :status => :unprocessable_entity } end end end output Performance Create (0.2ms) INSERT INTO `performances` (`event_id`, `artist_id`) VALUES(7, 19) Performance Create (0.1ms) INSERT INTO `performances` (`event_id`, `artist_id`) VALUES(7, 19)

    Read the article

  • Orbited exception Data must not be unicode.

    - by Sid
    I am working with orbited and once I switch on orbited in production mode it throws the following error on my screen -- <exception caught here> --- File "/usr/lib/python2.6/dist-packages/twisted/web/server.py", line 150, in process self.render(resrc) File "/usr/lib/python2.6/dist-packages/twisted/web/server.py", line 157, in render body = resrc.render(self) File "/usr/local/lib/python2.6/dist-packages/orbited-0.7.10-py2.6.egg/orbited/transports/base.py", line 21, in render self.conn.transportOpened(self) File "/usr/local/lib/python2.6/dist-packages/orbited-0.7.10-py2.6.egg/orbited/cometsession.py", line 322, in transportOpened self.cometTransport.flush() File "/usr/local/lib/python2.6/dist-packages/orbited-0.7.10-py2.6.egg/orbited/transports/base.py", line 45, in flush self.write(self.packets) File "/usr/local/lib/python2.6/dist-packages/orbited-0.7.10-py2.6.egg/orbited/transports/htmlfile.py", line 42, in write self.request.write(payload); File "/usr/lib/python2.6/dist-packages/twisted/web/http.py", line 862, in write self.transport.write(data) File "/usr/lib/python2.6/dist-packages/twisted/internet/tcp.py", line 420, in write abstract.FileDescriptor.write(self, bytes) File "/usr/lib/python2.6/dist-packages/twisted/internet/abstract.py", line 170, in write raise TypeError("Data must not be unicode") exceptions.TypeError: Data must not be unicode I have absolutely no clue as to what could be the problem. Could anyone point me in the right direction.

    Read the article

  • Need to reload current_cart to get the test passed

    - by leomayleomay
    I'm testing my online store app with RSpec, here's what I'm doing: # spec/controllers/line_items_controller_spec.rb require 'spec_helper' describe LineItemsController do describe "POST 'create'" do before do @current_cart = Factory(:cart) controller.stub!(:current_cart).and_return(@current_cart) end it 'should merge two same line_items into one' do @product = Factory(:product, :name => "Tee") post 'create', {:product_id => @product.id} post 'create', {:product_id => @product.id} assert LineItem.count.should == 1 assert LineItem.first.quantity.should == 2 end end end # app/controllers/line_items_controller.rb class LineItemsController < ApplicationController def create current_cart.line_items.each do |line_item| if line_item.product_id == params[:product_id] line_item.quantity += 1 if line_item.save render :text => "success" else render :text => "failed" end return end end @line_item = current_cart.line_items.new(:product_id => params[:product_id]) if @line_item.save render :text => "success" else render :text => "failed" end end end The problem right now is it never added up two line_items having the same product into one, because the second time I entered into the line_items_controller#create, the current_cart.line_items is [], I have run current_cart.reload to get the test passed, any idea what's going wrong?

    Read the article

  • JSF2.0: variable list of custom component

    - by rattaman
    Hello Is there any way of using JSF2.0 in connection with variable lists of components? For example, lets say I have list o people that I would like to edit. They are presented on the page as list of components PersonEditor, which allow changing person data. Each editor is associated with single Person element. In order for this to work I need to perform following steps: On initial request: Get list of people For each person create PersonEditor and associate it with Person object. Fill editor's data. On user action: When user changes values and presses Save, data is processed by backing bean. I can either fill editor with data from list of people or bind it to the backing bean, but not at the same time, so I am stuck. I tried people.xhtml <ui:render value="#{bean.people}" var="person"> <example:personEditor person="#{person}"/> </ui:render> where personEditor.xhtml: a) proper association with person object, but no connection to backing bean <h:form> <h:outputText value="#{cc.attr.person.name}"/> <h:commandButton name="Save" actionListener="editorBean.save"> <f:ajax execute="@form" render="@form"/> </h:commandButton> </h:form> b) no association with person object, but there is connection to backing bean - there is no way to pass that person to the backing bean <h:form> <h:outputText value="#{editorBean.name}"/> <h:commandButton name="Save" actionListener="editorBean.save"> <f:ajax execute="@form" render="@form"/> </h:commandButton> </h:form> If I had each editor on separate page, I could pass the person id as url parameter (either using f:param or f:attribute) and initialize it accordingly. Is there any solution to this problem?

    Read the article

  • Ruby on Rails controller and architecture with cells

    - by dt
    I decided to try to use the cells plugin from rails: http://cells.rubyforge.org/community.html given that I'm new to Ruby and very used to thinking in terms of components. Since I'm developing the app piecemeal and then putting it together piece by piece, it makes sense to think in terms of components. So, I've been able to get cells working properly inside a single view, which calls a partial. Now, what I would like to be able to do (however, maybe my instincts need to be redirected to be more "Rails-y"), is call a single cell controller and use the parameters to render one output vs. another. Basically, if there were a controller like: def index params[:responsetype] end def processListResponse end def processSearchResponse end And I have two different controller methods that I want to respond to based on the params response type, where I have a single template on the front end and want the inner "component" to render differently depending on what type of request is made. That allows me to reuse the same front-end code. I suppose I could do this with an ajax call instead and just have it rerender the component on the front end, but it would be nice to have the option to do it either way and to understand how to architect Rails a bit better in the process. It seems like there should be a "render" option from within the cells framework to render to a certain controller or view, but it's not working like I expect and I don't know if I'm even in the ballpark. Thanks!

    Read the article

  • Java - Calling all methods of a class

    - by Thomas Eschemann
    I'm currently working on an application that has to render several Freemarker templates. So far I have a Generator class that handles the rendering. The class looks more or less like this: public class Generator { public static void generate(…) { renderTemplate1(); renderTemplate2(); renderTemplate3(); } private static void render(…) { // renders the template } private static void renderTemplate1() { // Create config object for the rendering // and calls render(); }; private static void renderTemplate1() { // Create config object for the rendering // and calls render(); }; … } This works, but it doesn't really feel right. What I would like to do is create a class that holds all the renderTemplate...() methods and then call them dynamically from my Generator class. This would make it cleaner and easier to extend. I was thinking about using something like reflection, but it doesn't really feel like a good solution either. Any idea on how to implement this properly ?

    Read the article

  • ASP.NET: Page HTML head rendering

    - by Fabian
    I've been trying to figure out the best way to custom render the <head> element of a pag to get rid of the extra line breaks which is caused by <head runat="server">, so its properly formatted. So far the only thing i've found which works is the following: protected override void Render(HtmlTextWriter writer) { StringWriter stringWriter = new StringWriter(); HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter); base.Render(htmlTextWriter); htmlTextWriter.Close(); string html = stringWriter.ToString(); string newHTML = html.Replace("\r\n\r\n<!DOCTYPE", "<!DOCTYPE") .Replace("\r\n<html", "<html") .Replace("<title>\r\n\t", "<title>") .Replace("\r\n</title>", "</title>") .Replace("</head>", "\n</head>"); writer.Write(newHTML); } I define my had tag like Now i have 2 questions: How does the above code affect the performance (so is this viable in an production environment)? Is there a better way to do this, for example a method which i can override to just custom render the <head>? Oh yeah ASP.NET MVC is not an option.

    Read the article

  • Ruby on Rails unknown attribute form error

    - by Ulkmun
    I'm attempting to create a form which will allow me to upload a file.. I've got the following form.. <div class="field"> <%= f.label :title %><br /> <%= f.text_field :title %> </div> <div class="field"> <%= f.label :body %><br /> <%= f.text_area :body, "cols" => 100, "rows" => 40 %> </div> <div class="field"> <%= f.label :upload %><br /> <%= f.file_field :upload %> </div> <div class="actions"> <%= f.submit %> </div> I've got a controller which seems to error in this function.. # POST /posts # POST /posts.xml def create @post = Post.new(params[:post]) @post = DataFile.save(params[:upload]) ##render :text => "File has been uploaded successfully" respond_to do |format| if @post.save format.html { redirect_to(@post, :notice => 'Post was successfully created.') } format.xml { render :xml => @post, :status => :created, :location => @post } else format.html { render :action => "new" } format.xml { render :xml => @post.errors, :status => :unprocessable_entity } end end end That's the method that get's called when I create the post. The error is unknown attribute: upload app/controllers/posts_controller.rb:42:in ``new' app/controllers/posts_controller.rb:42:in ``create'

    Read the article

  • CakePHP update multiple elements in one div

    - by sw3n
    The idea is that I've 3 ajax links and each link is coupled to one single element (a form). The element will be loaded in one div. Each time when you click on a different link, the element that is requested before must be removed and the new one must come in there. So it has to update the DIV. The problem is, that it request the element, but it does not remove the other one. So when you click one the first link, it shows the first element, click on the second link and it puts the second element beneath them, and with the third one will happen exactly the same. If you clicked all the 3 links, it shows 3 forms right under each other. Some Code: Controller: function view($id) { // content could come from a database, xml, etc. $content = array ( array($this->render(null, 'ajax', '/elements/ga')), array($this->render(null, 'ajax', '/elements/ex')), array($this->render(null, 'ajax', '/elements/both')) ); $this->set('google', $content[$id][0]); // use ajax layout $this->render('/pages/form', 'ajax'); } View code: echo $ajax-link( 'Google', array( 'controller' = 'analytics', 'action' = 'view', 0 ), array( 'update' = 'dynamic1')); echo ' | '; echo $ajax-link( 'Exact', array( 'controller' = 'analytics', 'action' = 'view', 1 ), array( 'update' = 'dynamic1', 'loading' = 'Effect.BlindDownUp(\'dynamic1\')')); echo ' | '; echo $ajax-link( 'Beide', array( 'controller' = 'analytics', 'action' = 'view', 2 ), array( 'update' = 'dynamic1', 'loading' = 'Effect.BlindDown(\'dynamic1\')' )); echo $ajax-div('dynamic1'); echo $google; echo $ajax-divEnd('dynamic1');

    Read the article

  • Error Reading Image

    - by javawarrior
    When I tried to open a simple smile.png image using package com.java3d.java3d.graphics; import java.awt.Color; import java.awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; public class Texture { public static Render floor = loadBitMap("smile.png"); public Texture(){} public static Render loadBitMap(String fileName) { try { BufferedImage image = ImageIO.read(Thread.currentThread().getContextClassLoader().getResource(fileName)); System.out.print(image==null); int width = image.getWidth(); System.out.println(width); int height = image.getHeight(); System.out.println(height); System.out.println(image.getRGB(4, 4)); Render result = new Render(width, height); image.getRGB(0, 0, width, height, result.pixels, 0, width); return result; } catch (Exception e) { System.out.println("CRASH!"); throw new RuntimeException(e); } } } it returns every pixel as -1; what could be causing this problem? Here is the image:

    Read the article

  • ruby on rails basics help

    - by CHID
    Hi, i created a scaffolded application in rails by the name of product. The product_controller.rb file contains the following. class ProductsController ApplicationController def new @product = Product.new respond_to do |format| format.html # new.html.erb format.xml { render :xml = @product } end end def create @product = Product.new(params[:product]) respond_to do |format| if @product.save flash[:notice] = 'Product was successfully created.' format.html { redirect_to(@product) } format.xml { render :xml = @product, :status = :created, :location = @product } else format.html { render :action = "new" } format.xml { render :xml = @product.errors, :status = :unprocessable_entity } end end end Now when the url http://localhost:3000/products/create is given Where new product link is clicked, control is transferred to new definition in the controller class and then an instance variable @product is created. BUT WHERE IS THIS VARIABLE PASSED? The funtion inturn calls new.rhtml which contains <% form_for(@product) do |f| % #all form elments declaration <% f.submit "Create" % <%= end % Here @product is initialized in the controller file and passed to this new.rhtml. So where does form_for(@product) gets the data? How does the control gets tranfered to create function in controller file when submit button is clicked? No where action is specified to the controller file. in the create function, wat does redirec_to(@product) specify where @product is an object received from the new.html file... I am very much confused on the basics of ROR. Somone pls help me clarify this. pardon me for making such a big post. I have lots of doubts in this single piece of code

    Read the article

  • query not displaying proper result

    - by ravindra
    In my Rails 3 project I have the following code for My controller: class TasksController < ApplicationController def today @tasks = Task.today @task = Task.new respond_to do |format| format.html { render :text=> "Sorry , you don't have any task pending today." } format.html # new.html.erb format.xml { render :xml => @tasks } end end def this_week @tasks = Task.this_week @task = Task.new respond_to do |format| format.html { render :text => "Sorry , No content for selected period." } format.html # new.html.erb format.xml { render :xml => @tasks } end end end My model: class Task < ActiveRecord::Base def self.today Task.where(:due_date => "Date.today" , :task_status => "open").order("due_date ASC") end def self.this_week Task.where(:due_date =>"Time.now.this_week" , :task_status => "open" ).order("due_date ASC") end end Why it does not displaying anything in the relative view. Please help me. Thanks

    Read the article

  • How to allow devise users to edit their profil?

    - by user1704926
    I have a namespace called "backend" which is protected by Devise. I would like now to allow users to edit their profil. So I created a users_controller in Backend. Here's the users_controllercode : class Backend::UsersController < ApplicationController layout 'admin' before_filter :authenticate_user! def index @users = Backend::User.all respond_to do |format| format.html # index.html.erb format.json { render json: @users } end end def show @user = Backend::User.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @user } end end def edit @user = Backend::User.find(params[:id]) end def update @user = Backend::User.find(params[:id]) respond_to do |format| if @user.update_attributes(params[:user]) format.html { redirect_to @user, notice: 'Article was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @user.errors, status: :unprocessable_entity } end end end end When I go on backend_users_path there is a list of all the users. I would like to permit to edit only his own profil. So I go on the Edit page : <%= link_to "Edit", edit_backend_user_path(backend_user.id) %> . Here's the Edit page code : <%= simple_form_for @user do |f| %> <div><%= f.label :email %><br /> <%= f.input :email, :autofocus => true %></div> <div><%= f.submit "Update" %></div> <% end %> And there is my problem : when I try to modify the email address, nothing happen. The update fails. How can I do this ? I'm quite lost. Thanks by advance.

    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

  • Dereferencing possible null pointer in java

    - by Nealio
    I am just starting to get into graphics and when I am trying to get the graphics, I get the error"Exception in thread "Thread-2" java.lang.NullPointerException" and I have no clue on what is going on! Any help is greatly appreciated. //The display class for the game //Crated: 10-30-2013 //Last Modified: 10-30-2013 package gamedev; import gamedev.Graphics.Render; import gamedev.Graphics.Screen; import java.awt.Canvas; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Toolkit; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import javax.swing.JFrame; private void tick() { } private void render() { System.out.println("display.render"); BufferStrategy bs = this.getBufferStrategy(); if (bs == null) { createBufferStrategy(3); } for (int i = 0; i < GAMEWIDTH * GAMEHEIGHT; i++) { pixels[i] = screen.PIXELS[i]; } screen.Render(); //The line of code that is the problem Graphics g = bs.getDrawGraphics(); //end problematic code g.drawImage(img, 0, 0, GAMEWIDTH, GAMEHEIGHT, null); g.dispose(); bs.show(); }

    Read the article

  • LWJGL Voxel game, glDrawArrays

    - by user22015
    I've been learning about 3D for a couple days now. I managed to create a chunk (8x8x8). Add optimization so it only renders the active and visible blocks. Then I added so it only draws the faces which don't have a neighbor. Next what I found from online research was that it is better to use glDrawArrays to increase performance. So I restarted my little project. Render an entire chunck, add optimization so it only renders active and visible blocks. But now I want to add so it only draws the visible faces while using glDrawArrays. This is giving me some trouble with calling glDrawArrays because I'm passing a wrong count parameter. > # A fatal error has been detected by the Java Runtime Environment: > # > # EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000006e31a03, pid=1032, tid=3184 > # Stack: [0x00000000023a0000,0x00000000024a0000], sp=0x000000000249ef70, free space=1019k Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code) C [ig4icd64.dll+0xa1a03] Java frames: (J=compiled Java code, j=interpreted, Vv=VM code) j org.lwjgl.opengl.GL11.nglDrawArrays(IIIJ)V+0 j org.lwjgl.opengl.GL11.glDrawArrays(III)V+20 j com.vox.block.Chunk.render()V+410 j com.vox.ChunkManager.render()V+30 j com.vox.Game.render()V+11 j com.vox.GameHandler.render()V+12 j com.vox.GameHandler.gameLoop()V+15 j com.vox.Main.main([Ljava/lang/StringV+13 v ~StubRoutines::call_stub public class Chunk { public final static int[] DIM = { 8, 8, 8}; public final static int CHUNK_SIZE = (DIM[0] * DIM[1] * DIM[2]); Block[][][] blocks; private int index; private int vBOVertexHandle; private int vBOColorHandle; public Chunk(int index) { this.index = index; vBOColorHandle = GL15.glGenBuffers(); vBOVertexHandle = GL15.glGenBuffers(); blocks = new Block[DIM[0]][DIM[1]][DIM[2]]; for(int x = 0; x < DIM[0]; x++){ for(int y = 0; y < DIM[1]; y++){ for(int z = 0; z < DIM[2]; z++){ blocks[x][y][z] = new Block(); } } } } public void render(){ Block curr; FloatBuffer vertexPositionData2 = BufferUtils.createFloatBuffer(CHUNK_SIZE * 6 * 12); FloatBuffer vertexColorData2 = BufferUtils.createFloatBuffer(CHUNK_SIZE * 6 * 12); int counter = 0; for(int x = 0; x < DIM[0]; x++){ for(int y = 0; y < DIM[1]; y++){ for(int z = 0; z < DIM[2]; z++){ curr = blocks[x][y][z]; boolean[] neightbours = validateNeightbours(x, y, z); if(curr.isActive() && !neightbours[6]) { float[] arr = curr.createCube((index*DIM[0]*Block.BLOCK_SIZE*2) + x*2, y*2, z*2, neightbours); counter += arr.length; vertexPositionData2.put(arr); vertexColorData2.put(createCubeVertexCol(curr.getCubeColor())); } } } } vertexPositionData2.flip(); vertexPositionData2.flip(); FloatBuffer vertexPositionData = BufferUtils.createFloatBuffer(vertexColorData2.position()); FloatBuffer vertexColorData = BufferUtils.createFloatBuffer(vertexColorData2.position()); for(int i = 0; i < vertexPositionData2.position(); i++) vertexPositionData.put(vertexPositionData2.get(i)); for(int i = 0; i < vertexColorData2.position(); i++) vertexColorData.put(vertexColorData2.get(i)); vertexColorData.flip(); vertexPositionData.flip(); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vBOVertexHandle); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertexPositionData, GL15.GL_STATIC_DRAW); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vBOColorHandle); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertexColorData, GL15.GL_STATIC_DRAW); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); GL11.glPushMatrix(); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vBOVertexHandle); GL11.glVertexPointer(3, GL11.GL_FLOAT, 0, 0L); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vBOColorHandle); GL11.glColorPointer(3, GL11.GL_FLOAT, 0, 0L); System.out.println("Counter " + counter); GL11.glDrawArrays(GL11.GL_LINE_LOOP, 0, counter); GL11.glPopMatrix(); //blocks[r.nextInt(DIM[0])][2][r.nextInt(DIM[2])].setActive(false); } //Random r = new Random(); private float[] createCubeVertexCol(float[] CubeColorArray) { float[] cubeColors = new float[CubeColorArray.length * 4 * 6]; for (int i = 0; i < cubeColors.length; i++) { cubeColors[i] = CubeColorArray[i % CubeColorArray.length]; } return cubeColors; } private boolean[] validateNeightbours(int x, int y, int z) { boolean[] bools = new boolean[7]; bools[6] = true; bools[6] = bools[6] && (bools[0] = y > 0 && y < DIM[1]-1 && blocks[x][y+1][z].isActive());//top bools[6] = bools[6] && (bools[1] = y > 0 && y < DIM[1]-1 && blocks[x][y-1][z].isActive());//bottom bools[6] = bools[6] && (bools[2] = z > 0 && z < DIM[2]-1 && blocks[x][y][z+1].isActive());//front bools[6] = bools[6] && (bools[3] = z > 0 && z < DIM[2]-1 && blocks[x][y][z-1].isActive());//back bools[6] = bools[6] && (bools[4] = x > 0 && x < DIM[0]-1 && blocks[x+1][y][z].isActive());//left bools[6] = bools[6] && (bools[5] = x > 0 && x < DIM[0]-1 && blocks[x-1][y][z].isActive());//right return bools; } } public class Block { public static final float BLOCK_SIZE = 1f; public enum BlockType { Default(0), Grass(1), Dirt(2), Water(3), Stone(4), Wood(5), Sand(6), LAVA(7); int BlockID; BlockType(int i) { BlockID=i; } } private boolean active; private BlockType type; public Block() { this(BlockType.Default); } public Block(BlockType type){ active = true; this.type = type; } public float[] getCubeColor() { switch (type.BlockID) { case 1: return new float[] { 1, 1, 0 }; case 2: return new float[] { 1, 0.5f, 0 }; case 3: return new float[] { 0, 0f, 1f }; default: return new float[] {0.5f, 0.5f, 1f}; } } public float[] createCube(float x, float y, float z, boolean[] neightbours){ int counter = 0; for(boolean b : neightbours) if(!b) counter++; float[] array = new float[counter*12]; int offset = 0; if(!neightbours[0]){//top array[offset++] = x*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE + BLOCK_SIZE; } if(!neightbours[1]){//bottom array[offset++] = x*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE - BLOCK_SIZE; } if(!neightbours[2]){//front array[offset++] = x*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE + BLOCK_SIZE; } if(!neightbours[3]){//back array[offset++] = x*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE - BLOCK_SIZE; } if(!neightbours[4]){//left array[offset++] = x*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE + BLOCK_SIZE; } if(!neightbours[5]){//right array[offset++] = x*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = x*BLOCK_SIZE + BLOCK_SIZE; array[offset++] = y*BLOCK_SIZE - BLOCK_SIZE; array[offset++] = z*BLOCK_SIZE - BLOCK_SIZE; } return Arrays.copyOf(array, offset); } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } public BlockType getType() { return type; } public void setType(BlockType type) { this.type = type; } } I highlighted the code I'm concerned about in this following screenshot: - http://imageshack.us/a/img820/7606/18626782.png - (Not allowed to upload images yet) I know the code is a mess but I'm just testing stuff so I wasn't really thinking about it.

    Read the article

  • Cinema4D XML scene not rendering texture

    - by George Profenza
    I exported a basic Cinema4D scene as XML (File Export Cinema 4D XML) then opened up the xml in Cinema4D and it looses the reference to the texture applied. If I open up the original c4d file and render it I can see my texture applied. If I open up the exported xml file and render it the texture is missing. Any way to get around that ?

    Read the article

  • windows misconfigured keyboard after installing usb keyboard

    - by goliatone
    have a dell vostro 1520, installed an external usb keyboard which works fine but the laptop's keyboard does not work properly. in the log in screen everything works as it should, once logged in the keyboard breaks. keys that have an alternate symbol accessible with the FN key render it by default. Meaning i have to press the FN key for it to render the proper ones- p has the * as FN, in order to get the p i have to press p+FN.

    Read the article

  • 10.6.4 Apple Wiki: New just created users can do nothing?

    - by beefon
    Hello, After update to 10.6.4 there's an issue: any new users that I create in Server Prefs/WGM can't post to their blogs, comment, create wiki pages... They can't do anything! There's log from Wiki errors (when user DURAK tries to create new blog entry): [HTTPChannel,5,127.0.0.1] Traceback (most recent call last): [HTTPChannel,5,127.0.0.1] File "/usr/share/caldavd/lib/python/twisted/web/server.py", line 126, in process self.render(resrc) [HTTPChannel,5,127.0.0.1] File "/usr/share/caldavd/lib/python/twisted/web/server.py", line 133, in render body = resrc.render(self) [HTTPChannel,5,127.0.0.1] File "/usr/share/wikid/lib/python/apple_xmlrpc_server/WebAppServer.py", line 90, in render d = defer.maybeDeferred(function, *args) [HTTPChannel,5,127.0.0.1] File "/usr/share/caldavd/lib/python/twisted/internet/defer.py", line 104, in maybeDeferred result = f(*args, **kw) [HTTPChannel,5,127.0.0.1] --- <exception caught here> --- [HTTPChannel,5,127.0.0.1] File "/usr/share/wikid/lib/python/apple_xmlrpc_server/ContentServiceBase.py", line 121, in xmlrpc_addEntry aPage = ContentEntry.newBundleBasedContentEntry (path = path, content = content, author = author, title = title, uid = uid, type = kind, versioned = self.versioned, templateName = template) [HTTPChannel,5,127.0.0.1] File "/usr/share/wikid/lib/python/apple_wlt/ContentEntry.py", line 794, in newBundleBasedContentEntry aPage.save('First created', 'created') [HTTPChannel,5,127.0.0.1] File "/usr/share/wikid/lib/python/apple_wlt/ContentEntry.py", line 445, in save revisions.addRevision(self.serializeEntry(revisionAttributes), inComment = comment, inAuthor = updateAuthor, inChangeType = editType) [HTTPChannel,5,127.0.0.1] File "/usr/share/wikid/lib/python/apple_utilities/sqlitersion.py", line 36, in _func result = f(self, *args, **kwargs) [HTTPChannel,5,127.0.0.1] File "/usr/share/wikid/lib/python/apple_utilities/sqlitersion.py", line 49, in addRevision contentPlistStr = plistlib.writePlistToString(inContentDict).decode("utf-8") [HTTPChannel,5,127.0.0.1] File "/S-m/Lib-ry/Fr-ks/Python.fr-k/Ver-s/2.6/lib/pyth-2.6/plistlib.py", line 110, in writePlistToString [HTTPChannel,5,127.0.0.1] File "/S-m/Lib-ry/Fr-ks/Python.fr-k/Ver-s/2.6/lib/pyth-2.6/plistlib.py", line 94, in writePlist [HTTPChannel,5,127.0.0.1] File "/S-m/Lib-ry/Fr-ks/Python.fr-k/Ver-s/2.6/lib/pyth-2.6/plistlib.py", line 251, in writeValue [HTTPChannel,5,127.0.0.1] File "/S-m/Lib-ry/Fr-ks/Python.fr-k/Ver-s/2.6/lib/pyth-2.6/plistlib.py", line 280, in writeDict [HTTPChannel,5,127.0.0.1] File "/S-m/Lib-ry/Fr-ks/Python.fr-k/Ver-s/2.6/lib/pyth-2.6/plistlib.py", line 238, in writeValue [HTTPChannel,5,127.0.0.1] File "/S-m/Lib-ry/Fr-ks/Python.fr-k/Ver-s/2.6/lib/pyth-2.6/plistlib.py", line 171, in simpleElement [HTTPChannel,5,127.0.0.1] File "/S-m/Lib-ry/Fr-ks/Python.fr-k/Ver-s/2.6/lib/pyth-2.6/plistlib.py", line 221, in _escapeAndEncode [HTTPChannel,5,127.0.0.1] exceptions.UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128) [HTTPChannel,5,127.0.0.1] 'Unparseable html in page, removing whatever was already written.' [HTTPChannel,5,127.0.0.1] Removing /Library/Collaboration/Users/durak/weblog/27133.page Any "old" user CAN create, modify, comment, etc. What can you recommend to fix this issue? Hope for your help...

    Read the article

< Previous Page | 28 29 30 31 32 33 34 35 36 37 38 39  | Next Page >