Search Results

Search found 4969 results on 199 pages for 'def'.

Page 13/199 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >

  • Beginner questions regarding Python classes.

    - by Andy
    Hi. I am new to Python so please don't flame me if I ask something too noobish :) 1. Consider I have a class: class Test: def __init__(self, x, y): self.x = x self.y = y def wow(): print 5 * 5 Now I try to create an object of the class: x = Test(3, 4) This works as expected. However, when I try to call the method wow(), it returns an error, which is fixed by changing wow() to: def wow(self) Why do I need to include self and if I don't, what does the method mean?2. In the definition of __init__: def __init__(self, x, y): self.x = x self.y = y Why do I need to declare x and y, when I can do this: def __init__(self): self.x = x self.y = y I hope I am being clear... Thanks for your time.

    Read the article

  • What's the preferred way to use helper methods in Ruby?

    - by DR
    Disclaimer: Although I'm asking in context of a Rails application, I'm not talking about Rails helpers (i.e. view helpers) Let's say I have a helper method/function: def dispatch_job(job = {}) #Do something end Now I want to use this from several places (mostly controllers, but also a few BackgrounDRb workers) What's the preferred way to do this? I can think of two possibilities: 1. Use a class and make the helper a static method: class MyHelper def self.dispatch_job(job = {}) end end class MyWorker def run MyHelper.dispatch_job(...) end end 2. Use a module and include the method into whatever class I need this functionality module MyHelper def self.dispatch_job(job = {}) end end class MyWorker include MyHelper def run dispatch_job(...) end end 3. Other possibilities I don't know yet ... The first one is more Java-like, but I'm not sure if the second one is really an appropriate use of Ruby's modules.

    Read the article

  • Grails: Duplicates & unique constraint validation

    - by rukoche
    OK here is stripped down version of what I have in my app Artist domain: class Artist { String name Date lastMined def artistService static transients = ['artistService'] static hasMany = [events: Event] static constraints = { name(unique: true) lastMined(nullable: true) } def mine() { artistService.mine(this) } } Event domain: class Event { String name String details String country String town String place String url String date static belongsTo = [Artist] static hasMany = [artists: Artist] static constraints = { name(unique: true) url(unique: true) } } ArtistService: class ArtistService { def results = [ [ name:"name", details:"details", country:"country", town:"town", place:"place", url:"url", date:"date" ] ] def mine(Artist artist) { results << results[0] // now we have a duplicate results.each { def event = new Event(it) if (event.validate()) { if (artist.events.find{ it.name == event.name }) { log.info "grrr! valid duplicate name: ${event.name}" } artist.addToEvents(event) } } artist.lastMined = new Date() if (artist.events) { artist.save(flush: true) } } } In theory event.validate() should return false and event will not be added to artist, but it doesn't.. which results in DB exception on artist.save() Although I noticed that if duplicate event is persisted first everything works as intended. Is it bug or feature? :P

    Read the article

  • Sending object C from class A to class B

    - by user278618
    Hi, I can't figure out how to design classes in my system. In classA I create object selenium (it simulates user actions at website). In this ClassA I create another objects like SearchScreen, Payment_Screen and Summary_Screen. # -*- coding: utf-8 -*- from selenium import selenium import unittest, time, re class OurSiteTestCases(unittest.TestCase): def setUp(self): self.verificationErrors = [] self.selenium = selenium("localhost", 5555, "*chrome", "http://www.someaddress.com/") time.sleep(5) self.selenium.start() def test_buy_coffee(self): sel = self.selenium sel.open('/') sel.window_maximize() search_screen=SearchScreen(self.selenium) search_screen.choose('lavazza') payment_screen=PaymentScreen(self.selenium) payment_screen.fill_test_data() summary_screen=SummaryScreen(selenium) summary_screen.accept() def tearDown(self): self.selenium.stop() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main() It's example SearchScreen module: class SearchScreen: def __init__(self,selenium): self.selenium=selenium def search(self): self.selenium.click('css=button.search') I want to know if there is anything ok with a design of those classes?

    Read the article

  • how to use listctrl in notebook wxPython

    - by ???
    I have one question.. wxPython listctrl in notebook I created 2 tab use notebook. I added button in first tab and added Listctrl in second tab. If i click the button, Add value in Listctrl to second tab. how to solve this problem? import wx class PageOne(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.query_find_btn = wx.Button(self, 4, "BTN", (40,40)) self.Bind(wx.EVT_BUTTON, self.AddList, id = 4) def AddList(self, evt): self.list1.InsertStringItem(0,'Hello') class PageTwo(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.list1 = wx.ListCtrl(self,-1,wx.Point(0,0),wx.Size(400,400),style=wx.LC_REPORT | wx.SUNKEN_BORDER) self.list1.InsertColumn(0,'values') class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self,parent,id,title,size=(400,400),pos=wx.Point(100,100), style=wx.SYSTEM_MENU |wx.CAPTION ) p = wx.Panel(self) nb = wx.Notebook(p) MainFrame = PageOne(nb) SecondFrame = PageTwo(nb) nb.AddPage(MainFrame, "One") nb.AddPage(SecondFrame, "Two") sizer = wx.BoxSizer() sizer.Add(nb, 1, wx.EXPAND) p.SetSizer(sizer) class MyApp(wx.App): def OnInit(self): self.frame=MyFrame(None,-1,'Unknown.py') self.frame.Centre() self.frame.Show() return True if __name__ == '__main__': app = MyApp(False) app.MainLoop()

    Read the article

  • Ruby Koans 202: Why does the correct answer give a syntax error?

    - by hlh
    I'm working through the about_classes.rb file in the Ruby Koans, and have hit a brick wall with the "inside_a_method_self_refers_to_the_containing_object" test. Here's the code: class Dog7 attr_reader :name def initialize(initial_name) @name = initial_name end def get_self self end def to_s __ end def inspect "<Dog named '#{name}'>" end end def test_inside_a_method_self_refers_to_the_containing_object fido = Dog7.new("Fido") fidos_self = fido.get_self assert_equal <Dog named 'Fido'>, fidos_self end So, I'm trying to make the first half of the assert_equal evaluate to the second half (fidos_self). When I work it out in irb, fidos_self returns <Dog named 'Fido'>, but I keep receiving a syntax error for that answer. I've seen this similar post: Ruby Koans: Where are the quotes in this return value?, but his solution (putting fido instead of <Dog named 'Fido'>) causes my rake to abort, saying the stack level is too deep. This is driving me nuts. What am I missing here?

    Read the article

  • How to make pytest display a custom string representation for fixture parameters?

    - by Björn Pollex
    When using builtin types as fixture parameters, pytest prints out the value of the parameters in the test report. For example: @fixture(params=['hello', 'world'] def data(request): return request.param def test_something(data): pass Running this with py.test --verbose will print something like: test_example.py:7: test_something[hello] PASSED test_example.py:7: test_something[world] PASSED Note that the value of the parameter is printed in square brackets after the test name. Now, when using an object of a user-defined class as parameter, like so: class Param(object): def __init__(self, text): self.text = text @fixture(params=[Param('hello'), Param('world')] def data(request): return request.param def test_something(data): pass pytest will simply enumerate the number of values (p0, p1, etc.): test_example.py:7: test_something[p0] PASSED test_example.py:7: test_something[p1] PASSED This behavior does not change even when the user-defined class provides custom __str__ and __repr__ implementations. Is there any way to make pytest display something more useful than just p0 here? I am using pytest 2.5.2 on Python 2.7.6 on Windows 7.

    Read the article

  • Writing Strings to files in python

    - by Leif Andersen
    I'm getting the following error when trying to write a string to a file in pythion: Traceback (most recent call last): File "export_off.py", line 264, in execute save_off(self.properties.path, context) File "export_off.py", line 244, in save_off primary.write(file) File "export_off.py", line 181, in write variable.write(file) File "export_off.py", line 118, in write file.write(self.value) TypeError: must be bytes or buffer, not str I basically have a string class, which contains a string: class _off_str(object): __slots__ = 'value' def __init__(self, val=""): self.value=val def get_size(self): return SZ_SHORT def write(self,file): file.write(self.value) def __str__(self): return str(self.value) Furthermore, I'm calling that class like this: def write(self, file): for variable in self.variables: variable.write(file) I have no idea what is going on. I've seen other python programs writing strings to files, so why can't this one? Thank you very much for your help.

    Read the article

  • Scala, represent pattern of boolean tuple into something else.

    - by Berlin Brown
    This is a cellular automata rule (input Boolean == Left, Center, Right Cell) and output Boolean . What is a better way to represent this in Scala. trait Rule { def ruleId() : Int def rule(inputState:(Boolean, Boolean, Boolean)) : Boolean override def toString : String = "Rule:" + ruleId } class Rule90 extends Rule { def ruleId() = 90 def rule(inputState:(Boolean, Boolean, Boolean)) : Boolean = { // Verbose version, show all 8 states inputState match { case (true, true, true) => false case (true, false, true) => false case (false, true, false) => false case (false, false, false) => false case _ => true } } }

    Read the article

  • grailsApplication not getting injected in a service , Grails 2.1.0

    - by vijay tyagi
    I have service in which i am accessing few configuration properties from grailsApplication I am injecting it like this class MyWebService{ def grailsApplication WebService webService = new WebService() def getProxy(url, flag){ return webService.getClient(url) } def getResponse(){ def proxy = getProxy(grailsApplication.config.grails.wsdlURL, true) def response = proxy.getItem(ItemType) return response } } When i call getProxy() method, i see this in tomcat logs No signature of method: org.example.MyWebService.getProxy() is applicable for argument types: (groovy.util.ConfigObject, java.lang.Boolean) values: [[:], true] Possible solutions: getProxy(), getProxy(java.lang.String, boolean), setProxy(java.lang.Object) which means grailsApplication is not getting injected into the service, is there any alternate way to access configuration object ? according to burtbeckwith's post configurationholder has been deprecated, can't think of anything else. Interestingly the very same service works fine in my local IDE(GGTS 3.1.0), that means locally grailsApplication is getting injected, but when i create a war to deploy to a standalone tomcat, it stops getting injected.

    Read the article

  • Ruby Metaprogramming

    - by Veerendra Manikonda
    I am having a method which returns the price of a given symbol and i am writing a test for that method. This is my test def setup @asset = NetAssetValue.new end def test_retrieve_price_for_symbol_YHOO assert_equal(33.987, @asset.retrieve_price_for_a_symbol('YHOO')) end def test_retrive_price_for_YHOO def self.retrieve_price_for_a_symbol(symbol) 33.77 end assert_equal(33.97, @asset.retrieve_price_for_a_symbol('YHOO')) end This is my method. def retrieve_price_for_a_symbol(symbol) symbol_price = { "YHOO" => 33.987, "UPS" => 35.345, "T" => 80.90 } raise Exception if(symbol_price[symbol].nil?) symbol_price[symbol] end I am trying to mock the retrieve_price_for_a_symbol method by writing same method in test class but when i call it, the call is happening to method in main class not in the test class. How do I add that method to meta class from test and how do i call it? Please help.

    Read the article

  • Django & custom auth backend (web service) + no database. How to save stuff in session?

    - by Infinity
    I've been searching here and there, and based on this answer I've put together what you see below. It works, but I need to put some stuff in the user's session, right there inside authenticate. How would I store acme_token in the user's session, so that it will get cleared if they logged out? class AcmeUserBackend(object): # Create a User object if not already in the database? create_unknown_user = False def get_user(self, username): return AcmeUser(id=username) def authenticate(self, username=None, password=None): """ Check the username/password and return an AcmeUser. """ acme_token = ask_another_site_about_creds(username, password) if acme_token: return AcmeUser(id=username) return None ################## from django.contrib.auth.models import User class AcmeUser(User): objects = None # we cannot really use this w/o local DB def save(self): """saving to DB disabled""" pass def get_group_permissions(self): """If you don't make your own permissions module, the default also will use the DB. Throw it away""" return [] # likewise with the other permission defs def get_and_delete_messages(self): """Messages are stored in the DB. Darn!""" return []

    Read the article

  • Elegant way to add functionallity to previously defined functions

    - by Bastiaan
    How to combine two functions together I have a class controlling some hardware: class Heater() def set_power(self,dutycycle, period) ... def turn_on(self) ... def turn_off(self) And a class that connects to a database and handles all data logging fuctionallity for an experiment: class DataLogger() def __init__(self) # Record measurements and controls in a database def start(self,t) # Starts a new thread to aqcuire and reccord measuements every t secconds Now, in my program recipe.py I want to do something like: log = DataLogger() @DataLogger_decorator H1 = Heater() log.start(60) H1.set_power(10,100) H1.turn_on() sleep(10) H1.turn_off() etc Where all actions on H1 are recorded by the datalogger. I can change any of the classes involved, just looking for an elegant way to do this. Ideally the hardware functions remain separated from the database and DataLogger functions. And ideally the DataLogger is reusable for other controls and measurements.

    Read the article

  • Functions without arguments, with unit as argument in scala

    - by scout
    def foo(x:Int, f:Unit=>Int) = println(f()) foo(2, {Unit => 3+4} //case1 def loop:Int = 7 foo(2, loop) //does not compile changing loop to //case 2 def loop():Int = 7 foo(2, loop) // does not compile changing loop to //case 3 def loop(x:Unit): Int = 7 //changing according to Don's Comments foo(2,loop) // compiles and works fine should'nt case 1 and case 2 also work? why are they not working? defining foo as def foo(x:Int, y:()=>Int) then case 2 works but not case 1. Arent they all supposed to work, defining the functions either way. //also i think ()=Int in foo is a bad style, y:=Int does not work, comments??

    Read the article

  • Access to related Objects inside a model propery

    - by aliem
    Hi, I just run into some problems with django models. Example code is better than any word: class Cart(models.Model): updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) def __unicode__(self): return u'date %s;'%(self.created_at) def __str__(self): return self.__unicode__() def _total_items(self): """ Totale n di oggetti """ a = 0 for i in self.items.all: a += i.quantity return a total_items = property(_total_items) class Item(models.Model): cart = models.ForeignKey(Cart) quantity = models.PositiveIntegerField() def __unicode__(self): return u'product %s'%(self.id) def __str__(self): return self.__unicode__() but, when i call the cart property here's what i get in the python console: >>> a.total_items Traceback (most recent call last): File "<console>", line 1, in <module> File "models.py", line 49, in _total_items for i in self.item_set.all: TypeError: 'RelatedManager' object is not callable

    Read the article

  • Double "!!" in Ruby [closed]

    - by Alex Maslakov
    Possible Duplicate: What does !! mean in ruby? Ruby, !! operator (a/k/a the double-bang) Sometimes I see a Ruby code like this def sent? !!@sent_at end It seems to be not logical. Is it necessary to use here double !? As far as I'm concerned, it might be just def sent? @sent_at end UPDATE: then what is the difference between these def sent? !!@sent_at end def sent? @sent_at.nil? end def sent? @sent_at == nil end

    Read the article

  • Python - How can I make this code asynchronous?

    - by dave
    Here's some code that illustrates my problem: def blocking1(): while True: yield 'first blocking function example' def blocking2(): while True: yield 'second blocking function example' for i in blocking1(): print 'this will be shown' for i in blocking2(): print 'this will not be shown' I have two functions which contain while True loops. These will yield data which I will then log somewhere (most likely, to an sqlite database). I've been playing around with threading and have gotten it working. However, I don't really like it... What I would like to do is make my blocking functions asynchronous. Something like: def blocking1(callback): while True: callback('first blocking function example') def blocking2(callback): while True: callback('second blocking function example') def log(data): print data blocking1(log) blocking2(log) How can I achieve this in Python? I've seen the standard library comes with asyncore and the big name in this game is Twisted but both of these seem to be used for socket IO. How can I async my non-socket related, blocking functions?

    Read the article

  • Bundler isn't loading gems

    - by Garrett
    I have been having a problem with using Bundler and being able to access my gems without having to require them somewhere, as config.gem used to do that for me (as far as I know). In my Rails 3 app, I defined my Gemfile like so: clear_sources source "http://gemcutter.org" source "http://gems.github.com" bundle_path "vendor/bundler_gems" ## Bundle edge rails: git "git://github.com/rails/arel.git" git "git://github.com/rails/rack.git" gem "rails", :git => "git://github.com/rails/rails.git" ## Bundle gem "mongo_mapper", :git => "git://github.com/jnunemaker/mongomapper.git" gem "bluecloth", ">= 2.0.0" Then I run gem bundle, it bundles it all up like expected. Inside the environment.rb file that is included within boot.rb it looks like this: # DO NOT MODIFY THIS FILE module Bundler file = File.expand_path(__FILE__) dir = File.dirname(file) ENV["PATH"] = "#{dir}/../../../../bin:#{ENV["PATH"]}" ENV["RUBYOPT"] = "-r#{file} #{ENV["RUBYOPT"]}" $LOAD_PATH.unshift File.expand_path("#{dir}/gems/builder-2.1.2/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/builder-2.1.2/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/text-hyphen-1.0.0/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/text-hyphen-1.0.0/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/i18n-0.3.3/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/i18n-0.3.3/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/arel/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/arel/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activemodel/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activemodel/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/jnunemaker-validatable-1.8.1/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/jnunemaker-validatable-1.8.1/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/abstract-1.0.0/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/abstract-1.0.0/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/erubis-2.6.5/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/erubis-2.6.5/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/mime-types-1.16/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/mime-types-1.16/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/mail-2.1.2/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/mail-2.1.2/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/rake-0.8.7/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/rake-0.8.7/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/railties/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/railties/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/memcache-client-1.7.7/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/memcache-client-1.7.7/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rack/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rack/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/rack-test-0.5.3/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/rack-test-0.5.3/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/rack-mount-0.4.5/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/rack-mount-0.4.5/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/actionpack/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/actionpack/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/bluecloth-2.0.7/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/bluecloth-2.0.7/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/bluecloth-2.0.7/ext") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activerecord/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activerecord/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/text-format-1.0.0/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/text-format-1.0.0/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/actionmailer/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/actionmailer/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/tzinfo-0.3.16/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/tzinfo-0.3.16/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activesupport/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activesupport/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activeresource/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/activeresource/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/rails/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/mongo-0.18.2/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/gems/mongo-0.18.2/lib") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/mongomapper/bin") $LOAD_PATH.unshift File.expand_path("#{dir}/dirs/mongomapper/lib") @gemfile = "#{dir}/../../../../Gemfile" require "rubygems" unless respond_to?(:gem) # 1.9 already has RubyGems loaded @bundled_specs = {} @bundled_specs["builder"] = eval(File.read("#{dir}/specifications/builder-2.1.2.gemspec")) @bundled_specs["builder"].loaded_from = "#{dir}/specifications/builder-2.1.2.gemspec" @bundled_specs["text-hyphen"] = eval(File.read("#{dir}/specifications/text-hyphen-1.0.0.gemspec")) @bundled_specs["text-hyphen"].loaded_from = "#{dir}/specifications/text-hyphen-1.0.0.gemspec" @bundled_specs["i18n"] = eval(File.read("#{dir}/specifications/i18n-0.3.3.gemspec")) @bundled_specs["i18n"].loaded_from = "#{dir}/specifications/i18n-0.3.3.gemspec" @bundled_specs["arel"] = eval(File.read("#{dir}/specifications/arel-0.2.pre.gemspec")) @bundled_specs["arel"].loaded_from = "#{dir}/specifications/arel-0.2.pre.gemspec" @bundled_specs["activemodel"] = eval(File.read("#{dir}/specifications/activemodel-3.0.pre.gemspec")) @bundled_specs["activemodel"].loaded_from = "#{dir}/specifications/activemodel-3.0.pre.gemspec" @bundled_specs["jnunemaker-validatable"] = eval(File.read("#{dir}/specifications/jnunemaker-validatable-1.8.1.gemspec")) @bundled_specs["jnunemaker-validatable"].loaded_from = "#{dir}/specifications/jnunemaker-validatable-1.8.1.gemspec" @bundled_specs["abstract"] = eval(File.read("#{dir}/specifications/abstract-1.0.0.gemspec")) @bundled_specs["abstract"].loaded_from = "#{dir}/specifications/abstract-1.0.0.gemspec" @bundled_specs["erubis"] = eval(File.read("#{dir}/specifications/erubis-2.6.5.gemspec")) @bundled_specs["erubis"].loaded_from = "#{dir}/specifications/erubis-2.6.5.gemspec" @bundled_specs["mime-types"] = eval(File.read("#{dir}/specifications/mime-types-1.16.gemspec")) @bundled_specs["mime-types"].loaded_from = "#{dir}/specifications/mime-types-1.16.gemspec" @bundled_specs["mail"] = eval(File.read("#{dir}/specifications/mail-2.1.2.gemspec")) @bundled_specs["mail"].loaded_from = "#{dir}/specifications/mail-2.1.2.gemspec" @bundled_specs["rake"] = eval(File.read("#{dir}/specifications/rake-0.8.7.gemspec")) @bundled_specs["rake"].loaded_from = "#{dir}/specifications/rake-0.8.7.gemspec" @bundled_specs["railties"] = eval(File.read("#{dir}/specifications/railties-3.0.pre.gemspec")) @bundled_specs["railties"].loaded_from = "#{dir}/specifications/railties-3.0.pre.gemspec" @bundled_specs["memcache-client"] = eval(File.read("#{dir}/specifications/memcache-client-1.7.7.gemspec")) @bundled_specs["memcache-client"].loaded_from = "#{dir}/specifications/memcache-client-1.7.7.gemspec" @bundled_specs["rack"] = eval(File.read("#{dir}/specifications/rack-1.1.0.gemspec")) @bundled_specs["rack"].loaded_from = "#{dir}/specifications/rack-1.1.0.gemspec" @bundled_specs["rack-test"] = eval(File.read("#{dir}/specifications/rack-test-0.5.3.gemspec")) @bundled_specs["rack-test"].loaded_from = "#{dir}/specifications/rack-test-0.5.3.gemspec" @bundled_specs["rack-mount"] = eval(File.read("#{dir}/specifications/rack-mount-0.4.5.gemspec")) @bundled_specs["rack-mount"].loaded_from = "#{dir}/specifications/rack-mount-0.4.5.gemspec" @bundled_specs["actionpack"] = eval(File.read("#{dir}/specifications/actionpack-3.0.pre.gemspec")) @bundled_specs["actionpack"].loaded_from = "#{dir}/specifications/actionpack-3.0.pre.gemspec" @bundled_specs["bluecloth"] = eval(File.read("#{dir}/specifications/bluecloth-2.0.7.gemspec")) @bundled_specs["bluecloth"].loaded_from = "#{dir}/specifications/bluecloth-2.0.7.gemspec" @bundled_specs["activerecord"] = eval(File.read("#{dir}/specifications/activerecord-3.0.pre.gemspec")) @bundled_specs["activerecord"].loaded_from = "#{dir}/specifications/activerecord-3.0.pre.gemspec" @bundled_specs["text-format"] = eval(File.read("#{dir}/specifications/text-format-1.0.0.gemspec")) @bundled_specs["text-format"].loaded_from = "#{dir}/specifications/text-format-1.0.0.gemspec" @bundled_specs["actionmailer"] = eval(File.read("#{dir}/specifications/actionmailer-3.0.pre.gemspec")) @bundled_specs["actionmailer"].loaded_from = "#{dir}/specifications/actionmailer-3.0.pre.gemspec" @bundled_specs["tzinfo"] = eval(File.read("#{dir}/specifications/tzinfo-0.3.16.gemspec")) @bundled_specs["tzinfo"].loaded_from = "#{dir}/specifications/tzinfo-0.3.16.gemspec" @bundled_specs["activesupport"] = eval(File.read("#{dir}/specifications/activesupport-3.0.pre.gemspec")) @bundled_specs["activesupport"].loaded_from = "#{dir}/specifications/activesupport-3.0.pre.gemspec" @bundled_specs["activeresource"] = eval(File.read("#{dir}/specifications/activeresource-3.0.pre.gemspec")) @bundled_specs["activeresource"].loaded_from = "#{dir}/specifications/activeresource-3.0.pre.gemspec" @bundled_specs["rails"] = eval(File.read("#{dir}/specifications/rails-3.0.pre.gemspec")) @bundled_specs["rails"].loaded_from = "#{dir}/specifications/rails-3.0.pre.gemspec" @bundled_specs["mongo"] = eval(File.read("#{dir}/specifications/mongo-0.18.2.gemspec")) @bundled_specs["mongo"].loaded_from = "#{dir}/specifications/mongo-0.18.2.gemspec" @bundled_specs["mongo_mapper"] = eval(File.read("#{dir}/specifications/mongo_mapper-0.6.10.gemspec")) @bundled_specs["mongo_mapper"].loaded_from = "#{dir}/specifications/mongo_mapper-0.6.10.gemspec" def self.add_specs_to_loaded_specs Gem.loaded_specs.merge! @bundled_specs end def self.add_specs_to_index @bundled_specs.each do |name, spec| Gem.source_index.add_spec spec end end add_specs_to_loaded_specs add_specs_to_index def self.require_env(env = nil) context = Class.new do def initialize(env) @env = env && env.to_s ; end def method_missing(*) ; yield if block_given? ; end def only(*env) old, @only = @only, _combine_only(env.flatten) yield @only = old end def except(*env) old, @except = @except, _combine_except(env.flatten) yield @except = old end def gem(name, *args) opt = args.last.is_a?(Hash) ? args.pop : {} only = _combine_only(opt[:only] || opt["only"]) except = _combine_except(opt[:except] || opt["except"]) files = opt[:require_as] || opt["require_as"] || name files = [files] unless files.respond_to?(:each) return unless !only || only.any? {|e| e == @env } return if except && except.any? {|e| e == @env } if files = opt[:require_as] || opt["require_as"] files = Array(files) files.each { |f| require f } else begin require name rescue LoadError # Do nothing end end yield if block_given? true end private def _combine_only(only) return @only unless only only = [only].flatten.compact.uniq.map { |o| o.to_s } only &= @only if @only only end def _combine_except(except) return @except unless except except = [except].flatten.compact.uniq.map { |o| o.to_s } except |= @except if @except except end end context.new(env && env.to_s).instance_eval(File.read(@gemfile), @gemfile, 1) end end module Gem @loaded_stacks = Hash.new { |h,k| h[k] = [] } def source_index.refresh! super Bundler.add_specs_to_index end end But when I try to access any of my gems, e.g. MongoMapper, Paperclip, Haml, etc. I get: NameError: uninitialized constant MongoMapper The same goes for any other gem. Does Bundler not include gems like the old Rails 2.0 did? Or is something messed up with my system? Any help would be appreciated, thank you!

    Read the article

  • PyQt4 and QTableView with spinbox and checkbox

    - by ekapek
    Hi, I have a QTableView with QSqlTableModel and with 3 columns, now I need to have: - second column: spinbox after clicked to edit - third column: checkbox (displayed center) My code: class SpinBoxDelegate(QtGui.QItemDelegate): def createEditor(self, parent, option, index): editor = QtGui.QSpinBox(parent) editor.setMinimum(0) editor.setMaximum(100) print 'spinbox' return editor def setEditorData(self, spinBox, index): value = index.model().data(index, QtCore.Qt.EditRole).toInt()[0] spinBox.setValue(value) def setModelData(self, spinBox, model, index): spinBox.interpretText() value = spinBox.value() model.setData(index, value, QtCore.Qt.EditRole) def updateEditorGeometry(self, editor, option, index): editor.setGeometry(option.rect) class myQSqlTableModel(QtSql.QSqlTableModel): def flags(self,index): result = QtSql.QSqlTableModel.flags(self,index); if index.column() == 2: result |= QtCore.Qt.ItemIsUserCheckable return result def data(self,index,role): if not index.isValid: return QtCore.QVariant() value = QtSql.QSqlTableModel.data(self, index, role) if index.column() == 2: if role == QtCore.Qt.CheckStateRole: return QtCore.Qt.Unchecked if QtSql.QSqlTableModel.data(self, index).toInt()[0] else QtCore.Qt.Checked elif role == QtCore.Qt.DisplayRole: return QtCore.QVariant() return value and self.model = myQSqlTableModel(self) self.model.setTable("person") self.model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit) self.model.select(): self.model.setHeaderData(0, QtCore.Qt.Horizontal, self.tr("ID")) self.model.setHeaderData(1, QtCore.Qt.Horizontal, self.tr("A")) self.model.setHeaderData(2, QtCore.Qt.Horizontal, self.tr("B")) self.view = QtGui.QTableView() self.view.setModel(self.model) self.view.setSortingEnabled(True) spinDelegate = SpinBoxDelegate() self.view.setItemDelegateForColumn(1,spinDelegate) but it does't work: spinbox don't show after click and checkbox can't be clicked and is aligned to left Any help?

    Read the article

  • [Gray Hat Python] Simple debugger, want work ??

    - by Rami Jarrar
    hi, i'm reading the Gray Hat Python,, i reach for this :: class debugger(): def __init__(self): self.h_process = None self.pid = None self.debugger_active = False def load(self,path_to_exe): creation_flags = DEBUG_PROCESS startupinfo = STARTUPINFO() process_information = PROCESS_INFORMATION() startupinfo.dwFlags = 0x1 startupinfo.wShowWindows = 0x0 startupinfo.cb = sizeof(startupinfo) if kernel32.CreateProcessA(path_to_exe, None, None, None, None, creation_flags, None, None, byref(startupinfo), byref(process_information)): print "[*] We have successfully launched the process!" print "[*] PID: %d"%(process_information.dwProcessId) self.h_process = self.open_process(process_information.dwProcessId) else: print "[*] Error: 0x%08x."%(kernel32.GetLastError()) def open_process(self,pid): h_process = self.open_process(pid) if kernel32.DebugActiveProcess(pid): self.debugger_active = True self.pid = int(pid) self.run() else: print "[*] Unable to attach to the process." def run(self): while self.debugger_active == True: self.get_debug_event() def get_debug_event(self): debug_event = DEBUG_EVENT() continue_status = DBG_CONTINUE if kernel32.WaitForDebugEvent(byref(debug_event), INFINITE): raw_input("Press a Key to continue...") self.debugger_active = False kernel32.ContinueDebugEvent( \ debug_event.dwProcessId, \ debug_event.dwThreadId, \ continue_status ) def detach(self): if kernel32.DebugActiveProcessStop(self.pid): print "[*] Finished debugging. Exiting..." return True else: print "There was an error" return False when run my_test.py :: import my_dbg debugger = my_dbg.debugger() pid = raw_input('Enter the PID of the process to attach to: ') debugger.open_process(int(pid)) debugger.detach() i get this error :: Traceback (most recent call last): File "C:/Python26/dbgpy/my_test.py", line 5, in <module> debugger.attach(int(pid)) File "C:/Python26/dbgpy\my_dbg.py", line 37, in attach h_process = self.attach(pid) ........... ........... ........... File "C:/Python26/dbgpy\my_dbg.py", line 37, in attach h_process = self.attach(pid) File "C:/Python26/dbgpy\my_dbg.py", line 37, in attach h_process = self.attach(pid) RuntimeError: maximum recursion depth exceeded its because the loop and something else, but what it is ?? I'm running on Windows using Python2.6.4.. :) Update:: i remove h_process = self.open_process(pid), but i get the same error for the next instruction if kernel32.DebugActiveProcess(pid) , so the problem i think in the loop while,, but what it is ???

    Read the article

  • HOW TO: Draggable legend in matplotlib

    - by Adam Fraser
    QUESTION: I'm drawing a legend on an axes object in matplotlib but the default positioning which claims to place it in a smart place doesn't seem to work. Ideally, I'd like to have the legend be draggable by the user. How can this be done? SOLUTION: Well, I found bits and pieces of the solution scattered among mailing lists. I've come up with a nice modular chunk of code that you can drop in and use... here it is: class DraggableLegend: def __init__(self, legend): self.legend = legend self.gotLegend = False legend.figure.canvas.mpl_connect('motion_notify_event', self.on_motion) legend.figure.canvas.mpl_connect('pick_event', self.on_pick) legend.figure.canvas.mpl_connect('button_release_event', self.on_release) legend.set_picker(self.my_legend_picker) def on_motion(self, evt): if self.gotLegend: dx = evt.x - self.mouse_x dy = evt.y - self.mouse_y loc_in_canvas = self.legend_x + dx, self.legend_y + dy loc_in_norm_axes = self.legend.parent.transAxes.inverted().transform_point(loc_in_canvas) self.legend._loc = tuple(loc_in_norm_axes) self.legend.figure.canvas.draw() def my_legend_picker(self, legend, evt): return self.legend.legendPatch.contains(evt) def on_pick(self, evt): if evt.artist == self.legend: bbox = self.legend.get_window_extent() self.mouse_x = evt.mouseevent.x self.mouse_y = evt.mouseevent.y self.legend_x = bbox.xmin self.legend_y = bbox.ymin self.gotLegend = 1 def on_release(self, event): if self.gotLegend: self.gotLegend = False ...and in your code... def draw(self): ax = self.figure.add_subplot(111) scatter = ax.scatter(np.random.randn(100), np.random.randn(100)) legend = DraggableLegend(ax.legend()) I emailed the Matplotlib-users group and John Hunter was kind enough to add my solution it to SVN HEAD. On Thu, Jan 28, 2010 at 3:02 PM, Adam Fraser wrote: I thought I'd share a solution to the draggable legend problem since it took me forever to assimilate all the scattered knowledge on the mailing lists... Cool -- nice example. I added the code to legend.py. Now you can do leg = ax.legend() leg.draggable() to enable draggable mode. You can repeatedly call this func to toggle the draggable state. I hope this is helpful to people working with matplotlib.

    Read the article

  • Cheetah with Cherrypy: how to load base templates, and do so automatically on change during developm

    - by Heikki Toivonen
    I am working on a cherrypy+cheetah app and would like to improve the development experience. I have everything working when I manually compile templates beforehand. However, during development I'd rather just load the templates every time they are referenced so that I don't need to kill and restart my application. I have a couple of issues I am facing: If I have templates inheriting from base templates, I get import errors (can't find base templates). I think I had this actually working during my experiments, but unfortunately didn't save it and now I can't make it work. Suppose I get 1. working, how do make it so that edits even in base templates get picked up without restart. Below is my sample application that should demonstrate the problems. The directory structure is as follows: t.py templates/ base.tmpl index.tmpl t.py: import sys import cherrypy from Cheetah.Template import Template class T: def __init__(self, foo): self.foo = foo @cherrypy.expose def index(self): return Template(file='templates/index.tmpl', searchList=[{'foo': self.foo}]).respond() cherrypy.quickstart(T(sys.argv[1])) base.tmpl: #def body This is the body from the base #end def This is the base doc index.tmpl: #from templates.base import base #extends base #def body $base.body(self) This is the extended body #end def This is from index Run it like this: python t.py Something

    Read the article

  • Class Decorators, Inheritence, super(), and maximum recursion

    - by jamstooks
    I'm trying to figure out how to use decorators on subclasses that use super(). Since my class decorator creates another subclass a decorated class seems to prevent the use of super() when it changes the className passed to super(className, self). Below is an example: def class_decorator(cls): class _DecoratedClass(cls): def __init__(self): return super(_DecoratedClass, self).__init__() return _DecoratedClass class BaseClass(object): def __init__(self): print "class: %s" % self.__class__.__name__ def print_class(self): print "class: %s" % self.__class__.__name__ bc = BaseClass().print_class() class SubClass(BaseClass): def print_class(self): super(SubClass, self).print_class() sc = SubClass().print_class() @class_decorator class SubClassAgain(BaseClass): def print_class(self): super(SubClassAgain, self).print_class() sca = SubClassAgain() # sca.print_class() # Uncomment for maximum recursion The output should be: class: BaseClass class: BaseClass class: SubClass class: SubClass class: _DecoratedClass Traceback (most recent call last): File "class_decorator_super.py", line 34, in <module> sca.print_class() File "class_decorator_super.py", line 31, in print_class super(SubClassAgain, self).print_class() ... ... RuntimeError: maximum recursion depth exceeded while calling a Python object Does anyone know of a way to not break a subclass that uses super() when using a decorator? Ideally I'd like to reuse a class from time to time and simply decorate it w/out breaking it.

    Read the article

  • Macro access to members of object where macro is defined

    - by Marc Grue
    Say I have a trait Foo that I instantiate with an initial value val foo = new Foo(6) // class Foo(i: Int) and I later call a second method that in turn calls myMacro foo.secondMethod(7) // def secondMethod(j: Int) = macro myMacro then, how can myMacro find out what my initial value of i (6) is? I didn't succeed with normal compilation reflection using c.prefix, c.eval(...) etc but instead found a 2-project solution: Project B: object CompilationB { def resultB(x: Int, y: Int) = macro resultB_impl def resultB_impl(c: Context)(x: c.Expr[Int], y: c.Expr[Int]) = c.universe.reify(x.splice * y.splice) } Project A (depends on project B): trait Foo { val i: Int // Pass through `i` to compilation B: def apply(y: Int) = CompilationB.resultB(i, y) } object CompilationA { def makeFoo(x: Int): Foo = macro makeFoo_impl def makeFoo_impl(c: Context)(x: c.Expr[Int]): c.Expr[Foo] = c.universe.reify(new Foo {val i = x.splice}) } We can create a Foo and set the i value either with normal instantiation or with a macro like makeFoo. The second approach allows us to customize a Foo at compile time in the first compilation and then in the second compilation further customize its response to input (i in this case)! In some way we get "meta-meta" capabilities (or "pataphysic"-capabilities ;-) Normally we would need to have foo in scope to introspect i (with for instance c.eval(...)). But by saving the i value inside the Foo object we can access it anytime and we could instantiate Foo anywhere: object Test extends App { import CompilationA._ // Normal instantiation val foo1 = new Foo {val i = 7} val r1 = foo1(6) // Macro instantiation val foo2 = makeFoo(7) val r2 = foo2(6) // "Curried" invocation val r3 = makeFoo(6)(7) println(s"Result 1 2 3: $r1 $r2 $r3") assert((r1, r2, r3) ==(42, 42, 42)) } My question Can I find i inside my example macros without this double compilation hackery?

    Read the article

  • IBasic Accumulator

    - by Tara
    I am trying to do an accumulator in IBasic for a college assignment and I have the general stuff down but I cannot get it to accumulate. The code is below. My question is how do I get it to accumulate and pass to the different module. I'm trying to calculate how many right answers the user gets. Also, i need to calculate the percentage of right answers. so if the user gets 9 out of 10 right theyed answer 90% right. 'October 15, 2009 ' 'Lab 7.5 Programming Challenge 1 - Average Test Scores ' 'This is a dice game ' declare main() declare inputName(name:string) declare getAnswer(num1:int, num2:int) declare getResult(num1:int, num2:int, answer:int) declare avgRight(getRight:int) declare printInfo(name:string, getRight:int, averege:float) openconsole main() do:until inkey$<>"" closeconsole end sub main() def name:string def num1, num2, answer, total, getRight:int def averege:float inputName (name) getRight = 0 For counter = 1 to 10 getRight = getAnswer(num1, num2) getRight = getRight + 1 next counter average = avgRight (getRight) printInfo(Name, getRight, average) end sub inputName (name) Input "Please enter your name: " ,name return sub getAnswer(num1, num2) def answer, getRight:int num1 = rnd (10) + 1 num2 = rnd (10) + 1 Print num1, "+ " ,num2 Input "What is the answer to the equation? " ,answer getRight = getResult(num1, num2, answer) return getRight sub getResult(num1, num2, answer) def getRight:int if answer = num1 + num2 getRight = 1 else getRight = 0 endif return getRight sub avgRight(getRight) def average:float average = getRight / 10 return average sub printInfo(name, getRight, averege) Print "The students name is: " ,name Print "The number right is: " ,getRight Print Using ("&##.#&", "The average right is " ,averege * 100, "%") return

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >