Search Results

Search found 4088 results on 164 pages for 'params keyword'.

Page 76/164 | < Previous Page | 72 73 74 75 76 77 78 79 80 81 82 83  | Next Page >

  • problems with retrieving data that was saved outside of a grails webflow

    - by callie16
    Hi, this is actually connected to an earlier question of mine here. Anyway, I have 3 domains that look like this: class A { ... static hasMany = [ b : B ] ... } class B { ... static belongsTo = [ a : A ] static hasMany = [ c : C ] ... } class C { ... static belongsTo = [ b : B ] ... } In my GSP page, I call an action in the Controller via a remote function in a javascript block (I'm using Dojo so I'm passing data to be saved this way... it's not a form per se so I use JSON for now to pass the data to the Controller). Let's say, I'm calling something like this: def someAction = { def jsonArr = [parse the JSON here] def tmpA = A.get(params.id) ... def tmpB = new B() b.someParam = jsonArr.someParam ... def tmpC = new C() tmpC.cParam = jsonArr.cParam tmpB.addToC(tmpC) tmpB.save(flush: true) //this may or may not be here but I'm adding it for the sake of completeness tmpA.addToB(tmpB) tmpA.save(flush: true) // NOTE: If I check here via println or whatnot, tmpA has a tmpB which has a tmpC... in other words, the data got saved. It's also in the DB. redirect(action: 'order' ...) } Then comes the fun part. Here's the webflow sample: def orderFlow = { ... someStateIShouldEndUpIn { on("next") { // or on previous... doesn't matter def anId = params.id def currA = A.get(anId) // this does NOT return a null value def testB = currA.b // this DOES return a null value }.to("somePage") ... } ... } Any ideas on why this happens? Moreover, when I dump the data of currA, b=null... instead of b=[] or b=[contents of tmpB]. Any help would be seriously appreciated... been at this for a couple of days now... Thanks!

    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

  • Hide/Show Text Field based on Selected value - ROR

    - by Tau
    I am new to ROR. I am trying to show a "Others" text field only if the selected value is "others". I am trying to make hide/show function to be as general as possible, since I will need it in many controller. If anyone can help enlightening me, I will really appreciate it. BTW, I am using Rails 2.1.1 ruby 1.8.7 general_info.html.erb <div> <%= f.label :location_id, "Location:" %> <%= f.collection_select(:location_id, Event.locations, :id, :name, {:prompt => true}, {:onchange => remote_function( :url => {:action => "showHideDOMOther"}, :with => "'selectedText='+this.options[this.selectedIndex].text + '&other_div='+'loc_other'")}) %> </div> <div id="loc_other" style="display:none"> <%= f.label :location_others, "Others:" %> <%= f.text_field :location_others %> </div> info_controller.rb def showHideDomOther render :update do |page| page.showHideDOM("Others", params[:selectedText], params[:other_div]) end end ... application_helper.rb def showHideDOM(targetString, selectedText, targetDiv) if selectedText.casecmp targetString page.hide targetDiv else page.show targetDiv end end Seem to get the correct parameters value, but nothing seems to happen. This is what I see from the console when I changed the value of selection to "Others". Parameters: {"action"=>"showHideDOMOther", "authenticity_token"=>"e7da7ce4631480b482e29da9c0fde4c026a7a70d", "other_div"=>"loc_other", "controller"=>"events", "selectedText"=>"Others"} NoMethodError (undefined method search_generic_view_paths?' for #<EventsController:0xa41c720>): /vendor/plugins/active_scaffold/lib/extensions/generic_view_paths.rb:40:infind_template_extension_from_handler' C:/usr/lib/Ruby/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_view/template_finder.rb:138:in pick_template_extension' C:/usr/lib/Ruby/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_view/template_finder.rb:115:infile_exists?' : Rendering C:/usr/lib/Ruby/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/templates/rescues/layout.erb (internal_server_error)

    Read the article

  • Passing Values to Controllers

    - by Dru
    I'm trying to allow users to 'favorite' links (that is, create a new Favorite record with their user_id and the link_id) This is what I have so far.. When I click favorite (as a user), the new record is assigned to the user_id but the link_id field is nil. How can I pass the link_id into my FavoritesController? My View Code Added Link Model Code class FavoritesController < ApplicationController def create @user = User.find(session[:user_id]) @favorite = @user.favorites.create :link_id => params[:id] redirect_to :back end end The Favorite model belongs to :user and :link Note: I've also tried this but when I click 'favorite', there's an error "Couldn't find Link without an ID." Update <%= link_to "Favorite", :controller => :favorites, :action => :create, :link_id => link.id %> with class FavoritesController < ApplicationController def create @user = User.find(session[:user_id]) @favorite = @user.favorites.create :link_id => :params[:link_id] redirect_to :back end end Returns "can't convert Symbol into Integer" app/controllers/favorites_controller.rb:4:in [] app/controllers/favorites_controller.rb:4:in create I've tried forcing it into an Integer several ways with .to_i

    Read the article

  • ActionController::RoutingError (No route matches {:action=>"show", :controller=>"users", :id=>nil}):

    - by Matt Bishop
    I have been trying to fix this routing error for a long time. I would appreciate any assistance! This error is preventing me from being able to authenticate. Here is what I am getting in my Heroku logs. app/controllers/authentications_controller.rb:12:in `create' ActionController::RoutingError (No route matches {:action=>"show", :controller=>"users", :id=>nil}) Here is the routes.rb file: Company::Application.routes.draw do resources :profile_individual resources :careers match 'careers' => 'careers#index' match 'about' => 'about#index' constraints(:subdomain => /^$|www/) do devise_for :users resources :authentications, :identities #, :beta_invitations resources :users do resources :invitations, :controller => 'UserInvitation' do post :upload, :on => :collection get :email_template, :on => :collection get :plaintext_template, :on => :collection get :facebook_invitation, :on => :collection end member do get :summary get :recruits get :friends_events get :events_near_me get :recent_activity get :impact get :campaigns end end resources :password_resets do get 'password_reset' => 'password_resets#show', :as => 'password_reset' end resources :events, :only => [:new, :index, :create] resources :organizations, :only => [:index, :create] resources :orders do post :ipn, :on => :member resource :payment do member do post :relay_response get :receipt end end resource :paypal_integration do member do get :authorize get :cancel post :finalize end end end match '/users/:id/impact/money/:d' => 'users#impact_money_graph', :constraints => {:d => /\d+{4}_\d+{2}-\d+{2}/}, :as => :user_impact_money match '/users/:id/impact/money' => 'users#impact_money_graph', :as => :user_impact_money match '/users/:id/impact/recruits/:d' => 'users#impact_recruits_graph', :constraints => {:d => /\d+{4}_\d+{2}-\d+{2}/}, :as => :user_impact_recruits match '/users/:id/impact/recruits' => 'users#impact_recruits_graph', :as => :user_impact_recruits match '/auth/failure' => 'authentications#failure' match '/auth/:provider/callback' => 'authentications#create' match '/auth/:provider/callback' => 'authentications#show', :controller => 'users', :as => :login match '/logout' => 'authentications#destroy', :as => :logout match '/login' => 'authentications#new', :as => :login match "/join_team/:id" => "team_members#join", :as => :join_team match "/rsvp/:id" => "rsvps#show", :as => :rsvp match "/signup" => 'authentications#signup', :as => :signup match "/beacon/:id.gif" => "email_beacons#show", :as => :email_beacon root :to => "homes#show" match '/corporate_giving' => "homes#corporate_giving" end constraints(Subdomain) do resource :organization, :path => "/", :only => [:edit, :update] do member do get :org_photos_videos get :org_recent_activity end end resources :events, :except => [:index] do post :publish, :on => :member resource :supporter_invite resource :team_management do post :mailer, :on => :member end resource :team_member do post :invite, :on => :member end resource :rsvp do put :make_order, :on => :collection get :make_order, :on => :collection end resources :invites do post :upload, :on => :collection end resources :ticket_tiers, :team_members end match "/events" => redirect("/") root :to => "organizations#show" end namespace :admin do resources :stats resources :organizations resources :campaigns do resources :rewards resources :contents put :header, :action => 'header_update' end resources :users do member do post :grant_access post :revoke_access end end resources :nonprofits do member do put :approve put :revoke end end end resources :campaigns do get :find_charities, :on => :collection get :how_many_charities, :on => :collection member do post :join get :join post :header, :action => 'header_creation' put :header, :action => 'header_update' end resources :rewards resources :contents resource :donations do resource :paypal_integration, :controller => 'donations' do member do get :authorize get :cancel post :finalize end end end end match '/campaigns/:id/graph/:d' => 'campaigns#graph', :constraints => {:d => /\d+{4}_\d+ {2}-\d+{2}/}, :as => :graph_campaign match '/campaigns/:id/graph' => 'campaigns#graph', :as => :graph_campaign resources :business_campaigns, :controller => 'campaigns' resources :businesses do put :logo, :on => :collection, :action => 'upload_logo' member do get :summary get :recruits get :friends_events get :events_near_me get :recent_activity get :impact get :campaigns end end resources :nonprofit_campaigns, :controller => 'campaigns' resources :nonprofits do put :logo, :on => :collection, :action => 'upload_logo' member do get :summary get :recruits get :friends_events get :events_near_me get :recent_activity get :impact get :campaigns get :supporting_campaigns end end resources :publicities match '/campaigns/:campaign_id/rewards/:id' => 'campaigns#reward', :via => :get match "/robots.txt" => "application#robots_txt" match "/beta_invitations" => redirect('/') resource :sitemap resources :referrals end Here is my authentications_controller.rb file class AuthenticationsController < ApplicationController skip_before_filter :require_beta_access before_filter :redirect_to_profile_if_logged_in, :only => [:create, :new] layout :resolve_layout def create omniauth = request.env["omniauth.auth"] authentication = Authentication.find_by_provider_and_uid(omniauth['provider'], omniauth['uid']) if authentication && authentication.user.present? sign_in(:user, authentication.user) redirect_to session[:redirect_to] || user_path(current_user, :subdomain => nil) elsif current_user current_user.authentications.create!(:provider => omniauth['provider'], :uid => omniauth['uid']) redirect_to session[:redirect_to] || user_path(current_user, :subdomain => nil) else user = User.new user.apply_omniauth(omniauth) logger.debug "=======================auth=============================" logger.debug session[:referrer_token] logger.debug "========================================================" if session[:referrer_token] publicity = Publicity.find_by_token(session[:referrer_token]) user.invited_by = publicity user.recruited_by = publicity end if user.save sign_in(user) unless session[:redirect_to] session[:referrer_token] = nil end redirect_to session[:redirect_to] || user_path(current_user, :subdomain => nil) #redirect_to session[:redirect_to] || campaigns_url(:tc => request.env['omniauth.params']['tc']) #tc is for AB testing else session[:omniauth] = omniauth.except('extra') redirect_to signup_path end end end def failure flash[:error] = "Please check your email and password and try again" redirect_to login_path end def destroy reset_session redirect_to root_path end def signup # end private def redirect_to_profile_if_logged_in redirect_to user_path(current_user.permalink) if current_user end def resolve_layout case action_name when "new", "signup" "authentication" else "selfcontained" end end end I am adding my appplication_controller.rb too: class ApplicationController < ActionController::Base #Wrote by George for beta users -before_filter :require_beta_access before_filter :save_referrer_token protect_from_forgery helper_method :organization_admin?, :team_member?, :profile_url, :current_profile def set_headers # Set our headers here end def save_referrer_token #session.delete(:referrer_token) if params[:ref] publicity = Publicity.find_by_token(params[:ref]) logger.debug "========================================================" logger.debug current_profile.nil? logger.debug publicity.creator logger.debug current_profile logger.debug current_profile != publicity.creator session[:referrer_token] = params[:ref] if current_profile.nil? or publicity.creator != current_profile logger.debug session[:referrer_token] logger.debug "========================================================" end end def robots_txt robots = File.read(Rails.root + "public/robots.#{Rails.env}.txt") render :text => robots, :layout => false, :content_type => "text/plain" end def load_organization @organization = Organization.find_by_permalink(request.subdomain) raise ActiveRecord::RecordNotFound if @organization.nil? end def require_user unless current_user session[:redirect_to] = request.url redirect_to login_url(:host => request.domain) end end def require_beta_access if !current_user redirect_to root_url(:host => request.domain) elsif !current_user.beta_access? redirect_to new_beta_invitation_url(:host => request.domain) end end def require_organization_admin unless organization_admin? redirect_to root_url(:subdomain => @organization.permalink) end end def team_member? if current_user && @event.team_memberships.where(:user_id => current_user.id).count != 0 true end end def organization_admin? if current_user && current_user.beta_access? && @organization && @organization.memberships.where(:user_id => current_user.id, :role => 'admin').count != 0 true end end def profile_url(profile, opt = nil) if profile == current_user user_url(profile, :host => opt[:host]) elsif profile.is_a? BusinessProfile business_url(profile) elsif profile.is_a? NonprofitProfile nonprofit_url(profile) end end def set_current_profile(profile) session[:current_profile] = profile end def current_user @current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token] end def current_profile #if session session[:current_profile] || current_user #else # nil #end end IGIVEMORE_HTML5_OPTIOINS = { :style => 'z-index: 0;',:width => '290', :height => '200', :frameborder => '0', :url_params => {:wmode=>"opaque"} } def campaign_header_body(camp, opt = IGIVEMORE_HTML5_OPTIOINS) if camp.header_type == Campaign::HEADER_YOUTUBE youtube_html5(camp.header_url, opt).html_safe elsif camp.header_type == Campaign::HEADER_IMAGE "<img src=\"#{camp.header_url}\" width=\"#{opt[:width]}\" height=\"#{opt[:height]}\"/>'".html_safe else "Unsupported Type!!" end end def youtube_html5(url, opt) begin video = YouTubeIt::Client.new.video_by(url) video.embed_html5(opt).gsub(/http:\/\//,"https://") rescue => e "<div style='color:red; width:290px; height:100px; padding-top:100px'>Given Video URL has problem.</div>" end end end

    Read the article

  • Ajax request gets to server but page doesn't update - Rails, jQuery

    - by Jesse
    So I have a scenario where my jQuery ajax request is hitting the server, but the page won't update. I'm stumped... Here's the ajax request: $.ajax({ type: 'GET', url: '/jsrender', data: "id=" + $.fragment().nav.replace("_link", "") }); Watching the rails logs, I get the following: Processing ProductsController#jsrender (for 127.0.0.1 at 2010-03-17 23:07:35) [GET] Parameters: {"action"=>"jsrender", "id"=>"products", "controller"=>"products"} ... Rendering products/jsrender.rjs Completed in 651ms (View: 608, DB: 17) | 200 OK [http://localhost/jsrender?id=products] So, it seems apparent to me that the ajax request is getting to the server. The code in the jsrender method is being executed, but the code in the jsrender.rjs doesn't fire. Here's the method, jsrender: def jsrender @currentview = "shared/#{params[:id]}" respond_to do |format| format.js {render :template => 'products/jsrender.rjs'} end end For the sake of argument, the code in jsrender.rjs is: page<<"alert('this works!');" Why is this? I see in the params that there is no authenticity_token, but I have tried passing an authenticity_token as well with the same result. Thanks in advance.

    Read the article

  • Pymedia video encoding failed

    - by user1474837
    I am using Python 2.5 with Windows XP. I am trying to make a list of pygame images into a video file using this function. I found the function on the internet and edited it. It worked at first, than it stopped working. This is what it printed out: Making video... Formating 114 Frames... starting loop making encoder Frame 1 process 1 Frame 1 process 2 Frame 1 process 2.5 This is the error: Traceback (most recent call last): File "ScreenCapture.py", line 202, in <module> makeVideoUpdated(record_files, video_file) File "ScreenCapture.py", line 151, in makeVideoUpdated d = enc.encode(da) pymedia.video.vcodec.VCodecError: Failed to encode frame( error code is 0 ) This is my code: def makeVideoUpdated(files, outFile, outCodec='mpeg1video', info1=0.1): fw = open(outFile, 'wb') if (fw == None) : print "Cannot open file " + outFile return if outCodec == 'mpeg1video' : bitrate= 2700000 else: bitrate= 9800000 start = time.time() enc = None frame = 1 print "Formating "+str(len(files))+" Frames..." print "starting loop" for img in files: if enc == None: print "making encoder" params= {'type': 0, 'gop_size': 12, 'frame_rate_base': 125, 'max_b_frames': 90, 'height': img.get_height(), 'width': img.get_width(), 'frame_rate': 90, 'deinterlace': 0, 'bitrate': bitrate, 'id': vcodec.getCodecID(outCodec) } enc = vcodec.Encoder(params) # Create VFrame print "Frame "+str(frame)+" process 1" bmpFrame= vcodec.VFrame(vcodec.formats.PIX_FMT_RGB24, img.get_size(), # Covert image to 24bit RGB (pygame.image.tostring(img, "RGB"), None, None) ) print "Frame "+str(frame)+" process 2" # Convert to YUV, then codec da = bmpFrame.convert(vcodec.formats.PIX_FMT_YUV420P) print "Frame "+str(frame)+" process 2.5" d = enc.encode(da) #THIS IS WHERE IT STOPS print "Frame "+str(frame)+" process 3" fw.write(d.data) print "Frame "+str(frame)+" process 4" frame += 1 print "savng file" fw.close() Could somebody tell me why I have this error and possibly how to fix it? The files argument is a list of pygame images, outFile is a path, outCodec is default, and info1 is not used anymore. UPDATE 1 This is the code I used to make that list of pygame images. from PIL import ImageGrab import time, pygame pygame.init() f = [] #This is the list that contains the images fps = 1 for n in range(1, 100): info = ImageGrab.grab() size = info.size mode = info.mode data = info.tostring() info = pygame.image.fromstring(data, size, mode) f.append(info) time.sleep(fps)

    Read the article

  • Django: DatabaseError column does not exist

    - by Rosarch
    I'm having a problem with Django 1.2.4. Here is a model: class Foo(models.Model): # ... ftw = models.CharField(blank=True) bar = models.ForeignKey(Bar) Right after flushing the database, I use the shell: Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from apps.foo.models import Foo >>> Foo.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 67, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 82, in __len__ self._result_cache.extend(list(self._iter)) File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 271, in iterator for row in compiler.results_iter(): File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 677, in results_iter for rows in self.execute_sql(MULTI): File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 732, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python2.6/dist-packages/django/db/backends/util.py", line 15, in execute return self.cursor.execute(sql, params) File "/usr/local/lib/python2.6/dist-packages/django/db/backends/postgresql_psycopg2/base.py", line 44, in execute return self.cursor.execute(query, args) DatabaseError: column foo_foo.bar_id does not exist LINE 1: ...t_omg", "foo_foo"."ftw", "foo_foo... What am I doing wrong here?

    Read the article

  • Implementing a c/c++ style union as a column in MySQL

    - by user81338
    Friends, I have a strange need and cannot think my way through the problem. The great and mighty Google is of little help due to keyword recycling (as you'll see). Can you help? What I want to do is store data of multiple types in a single column in MySQL. This is the database equivalent to a C union (and if you search for MySQL and Union, you obviously get a whole bunch of stuff on the UNION keyword in SQL). [Contrived and simplified case follows] So, let us say that we have people - who have names - and STORMTROOPERS - who have TK numbers. You cannot have BOTH a NAME and a TK number. You're either BOB SMITH -or- TK409. In C I could express this as a union, like so: union { char * name; int tkNo; } EmperialPersonnelRecord; This makes it so that I am either storing a pointer to a char array or an ID in the type EmperialPersonnelRecord, but not both. I am looking for a MySQL equivalent on a column. My column would store either an int, double, or varchar(255) (or whatever combination). But would only take up the space of the largest element. Is this possible? (of course anything is possible given enough time, money and will - I mean is it possible if I am poor, lazy and on a deadline... aka "out of the box")

    Read the article

  • Nested Resource testing RSpec

    - by Joseph DelCioppio
    I have two models: class Solution < ActiveRecord::Base belongs_to :owner, :class_name => "User", :foreign_key => :user_id end class User < ActiveRecord::Base has_many :solutions end with the following routing: map.resources :users, :has_many => :solutions and here is the SolutionsController: class SolutionsController < ApplicationController before_filter :load_user def index @solutions = @user.solutions end private def load_user @user = User.find(params[:user_id]) unless params[:user_id].nil? end end Can anybody help me with writing a test for the index action? So far I have tried the following but it doesn't work: describe SolutionsController do before(:each) do @user = Factory.create(:user) @solutions = 7.times{Factory.build(:solution, :owner => @user)} @user.stub!(:solutions).and_return(@solutions) end it "should find all of the solutions owned by a user" do @user.should_receive(:solutions) get :index, :user_id => @user.id end end And I get the following error: Spec::Mocks::MockExpectationError in 'SolutionsController GET index, when the user owns the software he is viewing should find all of the solutions owned by a user' #<User:0x000000041c53e0> expected :solutions with (any args) once, but received it 0 times Thanks in advance for all the help. Joe

    Read the article

  • Rails Model inheritance in forms

    - by Tiago
    I'm doing a reporting system for my app. I created a model ReportKind for example, but as I can report a lot of stuff, I wanted to make different groups of report kinds. Since they share a lot of behavior, I'm trying to use inheritance. So I have the main model: model ReportKind << ActiveRecord::Base end and created for example: model UserReportKind << ReportKind end In my table report_kinds I've the type column, and until here its all working. My problem is in the forms/controllers. When I do a ReportKind.new, my form is build with the '*report_kind*' prefix. If a get a UserReportKind, even through a ReportKind.find, the form will build the 'user_report_kind' prefix. This mess everything in the controllers, since sometimes I'll have params[:report_kind], sometimes params[:user_report_kind], and so on for every other inheritance I made. Is there anyway to force it to aways use the 'report_kind' prefix? Also I had to force the attribute 'type' in the controller, because it didn't get the value direct from the form, is there a pretty way to do this? Routing was another problem, since it was trying to build routes based in the inherited models names. I overcome that by adding the other models in routes pointing to the same controller.

    Read the article

  • Display HttpResponse (string from Handler) in new WebView

    - by datguywhowanders
    I have the following code in a form's submit button onClickListener: String action, user, pwd, user_field, pwd_field; action = "theURL"; user_field = "id"; pwd_field = "pw"; user = "username"; pwd = "password!!"; List<NameValuePair> myList = new ArrayList<NameValuePair>(); myList.add(new BasicNameValuePair(user_field, user)); myList.add(new BasicNameValuePair(pwd_field, pwd)); HttpParams params = new BasicHttpParams(); HttpClient client = new DefaultHttpClient(params); HttpPost post = new HttpPost(action); HttpResponse end = null; String endResult = null; try { post.setEntity(new UrlEncodedFormEntity(myList)); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { HttpResponse response = client.execute(post); end = response; } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } BasicResponseHandler myHandler = new BasicResponseHandler(); try { endResult = myHandler.handleResponse(end); } catch (HttpResponseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } How can I take the resulting string (endResult) and start a new activity using an intent that will open webview and load the html?

    Read the article

  • is using private shared objects/variables on class level harmful ?

    - by haansi
    Hello, Thanks for your attention and time. I need your opinion on an basic architectural issue please. In page behind classes I am using a private and shared object and variables (list or just client or simplay int id) to temporary hold data coming from database or class library. This object is used temporarily to catch data and than to return, pass to some function or binding a control. 1st: Can this approach harm any way ? I couldn't analyze it but a thought was using such shared variables may replace data in it when multiple users may be sending request at a time? 2nd: Please comment also on using such variables in BLL (to hold data coming from DAL/database). In this example every time new object of BLL class will be made. Here is sample code: public class ClientManager { Client objclient = new Client(); //Used in 1st and 2nd method List<Client> clientlist = new List<Client>();// used in 3rd and 4th method ClientRepository objclientRep = new ClientRepository(); public List<Client> GetClients() { return clientlist = objclientRep.GetClients(); } public List<Client> SearchClients(string Keyword) { return clientlist = objclientRep.SearchClients(Keyword); } public Client GetaClient(int ClientId) { return objclient = objclientRep.GetaClient(ClientId); } public Client GetClientDetailForConfirmOrder(int UserId) { return objclientRep.GetClientDetailForConfirmOrder(UserId); } } I am really thankful to you for sparing time and paying kind attention.

    Read the article

  • Communication with different social networks, strategy pattern?

    - by bclaessens
    Hi For the last few days I've been thinking how I can solve the following programming problem and find the ideal, flexible programming structure. (note: I'm using Flash as my platform technology but that shouldn't matter since I'm just looking for the ideal design pattern). Our Flash website has multiple situations in which it has to communicate with different social networks (Facebook, Netlog and Skyrock). Now, the communication strategy doesn't have to change multiple times over one "run". The strategy should be picked once (at launch time) for that session. The real problem is the way the communication works between each social network and our website. Some networks force us to ask for a token, others force us to use a webservice, yet another forces us to set up its communication through javascript. The problem becomes more complicated when our website has to run in each network's canvas. Which results in even more (different) ways of communicating. To sum up, our website has to work in the following cases: standalone on the campaign website url (user chooses their favourite network) communicate with netlog OR communicate with facebook OR communicate with skyrock run in a netlog canvas and log in automatically (website checks for netlog parameters) run in a facebook canvas and log in automatically (website checks for facebook params) run in a skyrock canvas and log in automatically (website checks for skyrock params) As you can see, our website needs 6 different ways to communicate with a social network. To be honest, the actual significant difference between all communication strategies is the way they have to connect to their individual network (as stated above in my example). Posting an image, make a comment, ... is the same whether it runs standalone or in the canvas url. WARNING: posting an image, posting a comment DOES differ from network to network. Should I use the strategy pattern and make 6 different communication strategies or is there a better way? An example would be great but isn't required ;) Thanks in advance

    Read the article

  • How can I call `update_attribute` for a list item in rails then actually update the html using jquery?

    - by Patrick Connor
    I want my users to be able to mark one or more items from an index view as "Active" or "Inactive" using a link. The text for the link should be state aware - so it might default to "Mark as Active" if the corresponding attribute was false or null, and "Mark as Inactive" if true. Once the user clicks the link and the attribute is updated in the controller, the link-text should update based on the new state. I am WAY off here, but this is a small sample of the code I have been trying... CONTROLLER ... respond_to :html, :js ... def update @item = Item.find(params[:id]) if @item.update_attributes(params[:item]) #Not sure of how to respond to .js here end end ... update.js.erb #how do I identify which element to update? $('#item[13456]').html("State aware text for link_to") VIEW - for item in @items = item.name = link_to "Mark as Active", item_path(item), :method => :put, :remote => true. :id => "item[#{item.id}]" I am happy to read any APIs, blogs, tutorials, etc. I just can't seem to get my hands/mind around this task. Any help or guidance is greatly appreciated!

    Read the article

  • Some questions about special operators i've never seen in C++ code.

    - by toto
    I have downloaded the Phoenix SDK June 2008 (Tools for compilers) and when I'm reading the code of the Hello sample, I really feel lost. public ref class Hello { //-------------------------------------------------------------------------- // // Description: // // Class Variables. // // Remarks: // // A normal compiler would have more flexible means for holding // on to all this information, but in our case it's simplest (if // somewhat inelegant) if we just keep references to all the // structures we'll need to access as classstatic variables. // //-------------------------------------------------------------------------- static Phx::ModuleUnit ^ module; static Phx::Targets::Runtimes::Runtime ^ runtime; static Phx::Targets::Architectures::Architecture ^ architecture; static Phx::Lifetime ^ lifetime; static Phx::Types::Table ^ typeTable; static Phx::Symbols::Table ^ symbolTable; static Phx::Phases::PhaseConfiguration ^ phaseConfiguration; 2 Questions : What's that ref keyword? What is that sign ^ ? What is it doing protected: virtual void Execute ( Phx::Unit ^ unit ) override; }; override is a C++ keyword too? It's colored as such in my Visual Studio. I really want to play with this framework, but this advanced C++ is really an obstacle right now. Thank you.

    Read the article

  • Change a finder method w/ parameters to an association

    - by Sai Emrys
    How do I turn this into a has_one association? (Possibly has_one + a named scope for size.) class User < ActiveRecord::Base has_many :assets, :foreign_key => 'creator_id' def avatar_asset size = :thumb # The LIKE is because it might be a .jpg, .png, or .gif. # More efficient methods that can handle that are OK. ;) self.assets.find :first, :conditions => ["thumbnail = '#{size}' and filename LIKE ?", self.login + "_#{size}.%"] end end EDIT: Cuing from AnalogHole on Freenode #rubyonrails, we can do this: has_many :assets, :foreign_key => 'creator_id' do def avatar size = :thumb find :first, :conditions => ["thumbnail = ? and filename LIKE ?", size.to_s, proxy_owner.login + "_#{size}.%"] end end ... which is fairly cool, and makes syntax a bit better at least. However, this still doesn't behave as well as I would like. Particularly, it doesn't allow for further nice find chaining (such that it doesn't execute this find until it's gotten all its conditions). More importantly, it doesn't allow for use in an :include. Ideally I want to do something like this: PostsController def show post = Post.get_cache(params[:id]) { Post.find(params[:id], :include => {:comments => {:users => {:avatar_asset => :thumb}} } ... end ... so that I can cache the assets together with the post. Or cache them at all, really - e.g. get_cache(user_id){User.find(user_id, :include => :avatar_assets)} would be a good first pass. This doesn't actually work (self == User), but is correct in spirit: has_many :avatar_assets, :foreign_key => 'creator_id', :class_name => 'Asset', :conditions => ["filename LIKE ?", self.login + "_%"] (Also posted on Refactor My Code.)

    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

  • How to get acts on taggable working

    - by Schipperius
    I am new to ruby on rails (and programming) and this is probably a really stupid question. I am using Rails 3.2 and trying to use acts_as_taggable_on to generate tags on articles and to have those tags show on article index and show pages as a clickable links. I have tags clickable on both the article show and index pages, but the links just go back to the index page and don't sort according to the tag name. I have scoured the Internet and pieced together the code below from various sources, but I am clearly missing something. Any help is greatly appreciated, as I have exhausted my seemingly limited knowledge! Thanks. Here is what I have: class ArticlesController < ApplicationController def tagged @articles = Article.all(:order => 'created_at DESC') @tags = Article.tag_counts_on(:tags) @tagged_articles = Article.tagged_with(params[:tags]) respond_to do |format| format.html # index.html.erb format.json { render :json => @articles } end end def index @article = Article.new @articles = Article.paginate :page => params[:page], :per_page => 3 @tags = Article.tag_counts_on(:tags) respond_to do |format| format.html # index.html.erb format.json { render json: @articles } end end module ArticlesHelper include ActsAsTaggableOn::TagsHelper end class Article < ActiveRecord::Base acts_as_ordered_taggable acts_as_ordered_taggable_on :tags, :location, :about attr_accessible :tag_list scope :by_join_date, order("created_at DESC") end article/index.html.erb <% tag_cloud(@tags, %w(tag1 tag2 tag3 tag4)) do |tag| %> <%= link_to tag.name, articles_path(:id => tag.name) %> <% end %> article/show.html.erb <%= raw @article.tags.map { |tag| link_to tag.name, articles_path(:tag_id => tag) }.join(" | ") %>

    Read the article

  • Why does my jQuery/YQL call not return anything?

    - by tastyapple
    I'm trying to access YQL with jQuery but am not getting a response: http://jsfiddle.net/tastyapple/grMb3/ Anyone know why? $(function(){ $.extend( { _prepareYQLQuery: function (query, params) { $.each( params, function (key) { var name = "#{" + key + "}"; var value = $.trim(this); if (!value.match(/^[0-9]+$/)) { value = '"' + value + '"'; } query = query.replace(name, value); } ); return query; }, yql: function (query) { var $self = this; var successCallback = null; var errorCallback = null; if (typeof arguments[1] == 'object') { query = $self._prepareYQLQuery(query, arguments[1]); successCallback = arguments[2]; errorCallback = arguments[3]; } else if (typeof arguments[1] == 'function') { successCallback = arguments[1]; errorCallback = arguments[2]; } var doAsynchronously = successCallback != null; var yqlJson = { url: "http://query.yahooapis.com/v1/public/yql", dataType: "jsonp", success: successCallback, async: doAsynchronously, data: { q: query, format: "json", env: 'store://datatables.org/alltableswithkeys', callback: "?" } } if (errorCallback) { yqlJson.error = errorCallback; } $.ajax(yqlJson); return $self.toReturn; } } ); $.yql( "SELECT * FROM github.repo WHERE id='#{username}' AND repo='#{repository}'", { username: "jquery", repository: "jquery" }, function (data) { if (data.results.repository["open-issues"].content > 0) { alert("Hey dude, you should check out your new issues!"); } } ); });

    Read the article

  • Call any webservice from the same $.ajax() call

    - by Andreas
    Hi! Im creating a usercontrol which is controled client side, it has an javascript-file attatched to it. This control has a button and upon click a popup appears, this popup shows a list of my domain entities. My entities are fetched using a call to a webservice. Im trying to get this popup usercontrol to work on all my entities, therefore i have the need to call any webservice needed (one per entity for example) with the same $.ajax() call. I have hiddenfields for the webservice url in my usercontrol which you specify in the markup via a property. So far so good. The problem arise when i need some additional parameters to the webservice (other than pagesize and pageindex). Say for example that one webservice takes an additional parameter "Date". At the moment i have my parameters set up like this: var params = JSON.stringify({ pageSize: _this.pageSize, pageIndex: _this.pageIndex }); and then i call the webservice like so: $.ajax({ webserviceUrl, params, function(result) { //some logic }); }); What i want to do is to be able to add my extra parameters (Date) to "Param" when needed, the specification of these parameters will be done via properties of the usercontrol. So, bottom line, i have a set of default parameters and want to dynamically add optional extra parameters. How is this possible? Thanks in advance.

    Read the article

  • Does Interlocked guarantee visibility to other threads in C# or do I still have to use volatile?

    - by Lirik
    I've been reading the answer to a similar question, but I'm still a little confused... Abel had a great answer, but this is the part that I'm unsure about: ...declaring a variable volatile makes it volatile for every single access. It is impossible to force this behavior any other way, hence volatile cannot be replaced with Interlocked. This is needed in scenarios where other libraries, interfaces or hardware can access your variable and update it anytime, or need the most recent version. Does Interlocked guarantee visibility of the atomic operation to all threads, or do I still have to use the volatile keyword on the value in order to guarantee visibility of the change? Here is my example: public class CountDownLatch { private volatile int m_remain; // <--- do I need the volatile keyword there since I'm using Interlocked? private EventWaitHandle m_event; public CountDownLatch (int count) { Reset(count); } public void Reset(int count) { if (count < 0) throw new ArgumentOutOfRangeException(); m_remain = count; m_event = new ManualResetEvent(false); if (m_remain == 0) { m_event.Set(); } } public void Signal() { // The last thread to signal also sets the event. if (Interlocked.Decrement(ref m_remain) == 0) m_event.Set(); } public void Wait() { m_event.WaitOne(); } }

    Read the article

  • SSE (SIMD extensions) support in gcc

    - by goldenmean
    Hi, I see a code as below: include "stdio.h" #define VECTOR_SIZE 4 typedef float v4sf __attribute__ ((vector_size(sizeof(float)*VECTOR_SIZE))); // vector of four single floats typedef union f4vector { v4sf v; float f[VECTOR_SIZE]; } f4vector; void print_vector (f4vector *v) { printf("%f,%f,%f,%f\n", v->f[0], v->f[1], v->f[2], v->f[3]); } int main() { union f4vector a, b, c; a.v = (v4sf){1.2, 2.3, 3.4, 4.5}; b.v = (v4sf){5., 6., 7., 8.}; c.v = a.v + b.v; print_vector(&a); print_vector(&b); print_vector(&c); } This code builds fine and works expectedly using gcc (it's inbuild SSE / MMX extensions and vector data types. this code is doing a SIMD vector addition using 4 single floats. I want to understand in detail what does each keyword/function call on this typedef line means and does: typedef float v4sf __attribute__ ((vector_size(sizeof(float)*VECTOR_SIZE))); What is the vector_size() function return; What is the __attribute__ keyword for Here is the float data type being type defined to vfsf type? I understand the rest part. thanks, -AD

    Read the article

  • Reading the .vcproj file with C#

    - by Dulantha Fernando
    We create the vcproj file with the makefileproj keyword so we can use our own build in VS. My question is, using C#, how do you read the "C++" from the following vcproj file: <?xml version="1.0" encoding="Windows-1252"?> <VisualStudioProject ProjectType="Visual C++" Version="8.00" Name="TestCSProj" ProjectGUID="{840501C9-6AFE-8CD6-1146-84208624C0B0}" RootNamespace="TestCSProj" Keyword="MakeFileProj" > <Platforms> <Platform Name="x64" /> <Platform Name="C++" ===> I need to read "C++" /> </Platforms> I used XmlNode and got upto the second Platform: String path = "C:\\blah\\TestCSProj\\TestCSProj\\TestCSProj.vcproj"; FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(fs); XmlNodeList oldFiles = xmldoc.GetElementsByTagName("Platform"); XmlAttribute name = oldFiles[1].Attributes[0]; Console.WriteLine(name.Name); This will print Name, but I need "C++". How do I read that? Thank you very much in advance

    Read the article

  • WHY JSLint complains: "someFunction() was used before it was defined"?

    - by 7hi4g0
    Searching for the JSLint error "was used before it was defined" i've found these: JSLint: Using a function before it's defined error Function was used before it was defined - JSLint JSLint: was used before it was defined jsLint error: “somefunction() was used before it was defined” jslint - Should we tolerate misordered definitions? Problem None of those answers WHY the error is shown. Elaboration According to the ECMA-262 Specification functions are evaluated before execution starts, hence all functions declared using the function keyword are available to all the code idenpendent of the place they were declared (assuming they are acessible on that scope). This is otherwise known as hoisting. Douglas Crockford seems to think it is better to declare every function before the code that uses it regardless of the hoisting effect. According to StackOverflowNewbie in his question, this raises some code organization problems. Not to mention some people, like me, prefer to declare their functions underneath the main/init code. On those questions there are some ways to avoid or fix the error, such as using function expressions vs function declarations. But none of them showed me the reason of the error. Not even Crockford's site. Question(s) Why is it an error to call a function before the declaration, even if it was declared using the function keyword? Is it better to use function expressions instead of function declaration in the JSLint context? If one is preferred, why? Note Not looking for answers like: Crockford is a tyrant Is just Crockford's opinion Thank you :*

    Read the article

< Previous Page | 72 73 74 75 76 77 78 79 80 81 82 83  | Next Page >