buckingham 1.0
Dimensional Analysis / Formula Validation/ Units Conversion / Error Propagation In one single small file without dependencies buckingham.py http://code.google.com/p/buckingham/ based on the Buckingham Theorem How to use download the module download Python start Python import the module: from buckingham import Number, sin, cos, exp, log, allunits, pm Example of dimensional analysis and conversions a = Number(10,dims='meter/second') b = Number(2,dims='yard/minute') c = a + b print c.convert('kilometer/hour') (36.109728 ± 0) Number(1,dims='joule').convert('eV').value 6.2415096471204178e+18 print c.value, c.error, c.units() 10.03048 0.0 meter*second^-1 Without conversion results are always in: meters, seconds, grams, ampere, kelvin, currency (and combination) The error is the standard deviation assuming the true value is Normal distributed Error propagation assumes independence a = Number(1,dims='decimeter^3') b = Number(2,dims='liter') c = Number(5,dims='gram/centimeter^3') d = (a + b)*c print d.convert('kilogram') (15.00 ± 0) Simplified syntax globals().update(allunits()) length = (4+pm(0.5)) * meter velocity = 5 * meter/second time = length/velocity print time (8.00 ± 1.00)/10 Example of formula validation a = Number(10,dims='meter/second') b = Number(2,dims='yard^3') c = a + b Traceback (most recent call last): ... RuntimeError: Incompatible Dimensions Examples of error propagation a = Number(10,error=2,dims='meter/second') # (10±2)m/s b = Number(5,error=1,dims='hour') # (5±1)h c = a*b print c.convert('kilometer') (1.800 ± 0.509)x10^2 print c.convert('lightyear') (1.903 ± 0.538)/10^11 print c.convert('kilometer').value 180.0 print c.convert('kilometer').error 50.9116882454 Examples of more complex formulas c = a**4/(7*b) print '%s %s' % (c,c.units()) (7.94 ± 6.54)/10^2 meter^4*second^-5 For pure numbers sin, cos, exp, log are also defined. You can use a.is_pure() to check if a number is pure. Financial application example coupon = Number(200,error=1,dims=dollar/day) expiration = Number(1,error=0,dims=year) payoff = coupon*expiration print payoff.convert('dollar') (7.3048 ± 0.0365)x10^4 I.e. $73048 dollars with $365 dollars of one sigma uncertainly Latex Output print payoff.as_latex() (7.3048 \pm 0.0365)\times 10^{4} Rouding Notice the output as a string always uses scientific notation and value is automatically rounded compatibly with error/uncertainty in result. Supported units and combination of ampere, angstrom, atm, attoL, attoampere, attoangstrom, attoatm, attoau, attobar, attocalorie, attocoulomb, attocurrency, attoday, attodollar, attoeV, attoev, attofarad, attofaraday, attofermi, attofoot, attogram, attohenry, attohour, attohz, attoinch, attojoule, attokelvin, attolightyear, attoliter, attometer, attomho, attomile, attominute, attommhg, attonewton, attoohm, attopascal, attopound, attopsi, attopure, attoquart, attosecond, attosiemens, attovolt, attowatt, attoweber, attoyard, attoyear, au, bar, calorie, centiL, centiampere, centiangstrom, centiatm, centiau, centibar, centicalorie, centicoulomb, centicurrency, centiday, centidollar, centieV, centiev, centifarad, centifaraday, centifermi, centifoot, centigram, centihenry, centihour, centihz, centiinch, centijoule, centikelvin, centilightyear, centiliter, centimeter, centimho, centimile, centiminute, centimmhg, centinewton, centiohm, centipascal, centipound, centipsi, centipure, centiquart, centisecond, centisiemens, centivolt, centiwatt, centiweber, centiyard, centiyear, coulomb, currency, day, deciL, deciampere, deciangstrom, deciatm, deciau, decibar, decicalorie, decicoulomb, decicurrency, deciday, decidollar, decieV, deciev, decifarad, decifaraday, decifermi, decifoot, decigram, decihenry, decihour, decihz, deciinch, decijoule, decikelvin, decilightyear, deciliter, decimeter, decimho, decimile, deciminute, decimmhg, decinewton, deciohm, decipascal, decipound, decipsi, decipure, deciquart, decisecond, decisiemens, decivolt, deciwatt, deciweber, deciyard, deciyear, dekaL, dekaampere, dekaangstrom, dekaatm, dekaau, dekabar, dekacalorie, dekacoulomb, dekacurrency, dekaday, dekadollar, dekaeV, dekaev, dekafarad, dekafaraday, dekafermi, dekafoot, dekagram, dekahenry, dekahour, dekahz, dekainch, dekajoule, dekakelvin, dekalightyear, dekaliter, dekameter, dekamho, dekamile, dekaminute, dekammhg, dekanewton, dekaohm, dekapascal, dekapound, dekapsi, dekapure, dekaquart, dekasecond, dekasiemens, dekavolt, dekawatt, dekaweber, dekayard, dekayear, dollar, eV, ev, exaL, exaampere, exaangstrom, exaatm, exaau, exabar, exacalorie, exacoulomb, exacurrency, exaday, exadollar, exaeV, exaev, exafarad, exafaraday, exafermi, exafoot, exagram, exahenry, exahour, exahz, exainch, exajoule, exakelvin, exalightyear, exaliter, exameter, examho, examile, examinute, exammhg, exanewton, exaohm, exapascal, exapound, exapsi, exapure,
Re: Fastest way to detect a non-ASCII character in a list of strings.
Dun Peal, 17.10.2010 21:59: `all_ascii(L)` is a function that accepts a list of strings L, and returns True if all of those strings contain only ASCII chars, False otherwise. What's the fastest way to implement `all_ascii(L)`? My ideas so far are: 1. Match against a regexp with a character range: `[ -~]` 2. Use s.decode('ascii') 3. `return all(31 ord(c) 127 for s in L for c in s)` Any other ideas? Which one do you think will be fastest? You can't beat Cython for this kind of task. If it's really a list of (unicode) strings, you can do this: def only_allowed_characters(list strings): cdef unicode s for s in strings: for c in s: if c 31 or c 127: return False return True Or, a bit shorter, using Cython 0.13: def only_allowed_characters(list strings): cdef unicode s return any((c 31 or c 127) for s in strings for c in s) Both are untested. Basically the same should work for byte strings. You can also support both string types efficiently with an isinstance() type test inside of the outer loop. Also see here: http://behnel.de/cgi-bin/weblog_basic/index.php?p=49 http://docs.cython.org/src/tutorial/strings.html Stefan -- http://mail.python.org/mailman/listinfo/python-list
OO and game design questions
I'm building a turn based RPG game as a hobby. The design is becoming increasingly complicated and confusing, and I think I may have tendency to over-engineer simple things. Can anybody please check my problems-solutions and point me to more elegant solution? Every item/character/room is a separate object. Items/characters need to have references to room they are in, and room needs to have a list of references to items/characters that are contained within. I decided to use weak references. That way I can destroy object by deleting it, I don't have to destroy all references as well. In each object's __init__() that object is added to game_object list, and in each __del__() they are removed from game_object list. This mechanism keeps them safe from garbage collector. How pythonic is this design? In turn-based games, the order of action execution in battle can give unfair advantage to players. For example, if player's arm is crippled before his action is executed, he would do less damage. To offset this, I first execute all players' actions and calculate effects in first pass, then apply the effects in second pass. The effect can be health decrease by 15HP, item pick-up, 30p experience gain, etc. This means the player deals the same amount of damage no matter what happens to him in that turn. The difficult part is keeping track of various effects. I had to make separate class for various types of effects (ChangeAttributeEffect, GetItemEffect, LooseItemEffect). Each class stores weak reference to target object and has apply() method that applies the effect to object. I'm not satisfied with this as it's limiting, error-prone and uses metaprogramming. Is there a design pattern that would remember changes to an object, and apply them later? Sorry for the wall of text. -- http://mail.python.org/mailman/listinfo/python-list
Print to an IPP printer (pkipplib?)
I've found the module pkipplib which seems to work well for things like interrogating an IPP (CUPS) server. But is there a way to send a print job to an IPP print queue? [and no, the local system knows nothing about the print architecture so popenlp is not an option]. I just want to send the data from a file handle to a remote IPP queue as a print job. -- http://mail.python.org/mailman/listinfo/python-list
Print to an IPP printer (pkipplib?)
I've found the module pkipplib which seems to work well for things like interrogating an IPP (CUPS) server. But is there a way to send a print job to an IPP print queue? [and no, the local system knows nothing about the print architecture so popenlp is not an option]. I just want to send the data from a file handle to a remote IPP queue as a print job. -- http://mail.python.org/mailman/listinfo/python-list
Re: Deditor -- pythonic text-editor
Kruptein wrote: on steven, peter and eliasf: Well okay I'm new to the world of developing programs, if I encounter problems I directly post a bug on the relevant page, that's maybe why I was a bit frustrated :) but what you three say is indeed true.. Hi, It does not work with python 2.5 (with statement). __future__.with_statement allow me to only get to the next error: http://launchpad.net/deditor; Looks like it's using a different version of wx than mine: In [4]: wx.__version__ Out[4]: '2.6.3.2' You should include the requirements somewhere so that people don't bother downloading it if they don't have the proper python version. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: what difference does redirection make?
Dana Sun, 17 Oct 2010 15:36:13 -0400, Benjamin Kaplan benjamin.kap...@case.edu kaze: On Sun, Oct 17, 2010 at 3:04 PM, Nikola Skoric n...@fly.srk.fer.hr wrote: You're trying to write Unicode to a file. But there's no such thing as /snip .encode(cp1252) or whatever encoding you want to use to the end of the mytemplate.render_unicode(...) call on the last line. Thank you, thank you, thank you! I got it now... -- Now the storm has passed over me I'm left to drift on a dead calm sea And watch her forever through the cracks in the beams Nailed across the doorways of the bedrooms of my dreams -- http://mail.python.org/mailman/listinfo/python-list
Re: OO and game design questions
On Oct 18, 12:28 am, dex josipmisko...@gmail.com wrote: Every item/character/room is a separate object. Items/characters need to have references to room they are in, and room needs to have a list of references to items/characters that are contained within. I decided to use weak references. That way I can destroy object by deleting it, I don't have to destroy all references as well. You're aware Python can collect reference cycles, correct? You don't have to delete references; Python will get them eventually. If you feel you're overengineering things perhaps getting rid of weak references would be a substantial simplification. In each object's __init__() that object is added to game_object list, and in each __del__() they are removed from game_object list. This mechanism keeps them safe from garbage collector. How pythonic is this design? I would say overriding __del__ is not particularly Pythonic at all. Using __del__ has some undesirable side-effects (like potential for memory leaks), and is unreliable (there are different reasons it might not be called at all). I recommend that only experts deeply familiar with these issues override it, and then only for objects whose sole purpose is to own a resource. It's tricky to get right. Instead, I'd recommend managing the lifetime of all objects (creating and destroying) through game_object methods. To create an object, don't call its constructor, call obj = game_object.create(object_type,args) and game_object.destroy(obj). (If you really want to be strict about it, you can override __init__ to raise an exception (thus disabling the normal way to create an object), and create the objects in you create method by calling the class's __new__ method directly.) More generally, Python's dynamicism makes it hard for the language to manage resources other than RAM automatically; this is something we give up to get dynamicism's benefits. Therefore, the Pythonic approach is to manage resources with constructs like with and try...finally, although sometimes that's not possible so you have to just release the resource by hand. In your case, it'd be hard to manage the resource, i.e., an entry in youg game_object list, with try...finally because presumably the object lives for an indefinite abount of time. One thing I do in my games--you may or may not find this helpful--is to distinguish between lightweight and heavyweight objects. Lightweight objects do not need any sort of finalization and I use them whenever possible. Heavyweight objects not only need to be finalized but it must be explicit. I have a base class for heavyweights (written in C) that checks if the finalization occurred as a debugging aid, but it can't clean up automatically for various reasons. In turn-based games, the order of action execution in battle can give unfair advantage to players. For example, if player's arm is crippled before his action is executed, he would do less damage. To offset this, I first execute all players' actions and calculate effects in first pass, then apply the effects in second pass. The effect can be health decrease by 15HP, item pick-up, 30p experience gain, etc. This means the player deals the same amount of damage no matter what happens to him in that turn. The difficult part is keeping track of various effects. I had to make separate class for various types of effects (ChangeAttributeEffect, GetItemEffect, LooseItemEffect). Each class stores weak reference to target object and has apply() method that applies the effect to object. I'm not satisfied with this as it's limiting, error-prone and uses metaprogramming. Is there a design pattern that would remember changes to an object, and apply them later? Your objects should have two sets of attributes (beginning of round, end of round) and a method to copy the end-of-round attributes to the beginning-of-round area at the end of the round. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: stats 0.1a calculator statistics for Python
Steven D'Aprano wrote: I am pleased to announce the first public release of stats for Python. http://pypi.python.org/pypi/stats stats is a pure-Python module providing basic statistics functions similar to those found on scientific calculators. It currently includes: Univariate statistics including: * arithmetic, harmonic, geometric and quadratic means * median, mode * standard deviation and variance (sample and population) Multivariate statistics including: * Pearson's correlation coefficient * covariance (sample and population) * linear regression and others. This is an unstable alpha release of the software. Feedback and contributions are welcome. I already have a stats module: /usr/lib/python2.5/site-packages/stats.py stats.py module (Requires pstat.py module.) # ### Written by: Gary Strangman ### ### Last modified: May 10, 2002 ### # A collection of basic statistical functions for python. The function names appear below. [snip] It looks like it is part of the standard debian python distro (python 2.5). That would mean that 'sats' is already used. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: OO and game design questions
dex wrote: In each object's __init__() that object is added to game_object list, and in each __del__() they are removed from game_object list. This mechanism keeps them safe from garbage collector. How pythonic is this design? You don't have to manage memory with python, I don't know if you wrote C++ in the past (looks like) but consider that python is taking care of everything and you'll be fine. So do not override __del__ (anyway it is not called as you may expect it). Keep a game_object list only if you need the game to know wich objects are in the game, not to keep references. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: stats 0.1a calculator statistics for Python
On Sun, 2010-10-17 at 17:10 +, Steven D'Aprano wrote: I am pleased to announce the first public release of stats for Python. http://pypi.python.org/pypi/stats Quick comment on your sum() function: http://docs.python.org/library/math.html#math.fsum (in 2.6 and above) should do the same thing, but faster. It looks like a useful module though. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading Outlook .msg file using Python
On 17/10/2010 20:25, John Henry wrote: Not knowing anything about MAPI, I tried a number of the MAPI flags, the only one that works appears to be PR_SUBJECT. PR_CLIENT_SUBMIT_TIME, PR_CREATION_TIME and so forth doesn't work. I'll try to fish out some of the code we use, but for most of the fields, having got the body, I simply used the email module to parse it. (Obviously that doesn't give you anything which isn't included in the MIME version of the email). I have a lightweight wrapper that does some of the MAPI spadework. If you're interested, let me know and I can send it across or post it somewhere. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Spreadsheet-style dependency tracking
On Oct 17, 12:35 pm, Florian Weimer f...@deneb.enyo.de wrote: * Chris Torek: In article 87y69xbz6h@mid.deneb.enyo.de Florian Weimer f...@deneb.enyo.de wrote: Are there libraries which implement some form of spreadsheet-style dependency tracking? The idea is to enable incremental updates to some fairly convoluted computation. I hope that a general dependency tracking framework would avoid making the computation even more convoluted and difficult to change. Don't know of any libraries myself, but I wrote some code to do topological sort for dependencies, which I can paste here. It is also worth noting that a lot of spreadsheets cheat: they just repeat a sheet-wide computation until values stop changing (or a cycle count limit runs out). I think most of the relevant implementations use dependency information to speed up incremental recomputation. For instance, gnumeric seems to have code for this. This is the part I'm most interested in. I already have got an explicit ordering of the computations (fortunately, that part is fairly simple). And note that the repeating sheet-wide computation is a feature not a cheat (the default should still be to report cycles). Allowing calculations to complete even in the presence of cycles can be very useful. Michael Foord -- http://www.voidspace.org.uk/ -- http://mail.python.org/mailman/listinfo/python-list
error in loading data into the code
hello , I have started python last week,so maybe my question is a bit stupid. I got this error in my simple python code while trying to load data into the code. I have added this libaraies from pylab import * from scipy import * import matplotlib.mlab as mlab from numpy import * from scipy import optimize but get this following error : /usr/lib/pymodules/python2.6/matplotlib/mlab.py:1267: DeprecationWarning: use numpy.loadtxt warnings.warn(use numpy.loadtxt, DeprecationWarning) # 2009/06/13 any idea ? thanks,Nakisa -- http://mail.python.org/mailman/listinfo/python-list
Classes in a class: how to access variables from one in another
Hello. I have a class A that contains two classes B and C: class A: class B: self.x = 2 class C: Is there a way to access the x defined in B in class C? Thanks. -- F. Delente -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On 2010-10-18, f...@slick.airforce-one.org f...@slick.airforce-one.org wrote: Hello. I have a class A that contains two classes B and C: class A: class B: self.x = 2 class C: Is there a way to access the x defined in B in class C? That's not valid Python code. Do you mean: Class A: Class B: x = 2 or Class A: Class B: def __init__(self): self.x = 2 -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On 2010-10-18, Neil Cerutti ne...@norwich.edu wrote: On 2010-10-18, f...@slick.airforce-one.org f...@slick.airforce-one.org wrote: Hello. I have a class A that contains two classes B and C: class A: class B: self.x = 2 class C: Is there a way to access the x defined in B in class C? That's not valid Python code. Do you mean: Class A: Class B: x = 2 or Class A: Class B: def __init__(self): self.x = 2 Oops! Python has no Class. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
Neil Cerutti ne...@norwich.edu wrote: I have a class A that contains two classes B and C: class A: class B: self.x = 2 class C: I only wanted to show the structure of the code, not the actual instructions. That's not valid Python code. Do you mean: Class A: Class B: x = 2 Class A: Class B: def __init__(self): self.x = 2 Any of these, aslong as I can access x in C. By the way, is the first proposition (that is, x = 2, without the self.) valid? Is x a global variable then? Thanks. -- F. Delente -- http://mail.python.org/mailman/listinfo/python-list
Re: OO and game design questions
You're aware Python can collect reference cycles, correct? You don't have to delete references; Python will get them eventually. I'm not sure I understand this part? If I don't delete all strong references, the object will not be deleted. It will persist and occupy memory as long as there's at least one reference to it (it could be part of inventory, or target of some action). Instead, I'd recommend managing the lifetime of all objects (creating and destroying) through game_object methods. To create an object, don't call its constructor, call obj = game_object.create(object_type,args) and game_object.destroy(obj). (If you really want to be strict about it, you can override __init__ to raise an exception (thus disabling the normal way to create an object), and create the objects in you create method by calling the class's __new__ method directly.) This makes sense, I will make these modifications. Your objects should have two sets of attributes (beginning of round, end of round) and a method to copy the end-of-round attributes to the beginning-of-round area at the end of the round. Perhaps I could utilize properties. Make getters return start-of-round attributes and setters set end-of-round attributes. Things would get a bit messy if two or more players modify the same attribute or chest content. I need to think about this some more. Thanks for your thoughts. -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On 10/18/2010 06:45 AM, f...@slick.airforce-one.org wrote: Neil Ceruttine...@norwich.edu wrote: I have a class A that contains two classes B and C: class A: class B: self.x = 2 class C: I only wanted to show the structure of the code, not the actual instructions. That's not valid Python code. Do you mean: Class A: Class B: x = 2 Class A: Class B: def __init__(self): self.x = 2 Any of these, aslong as I can access x in C. By the way, is the first proposition (that is, x = 2, without the self.) valid? Is x a global variable then? Thanks. Well, your code still doesn't make sense, but the generic answers are: This defines a class variable: class A: x=123 and access to the variable is A.x This defines an instance variable: class A: def __init__(self): self.x = 123 and once you have an object of class A, a = A() access is a.x from outside the class, and self.x from inside the class. (Those are really the same, the instance is named 'a' in one case and 'self' in the other.) If *any* object, class or instance of a class (or module or whatever) contains another, access is by chaining the dots. OuterOb.InnerOb.attribute Hope that answers your question. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: Fastest way to detect a non-ASCII character in a list of strings.
On 2010-10-18, Steven D'Aprano steve-remove-t...@cybersource.com.au wrote: Neither is accurate. all_ascii would be: all(ord(c) = 127 for c in string for string in L) Definitely. all_printable would be considerably harder. As far as I can tell, there's no simple way to tell if a character is printable. There's no easy way to even define what printable means. Ask three different people, and you'll get at least four different answers answers. -- Grant Edwards grant.b.edwardsYow! If elected, Zippy at pledges to each and every gmail.comAmerican a 55-year-old houseboy ... -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
Gary Herron gher...@islandtraining.com wrote: Well, your code still doesn't make sense, but the generic answers are: I'll clarify what I need then: I'm drawing Bézier curves. I draw them on a zone that is defined as a subclass of GtkDrawingArea. In a zone, I define a system of coordinates by 4 values: xmin, xmax, ymin, and ymax that define the viewing port. A curve is defined in this system of coordinates by a collection of points. So my way of coding it is the following: class zone(GtkDrawingArea): class systemOfCoordinates: self.xmin = -5 self.xmax = 5 self.ymin = -5 self.ymax = 5 class Curve: self.listOfPoints = () def draw(self): pass # for each point in self.listOfPoints: draw this point # then draw the Bézier curve passing through these points class Point: def __init__(self, x, y): (self.x, self.y) = (x, y) def draw(self): # ... code for drawing a dot in the system of coordinates... def __init__(self): # for the zone object self.coord = self.systemOfCoordinates() self.listOfCurves = ( self.Curve() ) def expose(self, widget, event): pass # for each curve of self.listOfCurves: draw it Now to actually draw the dot on the screen, I need to access coord.xmin, coord.xmax, coord.ymin and coord.ymax to Point.draw(). I could do this by passing a reference to Point.draw(), but I'd like to do this implicitely. I guess that in that case, xmin, xmax, ymin and ymax should be class variables of zone, right? If *any* object, class or instance of a class (or module or whatever) contains another, access is by chaining the dots. OuterOb.InnerOb.attribute Hope that answers your question. This should help, I'll make some tests. Thanks. -- F. Delente -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
f...@slick.airforce-one.org wrote: Neil Cerutti ne...@norwich.edu wrote: I have a class A that contains two classes B and C: class A: class B: self.x = 2 class C: I only wanted to show the structure of the code, not the actual instructions. Always post working code, or at least something we can paste in the python interpreter (even if it's buggy) class A: class B: x=2 class C: def __init__(self): print A.B.x c = A.C() 2 JM -- http://mail.python.org/mailman/listinfo/python-list
Re: OO and game design questions
On Mon, Oct 18, 2010 at 9:50 AM, dex josipmisko...@gmail.com wrote: You're aware Python can collect reference cycles, correct? You don't have to delete references; Python will get them eventually. I'm not sure I understand this part? If I don't delete all strong references, the object will not be deleted. It will persist and occupy memory as long as there's at least one reference to it (it could be part of inventory, or target of some action). No it won't. Python has a garbage collector. The object will persist as long as it is reachable through code. If it becomes unreachable, the garbage collector will delete it even if there is a reference cycle. -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
Jean-Michel Pichavant jeanmic...@sequans.com wrote: Always post working code, or at least something we can paste in the python interpreter (even if it's buggy) Ok, noted. class A: class B: x=2 class C: def __init__(self): print A.B.x c = A.C() 2 Good, thanks. I've made further tests and here is what I have come to: class zoneDeDessin(gtk.DrawingArea): xmin = -5.5 xmax = 5.5 ymin = -5.5 ymax = 5.5 class Handle: def __init__(self, xEcran, yEcran): (self.xEcran, self.yEcran) = (xEcran, yEcran) (self.xRepere, self.yRepere) = (zoneDeDessin.XdeLEcranAuRepere(xEcran), zoneDeDessin.YdeLEcranAuRepere(yEcran)) def __init__(self): gtk.DrawingArea.__init__(self) (self.largeur, self.hauteur) = (0,0) def expose(self, widget, event): rect = self.get_allocation() (self.largeur, self.hauteur) = (rect.width, rect.height) def XdeLEcranAuRepere(self, x): return zoneDeDessin.xmin+x*(zoneDeDessin.xmax-zoneDeDessin.xmin)/float(self.largeur) def YdeLEcranAuRepere(self, y): return zoneDeDessin.ymax+y*(zoneDeDessin.ymin-zoneDeDessin.ymax)/float(self.hauteur) I have further code that should add a Handle when I double-click on the screen. However I get this error when executing: Traceback (most recent call last): File ./zoneDeDessin.py, line 161, in boutonRelache zoneDeDessin.Courbe.ajouterUnHandle(self.courbeCourante, event.x, event.y) File ./zoneDeDessin.py, line 36, in ajouterUnHandle self.listeDesPoints.append(zoneDeDessin.Handle(xEcran, yEcran)) File ./zoneDeDessin.py, line 22, in __init__ (self.xRepere, self.yRepere) = (zoneDeDessin.XdeLEcranAuRepere(xEcran), zoneDeDessin.YdeLEcranAuRepere(yEcran)) TypeError: unbound method XdeLEcranAuRepere() must be called with zoneDeDessin instance as first argument (got float instance instead) I understand the error (XdeLEcranAuRepere is an instance method, not a class method), but I don't see how to fix it, except by making largeur and hauteur class variables... Any hint? Thanks! -- F. Delente -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, 18 Oct 2010 14:35:58 +, fab wrote: So my way of coding it is the following: class zone(GtkDrawingArea): class systemOfCoordinates: self.xmin = -5 self.xmax = 5 self.ymin = -5 self.ymax = 5 self isn't meaningful within a class definition. It's far from clear what the intent of your code is. It's not even clear whether you understand the difference between a class and an object. class Curve: self.listOfPoints = () self isn't meaningful within a class definition. def draw(self): pass # for each point in self.listOfPoints: draw this point # then draw the Bézier curve passing through these points In light of this, I'add assume that the above: class Curve: self.listOfPoints = () should have been: class Curve: def __init__(self): self.listOfPoints = () This will give each *instance* of Curve a member named listOfPoints. def __init__(self): # for the zone object self.coord = self.systemOfCoordinates() self.listOfCurves = ( self.Curve() ) I suspect that you should use a list [...] rather than a tuple (...) here. The main difference is that you can modify a list, but you can't modify a tuple. Now to actually draw the dot on the screen, I need to access coord.xmin, coord.xmax, coord.ymin and coord.ymax to Point.draw(). I could do this by passing a reference to Point.draw(), but I'd like to do this implicitely. I guess that in that case, xmin, xmax, ymin and ymax should be class variables of zone, right? Not if you want to have more than one instance of zone. Class variables are effectively global, i.e. you only have one set of variables regardless of how many instances of the class you create. Putting them into a class simply avoids polluting the module's top-level namespace. If you don't want to pass the systemOfCoordinates to Point.draw, pass it to Point.__init__. Or pass a reference to the zone to either of these. If you're assuming that instances of a nested class get an implicit reference to some instance of the outer class, you're mistaken. Nested classes are simply a scoping feature, i.e. the name of the inner class is added to the outer class' dictionary, not to the module's dictionary. Other than that, the situation is no different than if the inner class had been declared at the top level. If you want objects to have a reference to some parent entity, you have to explicitly pass the reference to the constructor and store it as an instance member. -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
Am 18.10.2010 16:35, schrieb f...@slick.airforce-one.org: So my way of coding it is the following: class zone(GtkDrawingArea): class systemOfCoordinates: self.xmin = -5 self.xmax = 5 self.ymin = -5 self.ymax = 5 class Curve: self.listOfPoints = () def draw(self): pass # for each point in self.listOfPoints: draw this point # then draw the Bézier curve passing through these points class Point: def __init__(self, x, y): (self.x, self.y) = (x, y) def draw(self): # ... code for drawing a dot in the system of coordinates... def __init__(self): # for the zone object self.coord = self.systemOfCoordinates() self.listOfCurves = ( self.Curve() ) def expose(self, widget, event): pass # for each curve of self.listOfCurves: draw it Don't nest classes. Just don't. This might be a valid and good approach in some programming languages but it's not Pythonic. Your code can easily be implemented without nested classes. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
Christian Heimes li...@cheimes.de wrote: Don't nest classes. Just don't. This might be a valid and good approach in some programming languages but it's not Pythonic. Your code can easily be implemented without nested classes. I think you're right. It would have been more aesthetically pleasant to me (a Handle has only sense on a drawing zone), but if it's more complicated I'll avoid nested classes. -- F. Delente -- http://mail.python.org/mailman/listinfo/python-list
How to get key values when iterating a mailbox?
I'm trying to delete some messages from a mailbox when they are older than a certain number of days. If I iterate through the mailbox and find a message that needs deleting how do I get its key so I can do remove(key)? The trouble is that, as the documentation says: The default Mailbox iterator iterates over message representations, not keys as the default dictionary iterator does. So if you try something like:- for f in os.listdir(junkdir): mbxPath = os.path.join(junkdir, f) mbx = mailbox.mbox(mbxPath, factory=None) mbx.lock() for k, msg in mbx: if something is true msg.remove(k) mbx.flush() mbx.unlock() Then you get an exception on for k, msg in mbx which is an attribute error, presumably because a mailbox isn't a 'real' iterator. So how, do I get that key value? -- Chris Green -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, 18 Oct 2010 17:17:52 +0200 Christian Heimes li...@cheimes.de wrote: [snip] Don't nest classes. Just don't. This might be a valid and good approach in some programming languages but it's not Pythonic. Explain! /W -- To reach me via email, replace INVALID with the country code of my home country. But if you spam me, I'll be one sour Kraut. -- http://mail.python.org/mailman/listinfo/python-list
Re: Fastest way to detect a non-ASCII character in a list of strings.
On 10/18/10 09:28, Grant Edwards wrote: There's no easy way to even define what printable means. Ask three different people, and you'll get at least four different answers answers. I don't have a printer...that makes *all* characters unprintable, right? Now I can convert the algorithm to O(1) def is_printable(L): return False -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: error in loading data into the code
nakisa nakisa.noor...@gmail.com writes: hello , I have started python last week,so maybe my question is a bit stupid. I got this error in my simple python code while trying to load data into the code. I have added this libaraies from pylab import * from scipy import * import matplotlib.mlab as mlab from numpy import * from scipy import optimize but get this following error : /usr/lib/pymodules/python2.6/matplotlib/mlab.py:1267: DeprecationWarning: use numpy.loadtxt warnings.warn(use numpy.loadtxt, DeprecationWarning) # 2009/06/13 any idea ? You don't get an error. You get a warning. Crucial difference there. You can ignore it. You can even suppress it. But you shouldn't bother, the authors of mlab should. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: error in loading data into the code
On Oct 18, 5:02 pm, de...@web.de (Diez B. Roggisch) wrote: nakisa nakisa.noor...@gmail.com writes: hello , I have started python last week,so maybe my question is a bit stupid. I got this error in my simple python code while trying to load data into the code. I have added this libaraies from pylab import * from scipy import * import matplotlib.mlab as mlab from numpy import * from scipy import optimize thanks Diez :) but get this following error : /usr/lib/pymodules/python2.6/matplotlib/mlab.py:1267: DeprecationWarning: use numpy.loadtxt warnings.warn(use numpy.loadtxt, DeprecationWarning) # 2009/06/13 any idea ? You don't get an error. You get a warning. Crucial difference there. You can ignore it. You can even suppress it. But you shouldn't bother, the authors of mlab should. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
f...@slick.airforce-one.org wrote: Christian Heimes li...@cheimes.de wrote: Don't nest classes. Just don't. This might be a valid and good approach in some programming languages but it's not Pythonic. Your code can easily be implemented without nested classes. I think you're right. It would have been more aesthetically pleasant to me (a Handle has only sense on a drawing zone), but if it's more complicated I'll avoid nested classes. I would disagree to the point. Nested classes are perfectly fine, class can but used as class and/or namespaces. However Nested classes are rarely absolutely required so if you decide not to use them, that's not a big deal. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, Oct 18, 2010 at 8:58 AM, Andreas Waldenburger use...@geekmail.invalid wrote: On Mon, 18 Oct 2010 17:17:52 +0200 Christian Heimes li...@cheimes.de wrote: [snip] Don't nest classes. Just don't. This might be a valid and good approach in some programming languages but it's not Pythonic. Explain! Private classes that are closely related to another class can be simply be defined at the module level with an appropriate name indicating the privacy (e.g. _Private vs. Public) rather than inside their associated class; this saves on indentation and is thus more pleasant to read. Also, Python's scoping rules, particularly for class-level scopes, don't work the way programmers from languages where nested classes are common would expect: class Foo(object): SHARED_CONSTANT = 42 class FooBar(object): def baz(self): return SHARED_CONSTANT Foo.FooBar().baz() == Traceback (most recent call last): File stdin, line 1, in module File stdin, line 5, in baz NameError: global name 'SHARED_CONSTANT' is not defined Since you must use Foo.SHARED_CONSTANT and similar anyway when you're in FooBar, nesting FooBar within Foo doesn't really confer any advantages in the conciseness department. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to get key values when iterating a mailbox?
On Mon, Oct 18, 2010 at 8:42 AM, tinn...@isbd.co.uk wrote: I'm trying to delete some messages from a mailbox when they are older than a certain number of days. If I iterate through the mailbox and find a message that needs deleting how do I get its key so I can do remove(key)? The trouble is that, as the documentation says: The default Mailbox iterator iterates over message representations, not keys as the default dictionary iterator does. So if you try something like:- for f in os.listdir(junkdir): mbxPath = os.path.join(junkdir, f) mbx = mailbox.mbox(mbxPath, factory=None) mbx.lock() for k, msg in mbx: if something is true msg.remove(k) mbx.flush() mbx.unlock() Then you get an exception on for k, msg in mbx which is an attribute error, presumably because a mailbox isn't a 'real' iterator. No, it's probably because iterating over a Mailbox yields Message-s rather than (key, Message) pairs; Python thus tries to unpack each Message into a (k, msg) pair (since that's how you wrote your for-loop), but this fails since (I would assume) Messages aren't iterable. So how, do I get that key value? If you want to iterate over key-value pairs (aka items), then ask Mailbox for items in the first place: for k, msg in mbx.iteritems(): # rest of code Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
f...@slick.airforce-one.org wrote: Jean-Michel Pichavant jeanmic...@sequans.com wrote: Always post working code, or at least something we can paste in the python interpreter (even if it's buggy) Ok, noted. class A: class B: x=2 class C: def __init__(self): print A.B.x c = A.C() 2 Good, thanks. I've made further tests and here is what I have come to: class zoneDeDessin(gtk.DrawingArea): xmin = -5.5 xmax = 5.5 ymin = -5.5 ymax = 5.5 class Handle: def __init__(self, xEcran, yEcran): (self.xEcran, self.yEcran) = (xEcran, yEcran) (self.xRepere, self.yRepere) = (zoneDeDessin.XdeLEcranAuRepere(xEcran), zoneDeDessin.YdeLEcranAuRepere(yEcran)) def __init__(self): gtk.DrawingArea.__init__(self) (self.largeur, self.hauteur) = (0,0) def expose(self, widget, event): rect = self.get_allocation() (self.largeur, self.hauteur) = (rect.width, rect.height) def XdeLEcranAuRepere(self, x): return zoneDeDessin.xmin+x*(zoneDeDessin.xmax-zoneDeDessin.xmin)/float(self.largeur) def YdeLEcranAuRepere(self, y): return zoneDeDessin.ymax+y*(zoneDeDessin.ymin-zoneDeDessin.ymax)/float(self.hauteur) I have further code that should add a Handle when I double-click on the screen. However I get this error when executing: Traceback (most recent call last): File ./zoneDeDessin.py, line 161, in boutonRelache zoneDeDessin.Courbe.ajouterUnHandle(self.courbeCourante, event.x, event.y) File ./zoneDeDessin.py, line 36, in ajouterUnHandle self.listeDesPoints.append(zoneDeDessin.Handle(xEcran, yEcran)) File ./zoneDeDessin.py, line 22, in __init__ (self.xRepere, self.yRepere) = (zoneDeDessin.XdeLEcranAuRepere(xEcran), zoneDeDessin.YdeLEcranAuRepere(yEcran)) TypeError: unbound method XdeLEcranAuRepere() must be called with zoneDeDessin instance as first argument (got float instance instead) I understand the error (XdeLEcranAuRepere is an instance method, not a class method), but I don't see how to fix it, except by making largeur and hauteur class variables... Any hint? Thanks! Quite simple in fact, XdeLEcranAuRepere is an instance method (any method with self as 1st parameter is an instance method). However you called it as a class method: zoneDeDessin.XdeLEcranAuRepere(xEcran) Just change that code to self.XdeLEcranAuRepere(xEcran). 'self' allows you to access attributes and methods of an instance. Also don't code in french, you use meaningful names which is good, but they're meaninful only to french speaking people. That will reduce the help you can't get in this international list for instance. Another detail, my guess is that xmin = -5.5 xmax = 5.5 ymin = -5.5 ymax = 5.5 should be instance attributes not class attributes (you don't want 2 instances of zoneDeDessin sharing the same xmin value). A classic pattern for default values is: class DrawArea: DFT_XMIN = -5.5 DFT_XMAX = 5.5 DFT_YMIN = -5.5 DFT_YMAX = 5.5 def __init__(self, xmin=None, xmax=None, ymin=None, ymax=None): self.xmin=xmin self.xmax=xmax self.ymin=ymin self.ymax=ymax for attribute in ['xmin', 'xmax', 'ymin', 'ymax']: if getattr(self, attribute) is None: # then let's assign the default value setattr(self, attribute, getattr(self, 'DFT_' + attribute.upper())) # there's a little bit of magic here, it could be improved but this is not the purpose here d1=DrawArea() print 'd1 ', d1.__dict__ d2=DrawArea(xmax=8) print 'd2 ', d2.__dict__ execution output: d1 {'xmin': -5.5, 'ymin': -5.5, 'ymax': 5.5, 'xmax': 5.5} d2 {'xmin': -5.5, 'ymin': -5.5, 'ymax': 5.5, 'xmax': 8} JM PS : to those how would wonder why not include self.xmin=xmin into the 'for attribute' loop, it's just to not mess with most linter(including pylint), and for attributes, it's always a good think to 'declare' them explicitly in the __init__ method. -- http://mail.python.org/mailman/listinfo/python-list
Re: error in loading data into the code
Diez B. Roggisch wrote: nakisa nakisa.noor...@gmail.com writes: hello , I have started python last week,so maybe my question is a bit stupid. I got this error in my simple python code while trying to load data into the code. I have added this libaraies from pylab import * from scipy import * import matplotlib.mlab as mlab This is idiomatically written as from matplotlib import mlab from numpy import * from scipy import optimize When you (nakisa) use *-imports on large beasts like pylab and scipy you are likely to encounter name clashes. The behaviour of your program becomes dependent on the order of imports, and for every name in pylab that you want to use you have to verify that there isn't an object of the same name in scipy or numpy. I'd say this is more hassle than the few characters you save are worth. but get this following error : /usr/lib/pymodules/python2.6/matplotlib/mlab.py:1267: DeprecationWarning: use numpy.loadtxt warnings.warn(use numpy.loadtxt, DeprecationWarning) # 2009/06/13 any idea ? You don't get an error. You get a warning. Crucial difference there. You can ignore it. You can even suppress it. But you shouldn't bother, the authors of mlab should. ... unless you are invoking matplotlib.mlab.load() in the code you wrote yourself. In this case follow the advice in the warning and replace it with numpy.loadtxt(). Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Fastest way to detect a non-ASCII character in a list of strings.
Printable in the screen, all of them are, except for blank spaces ehhehehe 2010/10/18, Tim Chase python.l...@tim.thechases.com: On 10/18/10 09:28, Grant Edwards wrote: There's no easy way to even define what printable means. Ask three different people, and you'll get at least four different answers answers. I don't have a printer...that makes *all* characters unprintable, right? Now I can convert the algorithm to O(1) def is_printable(L): return False -tkc -- http://mail.python.org/mailman/listinfo/python-list -- Felipe Bastos Nunes -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading Outlook .msg file using Python
On Oct 18, 4:09 am, Tim Golden m...@timgolden.me.uk wrote: On 17/10/2010 20:25, John Henry wrote: Not knowing anything about MAPI, I tried a number of the MAPI flags, the only one that works appears to be PR_SUBJECT. PR_CLIENT_SUBMIT_TIME, PR_CREATION_TIME and so forth doesn't work. I'll try to fish out some of the code we use, but for most of the fields, having got the body, I simply used the email module to parse it. (Obviously that doesn't give you anything which isn't included in the MIME version of the email). I have a lightweight wrapper that does some of the MAPI spadework. If you're interested, let me know and I can send it across or post it somewhere. TJG In case you didn't receive my message sent via reply to author, please sent wrapper to e c s 1 7 4 9 (at) gmail (dot) com. Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On 10/18/2010 8:17 AM, Christian Heimes wrote: Am 18.10.2010 16:35, schrieb f...@slick.airforce-one.org: So my way of coding it is the following: class zone(GtkDrawingArea): class systemOfCoordinates: self.xmin = -5 self.xmax = 5 self.ymin = -5 self.ymax = 5 class Curve: self.listOfPoints = () def draw(self): pass No, that's not the way to do it. You're not clear on the difference between a class and an object instance. Data is normally stored in object instances, not classes themselves. (You can store data in a class itself, but that's just creates a single global variable. That's rarely done.) Something like this is more usual: class SystemOfCoordinates(object) : def __init__(self, xmin, xmax, ymin, ymax) : self.xmin = xmin self.xmax = xmax self.ymin = ymin self.ymax = ymax class Curve(object) : ... class Zone(GtkDrawingArea) : def __init__(self, xmin, xmax, ymin, ymax) self.coords = SystemOfCoordinates(xmin, xmax, ymin, ymax) myzone = Zone(0,200,0,200) # make a Zone ... myzone.Curve() ... myzone.draw() When you call Zone like that, an empty Zone object is created and the __init__ function of Zone is called to fill it. That function in turn calls SystemOfCoordinates, which calls the __init__ function of SystemOfCoordinates, which returns a SystemOfCoordinates object. That's stored in self.coords, a data attribute of the Zone object. You get back a filled-in Zone object, which you can then use. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
tkMessageBox
When I do import tkMessageBox the Python Shell tells me that this does not exist. Where do I find it? You may reply to my academic email: rdrie...@nps.edu -- http://mail.python.org/mailman/listinfo/python-list
Re: tkMessageBox
On Mon, Oct 18, 2010 at 11:32 AM, richard catbird.isl...@gmail.com wrote: When I do import tkMessageBox the Python Shell tells me that this does not exist. Where do I find it? What OS are you using? How did you install Python? Can you `import Tkinter`? Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: OO and game design questions
On Oct 18, 6:50 am, dex josipmisko...@gmail.com wrote: You're aware Python can collect reference cycles, correct? You don't have to delete references; Python will get them eventually. I'm not sure I understand this part? If I don't delete all strong references, the object will not be deleted. It will persist and occupy memory as long as there's at least one reference to it (it could be part of inventory, or target of some action). I was assuming the weak referencing was used to avoid reference cycling. I'm not sure if it's a good idea to let an item disappear from your inventory by a weak reference disappearing. It seems a little shaky to not know where your objects are being referenced, but that's yout decision. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Simple logging example doesn't work!
Here is an example straight out of the help, and for some reason, it is not working. I get the error messages in the log, but I do not get the info messages in the console. import datetime, logging def main(): timestamp = datetime.datetime.now().strftime(%Y%m%d-%I%M%S) #set up logging logfile = os.path.join('db_backup_' + timestamp + '.log') logging.basicConfig(filename=logfile, level=logging.WARN, format=%(asctime)s - %(levelname)s - % (message)s, datefmt=%H:%M:%S) # define a Handler which writes INFO messages or higher to the sys.stderr console = logging.StreamHandler() console.setLevel(logging.INFO) # set a format which is simpler for console use formatter = logging.Formatter('%(name)-12s: %(levelname)-8s % (message)s') # tell the handler to use this format console.setFormatter(formatter) # add the handler to the root logger logging.getLogger('').addHandler(console) conlog = logging.getLogger('console') #logging is now configured conlog.info('In Main') logging.error('An error occured.') -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: stats 0.1a calculator statistics for Python
2010/10/17 Steven D'Aprano st...@remove-this-cybersource.com.au: I am pleased to announce the first public release of stats for Python. http://pypi.python.org/pypi/stats stats is a pure-Python module providing basic statistics functions similar to those found on scientific calculators. It currently includes: Univariate statistics including: * arithmetic, harmonic, geometric and quadratic means * median, mode * standard deviation and variance (sample and population) Multivariate statistics including: * Pearson's correlation coefficient * covariance (sample and population) * linear regression and others. This is an unstable alpha release of the software. Feedback and contributions are welcome. -- Steven D'Aprano -- http://mail.python.org/mailman/listinfo/python-list Thanks for this useful module! I just wanted to report a marginal error triggered in the doctests: Failed example: isnan(float('nan')) Exception raised: Traceback (most recent call last): File C:\Python25\lib\doctest.py, line 1228, in __run compileflags, 1) in test.globs File doctest __main__.isnan[0], line 1, in module isnan(float('nan')) ValueError: invalid literal for float(): nan (python 2.5.4 on win XP; this might be OS specific; probably in the newer versions float() was updated, the tests on 2.6 and 2.7 are ok ): I too would be interested in a comparison with the older module with the same name: http://www.nmr.mgh.harvard.edu/Neural_Systems_Group/gary/python.html which is likely to be the same as the above mentioned one. vbr -- http://mail.python.org/mailman/listinfo/python-list
Help with paths
Hello, I am using os.path to get the absolute paths of a few directories that some python files are in. FIlePath = os.path.dirname(os.path.realpath(__file__)) which returns a path similar to /home/devinm/project/files Now I want to get the directory above this one. (/home/devinm/ project/) Is there a simple way to do this? I was considering spliting apart the path and then reconstructing it with the last folder left off. Hope theres a better way to do this. Regards, Devin M -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple logging example doesn't work!
On Mon, 18 Oct 2010 11:52:36 -0700, robinsieb...@gmail.com wrote: Here is an example straight out of the help, and for some reason, it is not working. I get the error messages in the log, but I do not get the info messages in the console. Hello, I don't see this code in the help; nevertheless, your code will work if you set the logging level in the logging.basicConfig() call to logging.INFO or lower. I suggest that you start by trying to output to just one handler, and play around with that before trying to configure multiple handlers. Sorry not to be more helpful, but it's late here. Cheers (apologetically), Kev -- http://mail.python.org/mailman/listinfo/python-list
pyqt4 Table Widget deleting c/c++ object
I have two issues dealing with the table widget, though they may be interconnected. I'm not sure. Both delete the cell widgets off of my table but leave the rows, and then when I have the table update, it complains the c++ object has been deleted. # self.tableData.setCellWidget(rowCount, 0, trackItem) # RuntimeError: underlying C/C++ object has been deleted I have a list of a custom widget class that keeps track of several directories. Each class gets put into a row on the table. I have a set of radio buttons that will show me different views of the data: All, New, Done, Errors, Warnings. When I switch views, I clear my table, set the row count to 0, and then add back in only the widgets I want to see. Error 1: I load in the data initially, and then repopulate the table, and then re-size the window, instantly all listed rows are cleared, but the rows stay. This only happened on the diagonal re-size (bottom left corner); not the up and down, or side to side re-size. Attempting to repopulate the table, resulted in: underlying C/C++ object has been deleted. Though it will put in the correct number of rows required. Everything worked fine as long as I did not re-size the window. Error 2: I load in the data initially, and then repopulate the table, the table clears and then nothing happens. No error messages or even visible rows. After several more repopulates it with either crash or tell me: underlying C/C++ object has been deleted. I had error 1 two days ago, then without changing the code, I now get error 2. I do not have to re-size the window for it to break now. I am using python 2.7 with PyQt4 4.7.7 Thanks for any insight, Andrew -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with paths
On Mon, 18 Oct 2010 14:24:39 -0700 (PDT) Devin M devin...@gmail.com wrote: Hello, I am using os.path to get the absolute paths of a few directories that some python files are in. FIlePath = os.path.dirname(os.path.realpath(__file__)) which returns a path similar to /home/devinm/project/files Now I want to get the directory above this one. (/home/devinm/ project/) Is there a simple way to do this? I was considering spliting apart the path and then reconstructing it with the last folder left off. Hope theres a better way to do this. Maybe os.relpath(.., FilePath) ? Python 2.6 only. Don't know if that does what you want, but from the description, it seems to fit: http://docs.python.org/library/os.path.html os.path.relpath(path[, start]) Return a relative filepath to path either from the current directory or from an optional start point. start defaults to os.curdir. /W -- To reach me via email, replace INVALID with the country code of my home country. But if you spam me, I'll be one sour Kraut. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with paths
On Mon, 18 Oct 2010 17:29:11 -0400 Andreas Waldenburger use...@geekmail.invalid wrote: On Mon, 18 Oct 2010 14:24:39 -0700 (PDT) Devin M devin...@gmail.com wrote: [snip] Maybe os.relpath(.., FilePath) ? Python 2.6 only. Gah! I should learn to copypaste more. Obviously it's the second one (os.path.relpath), not the first. /W -- To reach me via email, replace INVALID with the country code of my home country. But if you spam me, I'll be one sour Kraut. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with paths
On Mon, Oct 18, 2010 at 2:24 PM, Devin M devin...@gmail.com wrote: Hello, I am using os.path to get the absolute paths of a few directories that some python files are in. FIlePath = os.path.dirname(os.path.realpath(__file__)) which returns a path similar to /home/devinm/project/files Now I want to get the directory above this one. (/home/devinm/ project/) Is there a simple way to do this? parent_dir = os.path.split(FilePath)[0] Note that os.split() does not work like str.split(). Also, don't use CamelCase for non-classes. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with paths
On 10/18/2010 2:24 PM Devin M said... Hello, I am using os.path to get the absolute paths of a few directories that some python files are in. FIlePath = os.path.dirname(os.path.realpath(__file__)) which returns a path similar to /home/devinm/project/files Now I want to get the directory above this one. (/home/devinm/ project/) Is there a simple way to do this? I was considering spliting apart the path and then reconstructing it with the last folder left off. Hope theres a better way to do this. Yes -- in the same module... os.__file__ 'C:\\Python26\\lib\\os.pyc' os.path.dirname(os.__file__) 'C:\\Python26\\lib' -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple logging example doesn't work!
If I set logging.basicConfig() call to logging.INFO, then I see info messages in the logfile. I only want to see error messages in the logfile. -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, 18 Oct 2010 17:17:52 +0200, Christian Heimes wrote: Don't nest classes. Just don't. This might be a valid and good approach in some programming languages but it's not Pythonic. Your code can easily be implemented without nested classes. I'll accept that nested classes are unusual, but unPythonic? Never! Here's a contrived example: class K: class Data(tuple): def __init__(self, t): a, b, c = t self.a = a self.b = b self.c = c def spam(self, a, b, c): self.data = type(self).Data([a,b,c]) Of course, in Python 2.6 this *specific* example is better written using namedtuple, but namedtuple is just a factory function for returning a class! class K: # One-liner to create a nested class. Data = namedtuple(Data, a b c) ... Either way, now you can subclass K by changing Data, without exposing your private, internal classes to the rest of the module: class K2(K): class Data(K.Data): def __init__(self, t): t = (int(x) for x in t) super(Data, self).__init__(t) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, 18 Oct 2010 09:34:07 -0700, Chris Rebert wrote: Also, Python's scoping rules, particularly for class-level scopes, don't work the way programmers from languages where nested classes are common would expect: [snip example] I'm sorry, I don't see that language Foo programmers will be surprised that Python is not language Foo is an argument against Python programmers using nested classes. Surely it's an argument against writing Foo in Python? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, 18 Oct 2010 09:34:07 -0700, Chris Rebert wrote: Also, Python's scoping rules, particularly for class-level scopes, don't work the way programmers from languages where nested classes are common would expect: [snip example] I'm sorry, I don't see that language Foo programmers will be surprised that Python is not language Foo is an argument against Python programmers using nested classes. Surely it's an argument against writing Foo in Python? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, 18 Oct 2010 09:34:07 -0700, Chris Rebert wrote: Also, Python's scoping rules, particularly for class-level scopes, don't work the way programmers from languages where nested classes are common would expect: [snip example] I'm sorry, I don't see that language Foo programmers will be surprised that Python is not language Foo is an argument against Python programmers using nested classes. Surely it's an argument against writing Foo in Python? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, 18 Oct 2010 09:34:07 -0700, Chris Rebert wrote: Also, Python's scoping rules, particularly for class-level scopes, don't work the way programmers from languages where nested classes are common would expect: [snip example] I'm sorry, I don't see that language Foo programmers will be surprised that Python is not language Foo is an argument against Python programmers using nested classes. Surely it's an argument against writing Foo in Python? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, 18 Oct 2010 09:34:07 -0700, Chris Rebert wrote: Also, Python's scoping rules, particularly for class-level scopes, don't work the way programmers from languages where nested classes are common would expect: [snip example] I'm sorry, I don't see that language Foo programmers will be surprised that Python is not language Foo is an argument against Python programmers using nested classes. Surely it's an argument against writing Foo in Python? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with paths
On 18.10.2010 23:24, Devin M wrote: Hello, I am using os.path to get the absolute paths of a few directories that some python files are in. FIlePath = os.path.dirname(os.path.realpath(__file__)) which returns a path similar to /home/devinm/project/files Now I want to get the directory above this one. (/home/devinm/ project/) Is there a simple way to do this? I was considering spliting apart the path and then reconstructing it with the last folder left off. Hope theres a better way to do this. Regards, Devin M os.path.split() is designed for this In [4]: path=/home/devinm/project/files In [5]: import os.path In [6]: os.path.split(path)[0] Out[6]: '/home/devinm/project' -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, 18 Oct 2010 09:34:07 -0700, Chris Rebert wrote: Also, Python's scoping rules, particularly for class-level scopes, don't work the way programmers from languages where nested classes are common would expect: [snip example] I'm sorry, I don't see that language Foo programmers will be surprised that Python is not language Foo is an argument against Python programmers using nested classes. Surely it's an argument against writing Foo in Python? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, 18 Oct 2010 09:34:07 -0700, Chris Rebert wrote: Also, Python's scoping rules, particularly for class-level scopes, don't work the way programmers from languages where nested classes are common would expect: [snip example] I'm sorry, I don't see that language Foo programmers will be surprised that Python is not language Foo is an argument against Python programmers using nested classes. Surely it's an argument against writing Foo in Python? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, 18 Oct 2010 09:34:07 -0700, Chris Rebert wrote: Also, Python's scoping rules, particularly for class-level scopes, don't work the way programmers from languages where nested classes are common would expect: [snip example] I'm sorry, I don't see that language Foo programmers will be surprised that Python is not language Foo is an argument against Python programmers using nested classes. Surely it's an argument against writing Foo in Python? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, 18 Oct 2010 09:34:07 -0700, Chris Rebert wrote: Also, Python's scoping rules, particularly for class-level scopes, don't work the way programmers from languages where nested classes are common would expect: [snip example] I'm sorry, I don't see that language Foo programmers will be surprised that Python is not language Foo is an argument against Python programmers using nested classes. Surely it's an argument against writing Foo in Python? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, 18 Oct 2010 09:34:07 -0700, Chris Rebert wrote: Also, Python's scoping rules, particularly for class-level scopes, don't work the way programmers from languages where nested classes are common would expect: [snip example] I'm sorry, I don't see that language Foo programmers will be surprised that Python is not language Foo is an argument against Python programmers using nested classes. Surely it's an argument against writing Foo in Python? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
In article 4cbcca47$0$29979$c3e8da3$54964...@news.astraweb.com, Steven D'Aprano st...@remove-this-cybersource.com.au wrote: I'm sorry, I don't see that language Foo programmers will be surprised that Python is not language Foo is an argument against Python programmers using nested classes. Surely it's an argument against writing Foo in Python? Maybe, but there's no reason for posting that ten times! ;-) -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ If you think it's expensive to hire a professional to do the job, wait until you hire an amateur. --Red Adair -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: stats 0.1a calculator statistics for Python
On Mon, 18 Oct 2010 11:56:39 +0200, Jean-Michel Pichavant wrote: I already have a stats module: /usr/lib/python2.5/site-packages/stats.py The name of my module is not set in stone. I can't help what site-packages you have, but the above is not on PyPI, and it's certainly not part of the standard library. If my module (or one like it) gets accepted for the standard library, I don't think that could happen until version 3.3. When that happens, a name will be chosen. Until then, I've got the first package on PyPI called stats, and I'm keeping it :) It may not stay stats forever, since it is uncomfortably close to the stat module. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Starting Python in XP Pro
In message mailman.1791.1287310653.29448.python-l...@python.org, Dave Angel wrote: As you've noticed, many times a program started from the start menu doesn't leave its command window open long enough to read the messages. Windows needs an equivalent to ~/.xsession-errors. -- http://mail.python.org/mailman/listinfo/python-list
Re: Spreadsheet-style dependency tracking
In message 42d82f8a-4ee6-44a7-914d-86dfc21f1...@a36g2000yqc.googlegroups.com, Fuzzyman wrote: Allowing calculations to complete even in the presence of cycles can be very useful. But then the answer is no longer completely deterministic. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with paths
On Oct 18, 2:43 pm, Alexander Kapps alex.ka...@web.de wrote: On 18.10.2010 23:24, Devin M wrote: Hello, I am using os.path to get the absolute paths of a few directories that some python files are in. FIlePath = os.path.dirname(os.path.realpath(__file__)) which returns a path similar to /home/devinm/project/files Now I want to get the directory above this one. (/home/devinm/ project/) Is there a simple way to do this? I was considering spliting apart the path and then reconstructing it with the last folder left off. Hope theres a better way to do this. Regards, Devin M os.path.split() is designed for this In [4]: path=/home/devinm/project/files In [5]: import os.path In [6]: os.path.split(path)[0] Out[6]: '/home/devinm/project' Thank you for the help -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple logging example doesn't work!
On Oct 18, 10:45 pm, robinsieb...@gmail.com robinsieb...@gmail.com wrote: If I setlogging.basicConfig() call tologging.INFO, then I see info messages in the logfile. I only want to see error messages in the logfile. What you need to do is, 1. Set the root logger's level to INFO. That's because you want at least INFO messages to go somewhere. 2. Don't use basicConfig(), but instead create a console handler and a file handler explicitly. 3. Set the file handler's level to ERROR, so only ERROR messages and higher go to the file. 4. Set the console handler's level to INFO, so INFO messages and higher go to console. With this setup, the console will show INFO, WARNING, ERROR, CRITICAL messages. The log file will show ERROR, CRITICAL messages. If you need anything more involved (for example, you ONLY want INFO messages to be shown on the console) you'll need to set up a suitable Filter and add it to the console handler to filter out messages you don't want. See the logging docs for more info on Filters. Regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
surprise: cheap wholesale Gucci jackets by payal all products are free shipping
welcome to http://www.jialiuonline.com/FOOTWEAR/ or feel All the products are listed as following: Footwear: NikeAF1,Airmax,Shox,Adidas,Timberland,Puma,Gucci,Prada,LV,Chanel,Lacoste,Lebron,Kobe,Rift, Dunk SB, Nike Women Shoes, Nike Children Shoes, Hogan, Obama, Coogi, Bape Star, Adicolor, Ice Cream,Jordan1--Jordan24,Clear Jordan, Jordan Fusion, AJF, Jordan Flight 45,UGG Boots, Etc. Other Products: 1. Bags/Purses : Coach, Chanel, LV, DG, Burberry, Dior, Ed Hardy, Christian, Audigier(CA), Fendi, Guess, Gucci, Prada, Miumiu, Versace,Juicy, Chole, Tous, Cadillac, a,Etc. 2. Caps Hats: ED Hardy, Smet, Coogi, New Era, SF, Bape, AFF, CA, Ke, Etc. 3. T-Shirts: ED Hardy, Affliction, Christian, Audigier(CA), AF, Lacoste, Armani, Coogi, DG, G-Star, Evisu, Ad, Polo, Versace, Bape, Rockwear, Sinful, Smet, Gucci, Etc. 4. Hoody/Jacket/Coat: Affliction, AF, Blac Label, Bape, BBC, Christian Audigier(CA), Coogi, Crystal Rock,CLH,10Deep,DG,EDHardy,Ecko,Evisu,GGG,Gucci,G- Star,Juicy ,Kidrobot, Kappa, Lacoste, LRG,NY, Polo, Sinful, True Religion, Versace,Adicolor, Armani, Burberry, LV,NF, Prada, Spider, Etc. 5. JeansPants: AF, True Religion, LRG, Rock, Coogi, DG,ED Hardy, Christan Audigier, Red Monkey, Affliction, Artful Dodger, Armani, G-Star, Seven, Dsquared, Ect. 6. jerseys authentic NFL jerseys, MLB jerseys, NBA jerseys, NHL jerseys NCAA jerseys. 7. Sunglasses: Armani,Coach,Dior,EDHardy,Versace,LV,Rp,Fendi,Burberry,Cartier,Chanel,Dg,Gucci,Prada,Etc. 8.belts AAA belt: Armani belt AAA,Boss belt AAA,DG belt AAA,ED Hardy belt AAA,Gucci belt AAA,LV belt AAA,Versace belt AAA,Other belt AAA, Normal belt: Armani belt,Bape belt,Boss belt,Burberry belt,Chanel belt,DG belt, Diesel belt,DSQuard belt,ED CA belt,Gucci belt,Hermes belt,Juicy belt, LV belt,Versace belt,Other belt Website: http://www.jialiuonline.com Phone number :86-791-8327716 -- http://mail.python.org/mailman/listinfo/python-list
Getting returncode of a command executed with Popen through xterm
Hi, i have a program that have to execute linux commands. I do it like this: retcode = Popen([xterm, -e, command],stdin=PIPE, stdout=PIPE, stderr=PIPE) I have to use xterm because some commands need further input from the user after they are executed. But when i use xterm i can't get the returncode or the errormessage from a command: print retcode.returncode# always 0 print retcode.stderr.read() # always empty print retcode.stdout.read() # always empty The same code works without xterm. As i understand it, if i use xterm the retcode refers to the xterm window (process). But is there a way i can get the returncode and errormessage of the command i sent to xterm ? Thanks for any answers AmFreak -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On 2010-10-18, Aahz a...@pythoncraft.com wrote: In article 4cbcca47$0$29979$c3e8da3$54964...@news.astraweb.com, Steven D'Aprano st...@remove-this-cybersource.com.au wrote: [duplicate post] Maybe, but there's no reason for posting that ten times! ;-) I would guess that there is almost certainly a reason. My first candidate would be buggy software, but you never know. -s -- Copyright 2010, all wrongs reversed. Peter Seebach / usenet-nos...@seebs.net http://www.seebs.net/log/ -- lawsuits, religion, and funny pictures http://en.wikipedia.org/wiki/Fair_Game_(Scientology) -- get educated! I am not speaking for my employer, although they do rent some of my opinions. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: stats 0.1a calculator statistics for Python
Steven D'Aprano st...@remove-this-cybersource.com.au writes: On Mon, 18 Oct 2010 11:56:39 +0200, Jean-Michel Pichavant wrote: I already have a stats module: /usr/lib/python2.5/site-packages/stats.py The name of my module is not set in stone. I can't help what site-packages you have, but the above is not on PyPI, and it's certainly not part of the standard library. How did you determine that? Unfortunately, the name of the package listed on PyPI bears no relation to the name of packages installed into Python. So IIUC your claim above can only be verified by checking what package names actually get installed by each package on PyPI. -- \“Of course, everybody says they're for peace. Hitler was for | `\ peace. Everybody is for peace. The question is: what kind of | _o__)peace?” —Noam Chomsky, 1984-05-14 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, 18 Oct 2010 16:05:04 -0700, Aahz wrote: In article 4cbcca47$0$29979$c3e8da3$54964...@news.astraweb.com, Steven D'Aprano st...@remove-this-cybersource.com.au wrote: I'm sorry, I don't see that language Foo programmers will be surprised that Python is not language Foo is an argument against Python programmers using nested classes. Surely it's an argument against writing Foo in Python? Maybe, but there's no reason for posting that ten times! ;-) Gah!!! I promise that I only clicked Send *once*, honest! -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: stats 0.1a calculator statistics for Python
On Tue, 19 Oct 2010 11:53:40 +1100, Ben Finney wrote: Steven D'Aprano st...@remove-this-cybersource.com.au writes: On Mon, 18 Oct 2010 11:56:39 +0200, Jean-Michel Pichavant wrote: I already have a stats module: /usr/lib/python2.5/site-packages/stats.py The name of my module is not set in stone. I can't help what site-packages you have, but the above is not on PyPI, and it's certainly not part of the standard library. How did you determine that? Unfortunately, the name of the package listed on PyPI bears no relation to the name of packages installed into Python. Fair point. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Spreadsheet-style dependency tracking
On Oct 18, 4:15 pm, Lawrence D'Oliveiro l...@geek- central.gen.new_zealand wrote: In message 42d82f8a-4ee6-44a7-914d-86dfc21f1...@a36g2000yqc.googlegroups.com, Fuzzyman wrote: Allowing calculations to complete even in the presence of cycles can be very useful. But then the answer is no longer completely deterministic. Yes it is, unless you're using your Geiger counter random bit generator function. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Learning with Open Source Applications.
Hello all. I am sorry for the cross posting but I really would like to hear comments from experience people in Python. I am new to Python, not new in programming. I am leaving the PHP path and moving to Python. When I was learning PHP it was very useful to learn to install OpenSource solutions , implemented them and study how they work, learn how to modify them. For example I used e-commerce shopping cart solution and learned a lot. Can you recommend, similar solutions, not only for shopping cart but any other subject is good also so I can follow the same schema of learning ? I mean, solutions you consider are very well written and that are examples of what a good Python applications should be written? I know there are tons of applications but would like to hear advice based on experience if possible. Thanks. Thanks in advance. Jorge Biquez -- http://mail.python.org/mailman/listinfo/python-list
choose value from custom distribution
Hello, I'm trying to find a way to collect a set of values from real data, and then sample values randomly from this data - so, the data I'm collecting becomes a kind of probability distribution. For instance, I might have age data for some children. It's very easy to collect this data using a list, where the index gives the value of the data, and the number in the list gives the number of times that values occurs: [0,0,10,20,5] could mean that there are no individuals that are no people aged 0, no people aged 1, 10 people aged 2, 20 people aged 3, and 5 people aged 4 in my data collection. I then want to make a random sample that would be representative of these proportions - is there any easy and fast way to select an entry weighted by its value? Or are there any python packages that allow you to easily create your own distribution based on collected data? Two other things to bear in mind are that in reality I'm collating data from up to around 5 million individuals, so just making one long list with a new entry for each individual won't work. Also, it would be good if I didn't have to decide before hand what the possible range of values is (which unfortunately I have to do with the approach I'm currently working on). Thanks in advance for your help, elsa. -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
Steven D'Aprano st...@remove-this-cybersource.com.au wrote: I'll accept that nested classes are unusual, but unPythonic? Never! Not even if flat is better than nested ;) And are you the same Steven D'Aprano who once wrote: Never nest classes, unless you need to, or to win a bet. Given that there's little if anything gained from nesting classes (other than possible scoping confusion) is there ever a need? -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Tue, Oct 19, 2010 at 1:37 PM, alex23 wuwe...@gmail.com wrote: Given that there's little if anything gained from nesting classes (other than possible scoping confusion) is there ever a need? 15+ years of programming and I've never used nested classes in any language :) cheers James -- -- James Mills -- -- Problems are solved by method -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Tue, 19 Oct 2010 13:54:32 +1000, James Mills wrote: On Tue, Oct 19, 2010 at 1:37 PM, alex23 wuwe...@gmail.com wrote: Given that there's little if anything gained from nesting classes (other than possible scoping confusion) is there ever a need? 15+ years of programming and I've never used nested classes in any language :) I first started programming in the mid 1980s, and I've never once needed to write an SQL query. Does that imply that nobody does? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, Oct 18, 2010 at 3:24 PM, Steven D'Aprano st...@remove-this-cybersource.com.au wrote: On Mon, 18 Oct 2010 09:34:07 -0700, Chris Rebert wrote: Also, Python's scoping rules, particularly for class-level scopes, don't work the way programmers from languages where nested classes are common would expect: [snip example] I'm sorry, I don't see that language Foo programmers will be surprised that Python is not language Foo is an argument against Python programmers using nested classes. Surely it's an argument against writing Foo in Python? Touché; however, Python's semantics here differ so drastically from most other languages and the construction in question is so rarely used or useful that anyone who does use it is likely either in the running for Python language-lawyers-of-the-year or has a vendetta against polyglot programmers. :-) Cheers, Chris -- Why am I reminded of for-else... Also, where does one get a Juris Doctor Programmatica? http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Deferring a function call
I'm writing a simple simulator, and I want to schedule an action to occur at a later time. Basically, at some later point I want to call a function f(a, b, c). But the values of a, b and c are determined at the current time. One way way to do this is to keep a list of entries of the form [[TIME, FN, ARGS]...] and at simulated time TIME do: apply(FN, ARGS) Aside from the fact that apply is deprecated, it seems like there should be a cleaner (possibly more Pythonic) way to do this. Ideas? -Tom -- http://mail.python.org/mailman/listinfo/python-list
Re: Deferring a function call
On Mon, Oct 18, 2010 at 9:21 PM, TomF tomf.sess...@gmail.com wrote: I'm writing a simple simulator, and I want to schedule an action to occur at a later time. Basically, at some later point I want to call a function f(a, b, c). But the values of a, b and c are determined at the current time. See the `sched` std lib module: http://docs.python.org/library/sched.html Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: choose value from custom distribution
On Mon, Oct 18, 2010 at 8:27 PM, elsa kerensael...@hotmail.com wrote: Hello, I'm trying to find a way to collect a set of values from real data, and then sample values randomly from this data - so, the data I'm collecting becomes a kind of probability distribution. For instance, I might have age data for some children. It's very easy to collect this data using a list, where the index gives the value of the data, and the number in the list gives the number of times that values occurs: [0,0,10,20,5] could mean that there are no individuals that are no people aged 0, no people aged 1, 10 people aged 2, 20 people aged 3, and 5 people aged 4 in my data collection. I then want to make a random sample that would be representative of these proportions - is there any easy and fast way to select an entry weighted by its value? Or are there any python packages that allow you to easily create your own distribution based on collected data? Two other things to bear in mind are that in reality I'm collating data from up to around 5 million individuals, so just making one long list with a new entry for each individual won't work. Also, it would be good if I didn't have to decide before hand what the possible range of values is (which unfortunately I have to do with the approach I'm currently working on). http://stackoverflow.com/questions/526255/probability-distribution-in-python There's quite possibly something for this in NumPy/SciPy (or at least a more efficient recipe utilizing one of them). Hopefully someone will chime in. Cheers, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Classes in a class: how to access variables from one in another
On Mon, 18 Oct 2010 20:37:34 -0700, alex23 wrote: Steven D'Aprano st...@remove-this-cybersource.com.au wrote: I'll accept that nested classes are unusual, but unPythonic? Never! Not even if flat is better than nested ;) But Namespaces are one honking great idea -- let's do more of those! (classes are a good thing) and Readability counts. (namespace pollution is a bad thing). And are you the same Steven D'Aprano who once wrote: Never nest classes, unless you need to, or to win a bet. Yep, that was me. And I stand by it. Most of the time non-nested solutions is the best solution. But when it's not, there's nothing wrong with nesting classes. After all, a nested class is no more scary than a nested function. Given that there's little if anything gained from nesting classes (other than possible scoping confusion) is there ever a need? Avoiding namespace pollution and information hiding are two good reasons for nesting classes. Take this recipe for example: http://code.activestate.com/recipes/252524 There's no need to expose the Node class, and no reason not to nest it. Nor is there particularly any reason to nest it, other than those given above. But it is a matter of choice -- the author choose not to nest the class, but he could easily have chosen to. If the author had valued information hiding over one extra indent level, then I would call that a need. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Deferring a function call
On Mon, 18 Oct 2010 21:21:41 -0700, TomF wrote: I'm writing a simple simulator, and I want to schedule an action to occur at a later time. Basically, at some later point I want to call a function f(a, b, c). But the values of a, b and c are determined at the current time. One way way to do this is to keep a list of entries of the form [[TIME, FN, ARGS]...] and at simulated time TIME do: apply(FN, ARGS) Aside from the fact that apply is deprecated, Instead of apply(f, args) you should write: f(*args) If you have keyword arguments as well (or instead): f(*args, **kwargs) it seems like there should be a cleaner (possibly more Pythonic) way to do this. Ideas? Chris Rebert has already mentioned the sched module. Otherwise, put the function call in a thread, and have the thread use time.sleep to wait until the right time to execute. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Deferring a function call
In message 2010101821214168010-tomfsess...@gmailcom, TomF wrote: One way way to do this is to keep a list of entries of the form [[TIME, FN, ARGS]...] and at simulated time TIME do: fn(*args) or fn(**kwargs) -- http://mail.python.org/mailman/listinfo/python-list
Re: Deferring a function call
On 19Oct2010 04:59, Steven D'Aprano steve-remove-t...@cybersource.com.au wrote: | Chris Rebert has already mentioned the sched module. Otherwise, put the | function call in a thread, and have the thread use time.sleep to wait | until the right time to execute. There is also the Timer class from the threading module. Cheers, -- Cameron Simpson c...@zip.com.au DoD#743 http://www.cskk.ezoshosting.com/cs/ A crash reduces your expensive computer to a simple stone. - Haiku Error Messages http://www.salonmagazine.com/21st/chal/1998/02/10chal2.html -- http://mail.python.org/mailman/listinfo/python-list
[issue9862] PIPE_BUF is invalid on AIX
Sébastien Sablé sa...@users.sourceforge.net added the comment: Thanks R. David. I checked in 3.1 and PIPE_BUF is not defined in the select module, so the default value of 512 is used in subprocess. So no correction is needed for that version. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9862 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10048] urllib.request documentation confusing
Changes by Senthil Kumaran orsent...@gmail.com: -- assignee: d...@python - orsenthil ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10048 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1531775] HTTPSConnection request hangs
Senthil Kumaran orsent...@gmail.com added the comment: Not an issue anymore as socket timeout at client is supposed to happen with the connection is hung due to unresponsive host. The original bug was raised py2.3. Closing it as out of date. -- nosy: +orsenthil resolution: - out of date stage: unit test needed - committed/rejected status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue1531775 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1520831] urrlib2 max_redirections=0 disables redirects
Changes by Senthil Kumaran orsent...@gmail.com: -- assignee: - orsenthil ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue1520831 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9778] Make hash values the same width as a pointer (or Py_ssize_t)
Marc-Andre Lemburg m...@egenix.com added the comment: Wouldn't it be better to use Py_hash_t instead of size_t for calculating the hash values in those hash functions ? -- nosy: +lemburg ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9778 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue9778] Make hash values the same width as a pointer (or Py_ssize_t)
Marc-Andre Lemburg m...@egenix.com added the comment: And related to my previous comment: shouldn't Py_hash_t map to size_t instead of Py_ssize_t ? -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue9778 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue678250] test_mmap failling on AIX
Sébastien Sablé sa...@users.sourceforge.net added the comment: I also believe this patch should be backported. If the issue2643 is not backported, then the patch to apply should be patch_flush_mmap.diff instead of patch_mmap_flush_updated.diff -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue678250 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue10135] Format specifier 'n' not working
New submission from Boštjan Mejak bostjan.me...@gmail.com: Have your default locale set to 'Slovenian' which uses a comma for the decimal symbol, like 2.76 is written as 2,76. Observe that the format specifier 'n' does not work for the default 'Slovenian' locale setting. Then try running this in the Python interpreter: '{number:.3n}'.format(number=2.76) You get this: '{number:.3n}'.format(number=2.76) '2.76' Excepted the is the return value '2,76'. Please fix this bug. -- components: Interpreter Core messages: 119003 nosy: Retro priority: normal severity: normal status: open title: Format specifier 'n' not working type: behavior versions: 3rd party, Python 2.5, Python 2.6, Python 2.7, Python 3.1, Python 3.2, Python 3.3 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue10135 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com