Re: Docstrings for class attributes
Tom Harris a écrit : Greetings, I want to have a class as a container for a bunch of symbolic names for integers, eg: class Constants: FOO = 1 BAR = 2 Do you have a reason to stuff them in a class ? Usually, putting them at the top level of a module is quite enough... Except that I would like to attach a docstring text to the constants, so that help(Constants.FOO) will print some arbitrary string. You can document them in the module or class docstring... -- http://mail.python.org/mailman/listinfo/python-list
Re: Why no tailcall-optimization?
process a écrit : Why doesn't Python optimize tailcalls? Design choice. tail-recursive calls optimization makes debugging harder. Note that this has been discussed quite a few times here. Are there plans for it? I know GvR dislikes some of the functional additions like reduce and Python is supposedly about "one preferrable way of doing things" but not being able to use recursion properly is just a big pain in the a**. While it has some (limited) support for functional idioms, Python is still mostly an imperative language, and as such favors iteration over recursion. Not being able to do XXX is only a PITA if you know no other way to skin the cat. NB : FWIW, I'd personnally prefer to have tail-recursive calls optimization too - but not badly enough to switch to another language... -- http://mail.python.org/mailman/listinfo/python-list
Re: Using vObject
Joshua Gardner schrieb: I'm brand new to USENET so please bear with me. I'm writing a specialized to-do list app. I'm using Django but this is not a question about Django. It has to have recurring tasks set by the managers for the employees to then check off. I've got pretty much everything in the app worked out, except for one thing: the repeating tasks. I want to have it so that the manager puts in a repeating task with a description and a repeat rule. This rule then generates simpler one-time tasks. These one-time tasks have a description, a time (a datetime.datetime object) and "completed" boolean. I've looked around and think I have these options: 1. Manually put it all together with another Django model that implements the repeat rules. 2. Do the same thing but use dateutil.rrule to help. 3. Use the icalendar (http://codespeak.net/icalendar/) module to access ICS files. 4. vObject (http://vobject.skyhouseconsulting.com/) to do the same. I think I want to use vObject because it uses dateutil and the management can easily manage tasks from a desktop app. Only thing is that I find vObject's documentation very cryptic and was wondering if anybody here could shed some light on how to use vObject. A simple "getting-started" tutorial or something similar would be nice. I think you are going down a wrong route here. I have implemented a reservation management application for a museum in TurboGears - and while I use icalendar to support ICS-based viewing of the reservations, I completely manage * store them based on my own model. In case of the recurring events, I have one master-event, that defines the start & recurrence-options. I then create child-events that essentially are write-protected (all editing goes to the master), and serve only as place-holder. But if you want, you can "detach" them, to make them live on their own. The reason for this is simple: if you want to display views of your tasks based on e.g. a specific day, you can query the database. Simple queries will yield a list of tasks needed. Whereas all ICS-based approaches listed above, including vObject, would mean that you - extract *all* the ics-data from the database, not really knowing if there is anything relevant in there for the current view - potentially expand the events in there, manually or through some methods the libraries expose - filter the results. All of this is going to consume much useless time. So I would suggest you use approach 1, possibly 2 (don't know rrule). Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: A bit weird dictionary behavior
Carl Banks a écrit : On Sep 22, 3:43 pm, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote: [EMAIL PROTECTED] a écrit : Pekka Laukkanen: but it still doesn't feel exactly right. Would it be worth submitting a bug? It feels wrong because it is. In a tidier language (Pascal, Java, etc) a boolean and an integer must be different types. Some would argue (and some did by the time Python grew a 'bool' type) that what is wrong is to have a bool type in a language that already have a wider definition of the truth value of an expression... And some would argue that it was wrong to have such a wide definition for the truth value of an expression in the first place... Indeed !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: gplt from scipy missing ?
En Mon, 22 Sep 2008 23:19:49 -0300, Ivan Reborin <[EMAIL PROTECTED]> escribió: I'm relatively new to python. I'm following a tutorial I found on the net, and it uses scipy's gplt for plotting. I installed scipy from their website (win32 installation), numpy also, but when I do from scipy import gplt it gives this error: Traceback (most recent call last): File "", line 1, in from scipy import gplt ImportError: cannot import name gplt Please, can you help me solve this ? How do I get gplt to work ? All advice appreciated. I think scipy does not bundle plotting packages anymore - you may use whatever suits you, from other sources. Try matplotlib, see the wiki: http://wiki.python.org/moin/NumericAndScientific/Plotting -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: a short-cut command for globals().clear() ??
MRAB wrote: How about something like this: def clear_workspace(): keep_set = set(['__builtins__', '__doc__', '__name__', 'clear_workspace']) For 2.6/3.0, add __package__ to the list to be kept. for x in globals().keys(): if x not in keep_set: del globals()[x] -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Why no tailcall-optimization?
process wrote: Why doesn't Python optimize tailcalls? Are there plans for it? I started to write an article on this but it disappeared So short answer: 1. Unless down very carefully, in a way that would slow things down, it would change the semantics of Python. 2. It is usually trivial to convert to a while loop, which amounts to in-frame recursion. If using tail-recursion requires a nested inner function to avoid repeating one-time initialization or exposing the cumulation variable, writing the loop is easier since no nested function is needed. 3. In Python, for loops are usually better for processing iterables, which covers most uses of induction (recursion/iteration). Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Why no tailcall-optimization?
On Sep 22, 9:13 pm, process <[EMAIL PROTECTED]> wrote: > Why doesn't Python optimize tailcalls? Are there plans for it? The main technical difficulty is that the compiler has to know whether the function returns a tail call or not at compile time. But because Python is fully dynamic with regard to type, the compiler never(**) knows anything about any object other than "it's an object". The compiler doesn't even know if the object is callable. Probably it would be possible to achieve this optimization without involving the compiler, but it'd be at cost of great complexity and probably would negatively affect ordinary function calls (which are already slow enough). (BTW, if you're just talking about converting simple tail-recursive functions, and not about general tail-call optimization, then I'd suggest a third-party package would be better for that, since it would be a pretty complex thing that would benefit only a tiny fraction of users.) Carl Banks (**) Actually the compiler can do some compile-time constant expression folding, but that's about it. Otherwise it's object agnostic. -- http://mail.python.org/mailman/listinfo/python-list
Re: any tool can shrink DLL?
Hello, > So, is there such a tool that can scan a DLL then strip the unused > function's code out, so yields a small working DLL? I don't think a utility from the outside will know about unused code in a DLL? Usually the compiler is the one doing dead code elimination. The only thing that comes to mind is "strip" that removes strings from executables. As for UPX, does the slowdown really matter? HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Problems running on hp dual core processor
Hello, > I have a number of clients running a program built with > python 2.5. One has just purchased an HP with a duel > core processor, 2.2G with .099g ram. > > On the new hp, when they try to print they get an > import error; > File win32ui.pyc line 12, in > File win32ui.pyc, line 10, in _load > ImportError: DLL load failed: The specified module > could not be found. > > The file is there The only difference I could find from > their other machines is the processor. Is it the same OS (XP vs Vista ...)? Try to run a small script importing win32ui from CMD, it might give you a better indication on which DLL is causing the problem. As suggested by Mike, run DependecyWalker on win32ui.pyd HTH, -- Miki <[EMAIL PROTECTED]> http://pythonwise.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Regex Help
Hello,
> Anybody know of a good regex to parse html links from html code?
BeautifulSoup is *the* library to handle HTML
from BeautifulSoup import BeautifulSoup
from urllib import urlopen
soup = BeautifulSoup(urlopen("http://python.org/";))
for a in soup("a"):
print a["href"]
HTH,
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list
Re: Time.sleep(0.0125) not available within Linux
En Mon, 22 Sep 2008 23:09:50 -0300, Blubaugh, David A. <[EMAIL PROTECTED]> escribió: I was wondering if anyone has come across the issue of not being allowed to have the following within a Python script operating under Linux: time.sleep(0.0125) It appears that I am not allowed to have the object sleep. Has anyone encountered this specific issue before in the past? I bet your test script is called time.py, or there is a time.py[c] in the same directory, or somewhere in the Python search path. Move/rename the offending module. If I win, it's because my psychic capabilities allow me to translate "I am not allowed to have the object sleep" to "this line of code raises AttributeError". Next time please post the complete traceback... -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
python freeze help
Hello everyone,
I'm trying to use python's freeze utility but I'm running into problems.
I called it like this :
python /usr/share/doc/python2.5/examples/Tools/freeze/freeze.py
~/Documents/Code/Python/src/jester/service.py -m jester
then I did : make
then I tried to run it : ./service
and I get this :
[EMAIL PROTECTED]:~/tmp/freeze$ ./service
Traceback (most recent call last):
File "/home/grossetti/Documents/Code/Python/src/jester/service.py",
line 16, in
from jester import constants, utils
File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line
20, in
from twisted.internet.protocol import Protocol, ClientCreator
File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py",
line 17, in
from zope.interface import implements
File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in
pkg_resources.declare_namespace('zope')
File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749,
in declare_namespace
_handle_ns(packageName, path_item)
File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719,
in _handle_ns
path = module.__path__; path.append(subpath)
AttributeError: 'str' object has no attribute 'append'
Error in sys.excepthook:
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/apport_python_hook.py", line
38, in apport_excepthook
from apport.packaging_impl import impl as packaging
File "/usr/lib/python2.5/site-packages/apport/__init__.py", line 1, in
from apport.report import Report
File "/usr/lib/python2.5/site-packages/apport/report.py", line 20, in
from problem_report import ProblemReport
File "/usr/lib/python2.5/site-packages/problem_report.py", line 18, in
from email.MIMEMultipart import MIMEMultipart
File "/usr/lib/python2.5/email/__init__.py", line 79, in __getattr__
__import__(self.__name__)
ImportError: No module named multipart
Original exception was:
Traceback (most recent call last):
File "/home/grossetti/Documents/Code/Python/src/jester/service.py",
line 16, in
from jester import constants, utils
File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line
20, in
from twisted.internet.protocol import Protocol, ClientCreator
File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py",
line 17, in
from zope.interface import implements
File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in
pkg_resources.declare_namespace('zope')
File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749,
in declare_namespace
_handle_ns(packageName, path_item)
File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719,
in _handle_ns
path = module.__path__; path.append(subpath)
AttributeError: 'str' object has no attribute 'append'
Does anyone have any ideas as of why I get this?
Thank you,
Gabriel
--
http://mail.python.org/mailman/listinfo/python-list
adding in-place operator to Python
Hi All, Is there anyway to add new in-place operator to Python? Or is there any way to redefine internal in-place operators? Thanks. Cheers, Arash -- http://mail.python.org/mailman/listinfo/python-list
Re: adding in-place operator to Python
Arash Arfaee wrote: Hi All, Is there anyway to add new in-place operator to Python? You can't create new syntax, like %= Or is there any way to redefine internal in-place operators? What you can do is give your objects the ability to use these operators. See http://docs.python.org/ref/numeric-types.html for __iadd_ (+=) and friends. You could implement something like a string buffer this way: class Buffer: def __init__(self): self.buf = [] def __iadd__(self, item): self.buf.append(item) return self def __str__(self): return "".join(self.buf) if __name__ == "__main__": buf = Buffer() buf += "str1" buf += "str2" print str(buf) -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list
Comparing float and decimal
I'm not sure I follow this logic. Can someone explain why float and
integer can be compared with each other and decimal can be compared to
integer but decimal can't be compared to float?
>>> from decimal import Decimal
>>> i = 10
>>> f = 10.0
>>> d = Decimal("10.00")
>>> i == f
True
>>> i == d
True
>>> f == d
False
This seems to break the rule that if A is equal to B and B is equal to
C then A is equal to C.
--
D'Arcy J.M. Cain <[EMAIL PROTECTED]> | Democracy is three wolves
http://www.druid.net/darcy/| and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list
Re: python timers and COM/directshow
Sayanan Sivaraman wrote:
So I've written a simple video player using directshow/COM in VC++,
and I'm in the process of translating it to python. For example, when
the avi starts playing, I have a call media_control.Run() , etc.
I'm wondering how I should go about updating my gtk.Hscale widget as a
trackbar for the avi player.
In C++, I have the following callbacks that update the scrollbar and
video position with a timer.
[... snip callbacks ...]
I'm wondering how I would implement similar callbacks in Python for a
gtk.Hscale, and some sort of time [I'm not familiar with Pythons
timers/threading at all].
You'd help your cause a lot here if you posted *Python*
code to indicate what's calling what back where. Also if
you stated whether you were using, eg, the GTK toolkit which
your description suggests, or some other GUI toolkit. Because
they tend to vary as to how they arrange their callbacks.
In geeneral, Python callbacks are trivial: you create the
function to do whatever and then pass the function as an
object into the calling-back function call. Something
like this (invented GUI toolkit):
def handle_lbutton_click (event):
#
# do stuff with lbutton click
#
def handle_widget_slide (event):
#
# do stuff with widget slide
#
handle_event ("lbutton_click", handle_lbutton_click)
widget.attach_event ("slide", handle_widget_slide)
But the details will obviously depend on the toolkit you
use.
TJG
TJG
--
http://mail.python.org/mailman/listinfo/python-list
Re: gplt from scipy missing ?
On Tue, 23 Sep 2008 04:26:14 -0300, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > >I think scipy does not bundle plotting packages anymore - you may use >whatever suits you, from other sources. >Try matplotlib, see the wiki: >http://wiki.python.org/moin/NumericAndScientific/Plotting Hello Gabriel, thank you for answering. Unfortunatelly, I cannot change my plotting package, unless I indend to change a lot of code that I'll be using in the future. I'm not a programmer by trade, just a guy doing some calculations with already written programms. Do you know, by any chance, where one could get gplt separately, or for example, get older versions of scipy ? I'm using python 5.2.2.. If I install scipy for python 2.3. for example (let's assume that one still has gplt in it) will it work ? Best regards Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: gplt from scipy missing ?
On Tue, 23 Sep 2008 13:44:41 +0200, Ivan Reborin <[EMAIL PROTECTED]> wrote: >On Tue, 23 Sep 2008 04:26:14 -0300, "Gabriel Genellina" ><[EMAIL PROTECTED]> wrote: > >> >>I think scipy does not bundle plotting packages anymore - you may use >>whatever suits you, from other sources. >>Try matplotlib, see the wiki: >>http://wiki.python.org/moin/NumericAndScientific/Plotting > >Hello Gabriel, >thank you for answering. > >Unfortunatelly, I cannot change my plotting package, unless I indend >to change a lot of code that I'll be using in the future. I'm not a >programmer by trade, just a guy doing some calculations with already >written programms. > >Do you know, by any chance, where one could get gplt separately, or >for example, get older versions of scipy ? >I'm using python 5.2.2.. If I install scipy for python 2.3. for Mea culpa, *2.5.2 >example (let's assume that one still has gplt in it) will it work ? > >Best regards >Ivan -- http://mail.python.org/mailman/listinfo/python-list
Re: Docstrings for class attributes
Tom Harris wrote: > Greetings, > > I want to have a class as a container for a bunch of symbolic names > for integers, eg: > > class Constants: > FOO = 1 > BAR = 2 > > Except that I would like to attach a docstring text to the constants, > so that help(Constants.FOO) will print some arbitrary string. Sort of > a very limited implementation of PEP 224. The only solution that I can > see is to subclass int.__new__(), since once I have an int all it's > attributes are immutable. Epydoc interprets strings like this as doc-strings: """ FOO is not a bar """ FOO = "foo" However, it won't get recognized by help of course. Diez -- http://mail.python.org/mailman/listinfo/python-list
finding domain name
hi group. I'm new to python and need some help and hope you can answer this question. I have a situation in my code where i need to create a file on the server and write to it. That's not a problem if i hard code the path. However, the domain name needs to be dynamic so it is picked up automatically. The path to our websites is home/sites/x/ where x represents the domain name. How can I find the domain name of the current url being viewed. -- http://mail.python.org/mailman/listinfo/python-list
Re: gplt from scipy missing ?
On Sep 23, 7:44 am, Ivan Reborin <[EMAIL PROTECTED]> wrote: > On Tue, 23 Sep 2008 04:26:14 -0300, "Gabriel Genellina" > > <[EMAIL PROTECTED]> wrote: > > >I think scipy does not bundle plotting packages anymore - you may use > >whatever suits you, from other sources. > >Try matplotlib, see the wiki: > >http://wiki.python.org/moin/NumericAndScientific/Plotting > > Hello Gabriel, > thank you for answering. > > Unfortunatelly, I cannot change my plotting package, unless I indend > to change a lot of code that I'll be using in the future. I'm not a > programmer by trade, just a guy doing some calculations with already > written programms. > > Do you know, by any chance, where one could get gplt separately, or > for example, get older versions of scipy ? > I'm using python 5.2.2.. If I install scipy for python 2.3. for > example (let's assume that one still has gplt in it) will it work ? > > Best regards > Ivan Well, if you are using scipy, you must at least be doing some programming. Instead of using gplt, you could just write your data to a .csv file and feed that to gnuplot yourself. You can then use the full flexibility of gnuplot for formatting your output, without having to cross your fingers that the features you need will be covered by the gplt module. You also have your data in a readable format after calculation but before plotting - I find such intermediate data useful for debugging. -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing float and decimal
D'Arcy J.M. Cain wrote:
I'm not sure I follow this logic. Can someone explain why float and
integer can be compared with each other and decimal can be compared to
integer but decimal can't be compared to float?
from decimal import Decimal
i = 10
f = 10.0
d = Decimal("10.00")
i == f
True
i == d
True
f == d
False
I can give you the technical answer after reading the sources of the
decimal module: you can only compare to Decimal what can be converted to
Decimal. And that is int, long and another Decimal.
Everything else will return False when comparing.
This seems to break the rule that if A is equal to B and B is equal to
C then A is equal to C.
Yes, but only if comparison from type(A) to type(C) is supported at all.
Instead of raising ValueError or NotImplementedError, the decimal
module returns False here.
-- Gerhard
--
http://mail.python.org/mailman/listinfo/python-list
Re: finding domain name
Bobby Roberts wrote:
hi group. I'm new to python and need some help and hope you can
answer this question. I have a situation in my code where i need to
create a file on the server and write to it. That's not a problem if
i hard code the path. However, the domain name needs to be dynamic so
it is picked up automatically. The path to our websites is
home/sites/x/
where x represents the domain name.
How can I find the domain name of the current url being viewed.
Depends on the technology/web framework. If you use WSGI, you should use
something like:
host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"]
-- Gerhard
--
http://mail.python.org/mailman/listinfo/python-list
Re: finding domain name
On Tue, Sep 23, 2008 at 8:37 AM, Bobby Roberts <[EMAIL PROTECTED]> wrote: > hi group. I'm new to python and need some help and hope you can > answer this question. I have a situation in my code where i need to > create a file on the server and write to it. That's not a problem if > i hard code the path. However, the domain name needs to be dynamic so > it is picked up automatically. The path to our websites is > > home/sites/x/ > > where x represents the domain name. > > How can I find the domain name of the current url being viewed. I would guess that a pretty simple regular expression might do it. -- http://mail.python.org/mailman/listinfo/python-list
Re: finding domain name
> Depends on the technology/web framework. If you use WSGI, you should use
> something like:
>
> host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"]
>
> -- Gerhard
Yeah i already tried environ("SERVER_NAME") but get a key error when i
do.
--
http://mail.python.org/mailman/listinfo/python-list
Pyflix, confused about super() call
Anyone using Pyflix for the Netflix prize.
How can it call super to itself in its init-method?
-
#!/usr/bin/env python
'''Sample baseline averaging algorithms.'''
import numpy as N
from pyflix.algorithms import Algorithm
class MovieAverage(Algorithm):
'''Baseline algorithm that computes the average of all the votes
for a movie
and predicts that for every user.
This algorithm returns an RMSE score of 1.0528 on the scrubbed
dataset.
'''
def __init__(self, training_set):
self._movie_averages = {}
super(MovieAverage,self).__init__(training_set)
def __call__(self, movie_id, user_id):
try: return self._movie_averages[movie_id]
except KeyError:
avg =
N.average(self._training_set.movie(movie_id).ratings())
self._movie_averages[movie_id] = avg
return avg
class UserAverage(Algorithm):
'''Baseline algorithm that computes the average of all the votes
for a user
and predicts that for every movie.
This algorithm returns an RMSE score of 1.0688 on the scrubbed
dataset.
'''
def __init__(self, training_set):
self._user_averages = {}
super(UserAverage,self).__init__(training_set)
def __call__(self, movie_id, user_id):
try: return self._user_averages[user_id]
except KeyError:
avg =
N.average(self._training_set.user(user_id).ratings())
self._user_averages[user_id] = avg
return avg
class DoubleAverage(MovieAverage,UserAverage):
'''Returns the average of L{MovieAverage} and L{UserAverage}.
This algorithm returns an RMSE score of 1.0158 on the scrubbed
dataset.
'''
def __call__(self, movie_id, user_id):
return (MovieAverage.__call__(self,movie_id,user_id) +
UserAverage.__call__(self,movie_id,user_id)) / 2
--
http://mail.python.org/mailman/listinfo/python-list
Re: Comparing float and decimal
On Tue, 23 Sep 2008 07:20:12 -0400, D'Arcy J.M. Cain wrote:
> I'm not sure I follow this logic. Can someone explain why float and
> integer can be compared with each other and decimal can be compared to
> integer but decimal can't be compared to float?
In comparisons, `Decimal` tries to convert the other type to a `Decimal`.
If this fails -- and it does for floats -- the equality comparison
renders to False. For ordering comparisons, eg. ``D("10") < 10.0``, it
fails more verbosely::
TypeError: unorderable types: Decimal() < float()
The `decimal tutorial`_ states:
"To create a Decimal from a float, first convert it to a string. This
serves as an explicit reminder of the details of the conversion
(including representation error)."
See the `decimal FAQ`_ for a way to convert floats to Decimals.
from decimal import Decimal
i = 10
f = 10.0
d = Decimal("10.00")
i == f
> True
i == d
> True
f == d
> False
>
> This seems to break the rule that if A is equal to B and B is equal to C
> then A is equal to C.
I don't see why transitivity should apply to Python objects in general.
HTH,
.. _decimal tutorial: http://docs.python.org/lib/decimal-tutorial.html
.. _decimal FAQ: http://docs.python.org/lib/decimal-faq.html
--
Robert "Stargaming" Lehmann
--
http://mail.python.org/mailman/listinfo/python-list
Re: finding domain name
On Sep 23, 8:54 am, "Joe Riopel" <[EMAIL PROTECTED]> wrote: > On Tue, Sep 23, 2008 at 8:37 AM, Bobby Roberts <[EMAIL PROTECTED]> wrote: > > hi group. I'm new to python and need some help and hope you can > > answer this question. I have a situation in my code where i need to > > create a file on the server and write to it. That's not a problem if > > i hard code the path. However, the domain name needs to be dynamic so > > it is picked up automatically. The path to our websites is > > > home/sites/x/ > > > where x represents the domain name. > > > How can I find the domain name of the current url being viewed. > > I would guess that a pretty simple regular expression might do it. can you explain? -- http://mail.python.org/mailman/listinfo/python-list
Python-URL! - weekly Python news and links (Sep 23)
QOTW: "Python is THE real integration/composition platform !" - Nicolas Lehuen http://groups.google.com/group/comp.lang.python/msg/05dd6fa4509ab15c Python 2.6rc2 and 3.0rc1 have been released: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6a285ea5ea89bff9/ Using the right algorithm (a single for loop!) and the right data structure (a set!) so often improves computing time *drastically* (from 15 hours to 10 minutes in this example): http://groups.google.com/group/comp.lang.python/browse_thread/thread/21aef9dec3fb5403/ True==1 isn't an obvious fact. Also, why does the bool type exist at all? http://groups.google.com/group/comp.lang.python/browse_thread/thread/1d85b7e32a754e73/ Why some methods (like append) don't return the modified object, while others do? http://groups.google.com/group/comp.lang.python/browse_thread/thread/6196c94118247195/ A design exercise: assign different "weights" to methods--overridable in subclasses or individual instances--so the methods can be chosen at random: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5c90f12e6e7db784/ Grouping items to count them - this leads to discussion of possible implementations of len(arbitrary_iterable): http://groups.google.com/group/comp.lang.python/browse_thread/thread/c8b3976ec3ceadfd/ Killing a thread asynchronously is a bad idea (not just in Python): http://groups.google.com/group/comp.lang.python/browse_thread/thread/b37b57e9c7462fe9/ Discussing ways to secure (untrusted) Python code: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b0c13aaad8c3dc4f/ An [absurd] blog post about Python not being "a full OOP language" triggers a lot of responses: http://groups.google.com/group/comp.lang.python/browse_thread/thread/139c31ff17aed522/ Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see:
Re: New Web2Py framework SLASHES development time...
Hi Paul, yes, the model designer is the one from Ondras. We modified it so that it generates DAL (Database Abstraction Layer) code instead of SQL and it is a work in progress. Technically it is not pat of web2py and in fact it is not distributed with it. It is just one of the many web2py apps. You can find more on http://mdp.cti.depaul.edu/appliances Massimo On Sep 22, 5:48 am, Paul Boddie <[EMAIL PROTECTED]> wrote: > On 22 Sep, 04:49, Steve Shephed <[EMAIL PROTECTED]> wrote: > > > http://www.web2py.comWeb2Py- Python Framework is the newest > > kid on the block for Python frameworks. > > I'm not going to dwell on the merits of web2py, I'm afraid... > > > It has a lot of features that simply are not there in other > > frameworks. Even Ruby!. You can design database models graphically > > online. > > I had a closer look at the model designer, and the client-side magic > seems to originate from this project: > > http://ondras.zarovi.cz/sql/ > > It looks quite fancy, especially since it all seems to be happening in > the browser. Thanks for indirectly bringing this to our attention! ;-) > > Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: finding domain name
Bobby Roberts wrote:
Depends on the technology/web framework. If you use WSGI, you should use
something like:
host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"]
-- Gerhard
Yeah i already tried environ("SERVER_NAME") but get a key error when i
do.
You could output the whole environ to see what you get and how it is called.
I'd recommend however to check that you are using a configured value and
not something sent by the client if you are going to use it during
filesystem lookup.
Regards
Tino
smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list
Mutex not thread safe? PEP-3108.
I'm perusing PEP-3108 and came upon this interesting statement (under the "Hardly used" section): mutex [...] Not thread-safe. How can a mutex, whose sole reason for existence is to mediate thread safety, not be thread safe? -- http://mail.python.org/mailman/listinfo/python-list
Python is slow?
I have recently been playing with a kd-tree for solving the "post office problem" in a 12-dimensional space. This is pure cpu bound number crunching, a task for which I suspected Python to be inefficient. My prototype in Python 2.5 using NumPy required 0.41 seconds to construct the tree from 50,000 samples. Unfortunately, searching it felt a bit slow, finding the 11 nearest-neighbours of 1,000 points took 29.6 seconds (and there were still 49,000 to go). Naturally, I blamed this on Python. It would be 100 times faster if I used C++, right? After having a working Python prototype, I resorted to rewrite the program in C++. The Python prototype took an hour to make, debug and verify. The same thing in C++ took me almost a day to complete, even with a working prototype as model. To my surprise, the resulting beast of C++ required 64.3 seconds to construct the same kd-tree. Searching the tree was not faster either, 1,000 points required 38.8 seconds. I wasted a day, only to find my Python prototype being the faster. We may conclude that I'm bad at programming C++, but I suspect that is not the case here. Albeit micro-benchmarks may indicate that Python is 100-200 times slower than C++, they may not be applicable to the real world. Python can be very efficient. And when combined with libraries like NumPy, beating it's performance with hand-crafted C++ is difficult. At least, my 10 years experience programming scientific software in various languages was not sufficient to beat my own Python prototype with C++. That is not to say I have never seen C++ run a lot faster than Python. But it tends to be very short pieces of CPU bound code, no more than a function or two. But as the problem grows in complexity, C++ accumulates too much of its own bloat. -- http://mail.python.org/mailman/listinfo/python-list
Re: Mutex not thread safe? PEP-3108.
> "Roy" == Roy Smith <[EMAIL PROTECTED]> writes: Roy> I'm perusing PEP-3108 and came upon this interesting statement Roy> (under the "Hardly used" section): Roy> mutex [...] Not thread-safe. Roy> How can a mutex, whose sole reason for existence is to mediate thread Roy> safety, not be thread safe? Because it is a mutex in name only. Take a look at the code. There is nothing in there which actually locks the internal data structure against simultaneous manipulation (a collections.deque instance in this case) from multiple threads. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Mutex not thread safe? PEP-3108.
Roy Smith <[EMAIL PROTECTED]> writes: > I'm perusing PEP-3108 and came upon this interesting statement (under the > "Hardly used" section): > > mutex [...] Not thread-safe. > > How can a mutex, whose sole reason for existence is to mediate thread > safety, not be thread safe? "mutex" is a module designed for use with "sched", not for multithreading: """Mutual exclusion -- for use with module sched [...] Of course, no multi-threading is implied -- hence the funny interface for lock, where a function is called once the lock is aquired. """ What is called a mutex in multithreading is known in Python as threading.Lock, and does work with threads. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why no tailcall-optimization?
On Sep 23, 3:13 am, process <[EMAIL PROTECTED]> wrote: > Why doesn't Python optimize tailcalls? Are there plans for it? Because Python is a dynamic language. While a function is executing, its name may be bound to another object. It may happen as a side effect of what the function is doing, or even from another thread. The compiler has no way of knowing that. Recursion can always be expressed as iteration, possibly with a Python list as stack. -- http://mail.python.org/mailman/listinfo/python-list
The World Trade Plaza - Free Trade Leads
FREE INTERNATIONAL TRADE LEADS ==> The World Trade Plazahttp://trade-plaza.blogspot.com Are you looking for potential clients for your products? Are you looking for a free place for to display your products? Each day we publish international purchase requisitions and offers for sale. The Trade Leads published in our website are FREE for everyone! You have NO NEED TO REGISTER for to view any lead in this website. You have NO LIMIT on Posting Trade Leads. You can Upload Photos With Every Import Export Leads. You can See Latest Products You can automatically receive All Trade Leads by email (Free Subscribe) Much more are All Free. Start Buying or Selling NOW. ==> http://trade-plaza.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Tue, 23 Sep 2008 06:23:12 -0700 (PDT), sturlamolden <[EMAIL PROTECTED]> wrote: >I have recently been playing with a kd-tree for solving the "post >office problem" in a 12-dimensional space. This is pure cpu bound >number crunching, a task for which I suspected Python to be >inefficient. Well, python is not a number crunching language. However much we would like it to be (we would ? :-). No scripting language is. Developing time is shorter, I agree, but when you have, for example a problem which takes 8,31 minutes to go through in optimized fortran code (like the one I had the other day), then that hardly matters. > >My prototype in Python 2.5 using NumPy required 0.41 seconds to >construct the tree from 50,000 samples. Unfortunately, searching it >felt a bit slow, finding the 11 nearest-neighbours of 1,000 points >took 29.6 seconds (and there were still 49,000 to go). Naturally, I >blamed this on Python. It would be 100 times faster if I used C++, >right? Not necessarily. Before resorting to rewriting the problem try psyco. It speeds up things sometimes. Also, (I'm not that familiar with python yet, so I don't know how to do it in python), try finding the bottlenecks of your calculation. Are the loops where most of the processing time is wasted, or disk accessing, or ... ? > >After having a working Python prototype, I resorted to rewrite the >program in C++. The Python prototype took an hour to make, debug and >verify. The same thing in C++ took me almost a day to complete, even >with a working prototype as model. To my surprise, the resulting beast >of C++ required 64.3 seconds to construct the same kd-tree. Searching >the tree was not faster either, 1,000 points required 38.8 seconds. I >wasted a day, only to find my Python prototype being the faster. > >We may conclude that I'm bad at programming C++, but I suspect that is >not the case here. Albeit micro-benchmarks may indicate that Python is >100-200 times slower than C++, they may not be applicable to the real >world. Python can be very efficient. And when combined with libraries >like NumPy, beating it's performance with hand-crafted C++ is >difficult. At least, my 10 years experience programming scientific >software in various languages was not sufficient to beat my own Python >prototype with C++. > >That is not to say I have never seen C++ run a lot faster than Python. >But it tends to be very short pieces of CPU bound code, no more than a >function or two. But as the problem grows in complexity, C++ >accumulates too much of its own bloat. > Well, personally, I try to combine fortran (being a fortran programmer by trade) with python (in the last few years), as I find fortran to be, by two grades, more comfortable for solving scientific problems then c (or python for that matter, although it has its merits). Starting from ith his capabilities for "normal" array handling, to optimisation and easy readability, to whatnot. Best regards Bob -- http://mail.python.org/mailman/listinfo/python-list
Re: Why no tailcall-optimization?
On Tue, 23 Sep 2008 06:41:33 -0700 (PDT), sturlamolden <[EMAIL PROTECTED]> wrote: On Sep 23, 3:13 am, process <[EMAIL PROTECTED]> wrote: Why doesn't Python optimize tailcalls? Are there plans for it? Because Python is a dynamic language. While a function is executing, its name may be bound to another object. It may happen as a side effect of what the function is doing, or even from another thread. The compiler has no way of knowing that. That's not the reason. It's not particularly hard to implement TCE for Python. Instead, Guido has repeatedly given the reason as his feeling that recursion is not the most natural way to express most algorithms in Python. Adding TCE to the runtime would encourage people to write (or continue to write) highly recursive algorithms, which would go against what Guido thinks is "Pythonic". Here's a quote from him on the topic: But I have a problem with tail recursion. It's generally requested by new converts from the Scheme/Lisp or functional programming world, and it usually means they haven't figured out yet how to write code without using recursion for everything yet. IOW I'm doubtful on how much of a difference it would make for real Python programs (which, simplifying a bit, tend to use loops instead of recursion). Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Call for Papers, Volume 3 Issue 3
We would like to call for papers, articles, opinion pieces and feedback to include in Volume 3, Issue 3 of The Python Papers. We would love to receive articles on Python for beginners and discussions about Python performance. Any article will be gratefully received, of course, so do not let the above list of suggestions deter you from considering an article on another topic. We also need volunteers from Python User Groups to include an article on the activities, members and geographical area of their local group. Expressions of Interest Close: Friday, 14 November Initial Draft Submission Deadline: Friday, 21 November Editorial Process Concludes (i.e. Final Version Due): Monday, 15 December PDF Release Date: Sunday, 4th January (approximate) If you are considering submitting an article, please let us know A.S.A.P., even if you are only thinking about it. This will allow us to post email reminders of important dates to prospective authors, as well as giving us an indication of content. If you are unable to submit an article according to the schedule above, please let us know of your interest anyway, and we will involve you in the publication cycle for the following edition. Contact us at [EMAIL PROTECTED] Thanks, -Maurice Ling Co-Editor In Chief, The Python Papers -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On 2008-09-23, sturlamolden <[EMAIL PROTECTED]> wrote: [...] > After having a working Python prototype, I resorted to rewrite the > program in C++. The Python prototype took an hour to make, debug and > verify. The same thing in C++ took me almost a day to complete, even > with a working prototype as model. To my surprise, the resulting beast > of C++ required 64.3 seconds to construct the same kd-tree. Searching > the tree was not faster either, 1,000 points required 38.8 seconds. I > wasted a day, only to find my Python prototype being the faster. > > We may conclude that I'm bad at programming C++, AFAICT, _everybody_ is bad at programming C++. One begins to suspect it's not the fault of the programmers. -- Grant Edwards grante Yow! Finally, Zippy at drives his 1958 RAMBLER visi.comMETROPOLITAN into the faculty dining room. -- http://mail.python.org/mailman/listinfo/python-list
Re: improving a huge double-for cycle
how abt this ? N = len(IN) for k in range(N): for j in range(N): if j >= k: # or k <= j doSomething() KM ~~~ On Thu, Sep 18, 2008 at 6:27 PM, Tim Chase <[EMAIL PROTECTED]>wrote: > Code: Select all >>for i in range(len(IN)): #scan all elements of the list IN >> for j in range(len(IN)): >>if i <> j: >> if IN[i].coordinates[0] == IN[j].coordinates[0]: >> if IN[i].coordinates[1] == IN[j].coordinates[1]: >> SN.append(IN[i].label) >> >> >> Unfortunately my len(IN) is about 100.000 and the running time about >> 15h :( >> >> Any idea to improve it? >> > [snip] > >> I have already tried to group the "if statements" in a single one: >> >> Code: Select all >>if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and >> if IN[i].coordinates[1] == IN[j].coordinates[1]: >> >> but no improvements. >> > > It's like rearranging deck-chairs on the Titanic :) Yes, it may give a > speed up, but what's 3 seconds when you're waiting 15hr :) > > Not knowing the len(IN[x].coordinates) or their structure, if it's a list > of len==2, you should be able to just do > > if i <> j and IN[i].coordinates == IN[j].coordinates > > or > > if i <> j and IN[i].coordinates[:2] == IN[j].coordinates[:2] > > However, again, this is just polish. The big problem is that you have an > O(N^2) algorithm that's killing you. > > 1) use xrange instead of range to save eating memory with a huge unneeded > array. > > 2) unless you need to append duplicate labels, you know that when I and J > are swapped, you'll reach the same condition again, so it might be worth > writing the outer loops to eliminate this scenario, and in the process, but > just starting at i+1 rather than i, you can forgo the check if "i<>j". > > Such changes might look something like > > for i in xrange(len(IN)): >for j in xrange(i+1, len(IN)): > if IN[i].coordinates == IN[j].coordinates: >SN.append(IN[i].label) > > If my college algorithms memory serves me sufficiently, this reduces your > O(N^2) to O(N log N) which will garner you some decent time savings. > > -tkc > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing float and decimal
> > This seems to break the rule that if A is equal to B and B is equal to C > > then A is equal to C. > > I don't see why transitivity should apply to Python objects in general. Well, for numbers it surely would be a nice touch, wouldn't it. May be the reason for Decimal to accept float arguments is that irrational numbers or very long rational numbers cannot be converted to a Decimal without rounding error, and Decimal doesn't want any part of it. Seems pointless to me, though. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 9:57 am, Grant Edwards <[EMAIL PROTECTED]> wrote: > On 2008-09-23, sturlamolden <[EMAIL PROTECTED]> wrote: > > [...] > > > After having a working Python prototype, I resorted to rewrite the > > program in C++. The Python prototype took an hour to make, debug and > > verify. The same thing in C++ took me almost a day to complete, even > > with a working prototype as model. To my surprise, the resulting beast > > of C++ required 64.3 seconds to construct the same kd-tree. Searching > > the tree was not faster either, 1,000 points required 38.8 seconds. I > > wasted a day, only to find my Python prototype being the faster. > > > We may conclude that I'm bad at programming C++, > > AFAICT, _everybody_ is bad at programming C++. +1 QOTW -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
>> We may conclude that I'm bad at programming C++, Grant> AFAICT, _everybody_ is bad at programming C++. Grant> One begins to suspect it's not the fault of the programmers. +1 QOTW... Skip -- http://mail.python.org/mailman/listinfo/python-list
tkFileDialog and locale under Linux
Hi,
I have problems using tkFileDialog under Linux (Ubuntu 8.04 in my case, but
other Linuxes seem to show the same behaviour).
The following works fine:
import tkFileDialog
f = tkFileDialog.askopenfilename()
No problem, I can chose a filename.
But when switching the locale (in my case to German) like this:
import locale
locale.setlocale(locale.LC_ALL, '')
the file dialog won't work anymore. The traceback is:
Traceback (most recent call last):
File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1406, in __call__
return self.func(*args)
File "TextSTAT.pyw", line 701, in datei_hinzu
dateinamen = tkFileDialog.askopenfilename(initialdir=cfg['FileDir'],
filetypes= (('All', '*.*'),('Text', '*.txt'),('HTML', '*.htm*'),('MS Word',
'*.doc'),('MS Word 2007', '*.docx'),('OpenOffice 1.x',
'*.sxw'),('OpenOffice 2.x', '*.odt')), multiple=1)
File "/usr/lib/python2.5/lib-tk/tkFileDialog.py", line 125, in
askopenfilename
return Open(**options).show()
File "/usr/lib/python2.5/lib-tk/tkCommonDialog.py", line 48, in show
s = w.tk.call(self.command, *w._options(self.options))
TclError: expected floating-point number but got "0.0"
Switching back to the C-locale solves the problem:
locale.setlocale(locale.LC_ALL, 'C')
tkFileDialog will work again.
Any ideas?
Best, Matthias
--
http://mail.python.org/mailman/listinfo/python-list
Re: improving a huge double-for cycle
km wrote: how abt this ? N = len(IN) for k in range(N): for j in range(N): if j >= k: # or k <= j doSomething() This has the root problem that the "if" statement is evaluated N*N times, which is ugly/slow O(N^2) behavior. My solution managed to reduce it by a constant multiplier, but several folks proposed a more elegant O(N) solution which was leaps & bounds faster. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Attachment Size and SMTP EMail
Hello All -
I am using python to send an email with a large zip file as an
attachment. I successfully sent a 52M attachment. If I try to send a
63M attachment or larger, the message never gets through. I do not
get any errors in my python code. I pasted my python code below.
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email import Encoders
import smtplib,os
mssg = MIMEMultipart()
part = MIMEBase('application',"octet-stream")
part.set_payload(open(zipFileName,"rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' %
os.path.basename(zipFileName))
mssg.attach(part)
s = smtplib.SMTP('localhost')
s.set_debuglevel(1)
s.sendmail(fromAddr,toAddr,mssg.as_string())
s.quit()
I am using a Fedora Core 6 system with python 2.4.4.
Any suggestions on what could be limiting the attachment size or how I
could troubleshoot this?
Thanks!
EricE
--
http://mail.python.org/mailman/listinfo/python-list
Re: Attachment Size and SMTP EMail
On 2008-09-23, Eric E <[EMAIL PROTECTED]> wrote: > I am using python to send an email with a large zip file as an > attachment. I successfully sent a 52M attachment. If I try > to send a 63M attachment or larger, the message never gets > through. I do not get any errors in my python code. Does sending large attachements with other SMTP clients using the same SMTP server work? -- Grant Edwards grante Yow! Zippy's brain cells at are straining to bridge visi.comsynapses ... -- http://mail.python.org/mailman/listinfo/python-list
Re: finding domain name
On Sep 23, 9:10 am, Tino Wildenhain <[EMAIL PROTECTED]> wrote:
> Bobby Roberts wrote:
> >> Depends on the technology/web framework. If you use WSGI, you should use
> >> something like:
>
> >> host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"]
>
> >> -- Gerhard
>
> > Yeah i already tried environ("SERVER_NAME") but get a key error when i
> > do.
>
> You could output the whole environ to see what you get and how it is called.
>
> I'd recommend however to check that you are using a configured value and
> not something sent by the client if you are going to use it during
> filesystem lookup.
>
> Regards
> Tino
>
> smime.p7s
> 4KViewDownload
evidently the environ dictionary is off limits on our server. It can't
be that tough in python to get the current complete url being viewed.
It's a snap in asp(which is my background).
--
http://mail.python.org/mailman/listinfo/python-list
Linq to Python
Hi Will LINQ be ported to Python ? regards Hrishy -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyflix, confused about super() call
process a écrit :
Anyone using Pyflix for the Netflix prize.
How can it call super to itself in its init-method?
You mean :
class MovieAverage(Algorithm):
def __init__(self, training_set):
self._movie_averages = {}
this line ?
super(MovieAverage,self).__init__(training_set)
If that's what confuse you, I think you really should read the
FineManual(tm) instead of assuming Python is language X or Y.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Linq to Python
hrishy wrote: > Hi > > Will LINQ be ported to Python ? Take a look at SQLAlchemy or SQLObject for python-based ORM/SQL-abstractions. Apart from that, python is already heavily based on concepts like iterators, filtering. Take a look at itertools. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Docstrings for class attributes
On Tue, 23 Sep 2008 15:23:35 +1000, Tom Harris <[EMAIL PROTECTED]> wrote: > > I want to have a class as a container for a bunch of symbolic names > for integers, eg: > > class Constants: > FOO = 1 > BAR = 2 > > Except that I would like to attach a docstring text to the constants, > so that help(Constants.FOO) will print some arbitrary string. [snip] Commiserating, not helping: I have a similar problem with a module that holds values of physical constants, http://webpages.charter.net/curryfans/peter/nature.py: boltzmanns_constant = 1.380622e-16 * erg / k stefan_boltzmann_constant = 5.66961e-5 * erg/s/cm/cm/k/k/k/k gravitational_constant = 6.6732e-8 * erg*cm/g/g I would like to reveal more details with, e.g., help( gravitational_constant ) . . . and maybe then I could use shorter names. -- To email me, substitute nowhere->spamcop, invalid->net. -- http://mail.python.org/mailman/listinfo/python-list
Re: Attachment Size and SMTP EMail
On Sep 23, 9:52 am, Grant Edwards <[EMAIL PROTECTED]> wrote: > On 2008-09-23, Eric E <[EMAIL PROTECTED]> wrote: > > > I am using python to send an email with a large zip file as an > > attachment. I successfully sent a 52M attachment. If I try > > to send a 63M attachment or larger, the message never gets > > through. I do not get any errors in my python code. > > Does sending large attachements with other SMTP clients using > the same SMTP server work? > > -- > Grant Edwards grante Yow! Zippy's brain cells > at are straining to bridge >visi.comsynapses ... I do not know for sure. I recently downloaded msmtp 1.4.16 and am still in the process of trying to get it to work. -- http://mail.python.org/mailman/listinfo/python-list
Re: python freeze help
On Sep 23, 5:01 am, Gabriel Rossetti <[EMAIL PROTECTED]>
wrote:
> Hello everyone,
>
> I'm trying to use python's freeze utility but I'm running into problems.
> I called it like this :
>
> python /usr/share/doc/python2.5/examples/Tools/freeze/freeze.py
> ~/Documents/Code/Python/src/jester/service.py -m jester
>
> then I did : make
>
> then I tried to run it : ./service
>
> and I get this :
>
> [EMAIL PROTECTED]:~/tmp/freeze$ ./service
> Traceback (most recent call last):
> File "/home/grossetti/Documents/Code/Python/src/jester/service.py",
> line 16, in
> from jester import constants, utils
> File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line
> 20, in
> from twisted.internet.protocol import Protocol, ClientCreator
> File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py",
> line 17, in
> from zope.interface import implements
> File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in
>
> pkg_resources.declare_namespace('zope')
> File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749,
> in declare_namespace
> _handle_ns(packageName, path_item)
> File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719,
> in _handle_ns
> path = module.__path__; path.append(subpath)
> AttributeError: 'str' object has no attribute 'append'
> Error in sys.excepthook:
> Traceback (most recent call last):
> File "/usr/lib/python2.5/site-packages/apport_python_hook.py", line
> 38, in apport_excepthook
> from apport.packaging_impl import impl as packaging
> File "/usr/lib/python2.5/site-packages/apport/__init__.py", line 1, in
>
> from apport.report import Report
> File "/usr/lib/python2.5/site-packages/apport/report.py", line 20, in
>
> from problem_report import ProblemReport
> File "/usr/lib/python2.5/site-packages/problem_report.py", line 18, in
>
> from email.MIMEMultipart import MIMEMultipart
> File "/usr/lib/python2.5/email/__init__.py", line 79, in __getattr__
> __import__(self.__name__)
> ImportError: No module named multipart
I've gotten this error from py2exe before. I'm not sure how freeze
works, but in py2exe I had to make sure the email package wasn't being
accidentally excluded and explicitly included.
>
> Original exception was:
> Traceback (most recent call last):
> File "/home/grossetti/Documents/Code/Python/src/jester/service.py",
> line 16, in
> from jester import constants, utils
> File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line
> 20, in
> from twisted.internet.protocol import Protocol, ClientCreator
> File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py",
> line 17, in
> from zope.interface import implements
> File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in
>
> pkg_resources.declare_namespace('zope')
> File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749,
> in declare_namespace
> _handle_ns(packageName, path_item)
> File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719,
> in _handle_ns
> path = module.__path__; path.append(subpath)
> AttributeError: 'str' object has no attribute 'append'
>
> Does anyone have any ideas as of why I get this?
>
> Thank you,
> Gabriel
I don't know what this second error is...
Mike
--
http://mail.python.org/mailman/listinfo/python-list
Re: finding domain name
Bobby Roberts a écrit :
On Sep 23, 9:10 am, Tino Wildenhain <[EMAIL PROTECTED]> wrote:
Bobby Roberts wrote:
Depends on the technology/web framework. If you use WSGI, you should use
something like:
host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"]
-- Gerhard
Yeah i already tried environ("SERVER_NAME") but get a key error when i
do.
You could output the whole environ to see what you get and how it is called.
I'd recommend however to check that you are using a configured value and
not something sent by the client if you are going to use it during
filesystem lookup.
Regards
Tino
smime.p7s
4KViewDownload
evidently the environ dictionary is off limits on our server.
???
It can't
be that tough in python to get the current complete url being viewed.
It's a snap in asp(which is my background).
Please don't compare apples to roller-skates. asp is a mix of libraries,
components and whatever, while Python is a language.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Linq to Python
Hi Thanks for those links however LINQ seems to be much more then ORM tool it can for example join an XML file with a relational datasource or create a XSD regards Hrishy --- On Tue, 23/9/08, Diez B. Roggisch <[EMAIL PROTECTED]> wrote: > From: Diez B. Roggisch <[EMAIL PROTECTED]> > Subject: Re: Linq to Python > To: [email protected] > Date: Tuesday, 23 September, 2008, 4:06 PM > hrishy wrote: > > > Hi > > > > Will LINQ be ported to Python ? > > Take a look at SQLAlchemy or SQLObject for python-based > ORM/SQL-abstractions. > > Apart from that, python is already heavily based on > concepts like iterators, > filtering. Take a look at itertools. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
sturlamolden: CPython is generally slow (you can see this from the huge amount of solutions invented to solve the speed problem, like Cython, Numpy, Psyco, ShedSkin, Weave, Inline, SIP, Boost Python, SWIG, etc etc), but for most of the usages Python is used for, it's not a significant problem. I know that sounds like a tautology :-) Well written C++ code is generally faster or much faster than similar Python code, but programming in Python is often simpler, and it generally requires less time. So it may happen that to solve a problem a Python program that runs in 1 hour that requires 1 hour to be written allows you to find the solution in less time than a C++ program that runs in 5-10 minutes that requires you 3-4 hours to be written :-) Note that C++ is just one option, but there are other languages around, like CLisp or D (or even a modern JavaVM), that are often an acceptable compromise between Python and C/C++. So you can show us a reduced/minimal working version of your Python code, so I/someone may find ways to speed it up, translate it to C or C ++ or CLisp or D, etc. Note that I have written a kd-tree in both Python (with Psyco compulsively) and D, this is the Psyco version: http://code.activestate.com/recipes/572156/ Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
lxml and adding a stylesheet
I have an xml document and simply need to add an xml-stylesheet to it. I am using lxml to parse the xml document and then would like to insert the xml-stylesheet tag using the etree api. Any suggestions? Thanks, Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing float and decimal
On Sep 23, 10:08 am, Michael Palmer <[EMAIL PROTECTED]> wrote: > May be the reason for Decimal to accept float arguments is that NOT to accept float arguments. -- http://mail.python.org/mailman/listinfo/python-list
Re: download redtube video - Free
Hello, You can download Redtube videos to your Computer, iPod, PSP or other mobile devices.. Just get a RedTube Downloader from here: http://www.downloadvideos-convert.com/redtube-downloader --- Enjoy it~ Download Videos from RedTube, YouPorn, PornoTube, XTube, Tube8, Xnxx.com easily, also help you convert videos to any format you want, so you can put RedTube videos on your iPod, PSP or other mobile devices. -- http://mail.python.org/mailman/listinfo/python-list
Re: download redtube video - Free
Or download RedTube videos online: http://www.download-redtube.com/ -- http://mail.python.org/mailman/listinfo/python-list
SPE restore defaults
Hi, I am sorry if this is a bit off topic... I downloaded SPE, but i changed the config option by mistake to a Skin only for Mac... so everytime i start SPE it crashes. I tried uninstalling, but it didnt work, it seems the value is in the registry, but i couldnt find it. Can anyone help? (Spe forum is not useful.. thanks) -- http://mail.python.org/mailman/listinfo/python-list
Re: how can I use a callable object as a method
Hrvoje Niksic wrote: >> However, the second version does not work. I think I understand >> why. That's because "a" inside f1 is not a function (but an object). > > An object that defines __call__ is perfectly usable as a function. > Your problem is that it doesn't know how to convert itself to a > method, so that f1.a() knows how to pass f1 as another_self to > add.__call__. To do that, add needs to be a bit smarter: A! Now it works, thanks a lot! -- http://mail.python.org/mailman/listinfo/python-list
Re: finding domain name
Hi,
Bobby Roberts wrote:
On Sep 23, 9:10 am, Tino Wildenhain <[EMAIL PROTECTED]> wrote:
Bobby Roberts wrote:
Depends on the technology/web framework. If you use WSGI, you should use
something like:
host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"]
-- Gerhard
Yeah i already tried environ("SERVER_NAME") but get a key error when i
do.
You could output the whole environ to see what you get and how it is called.
...
evidently the environ dictionary is off limits on our server. It can't
be that tough in python to get the current complete url being viewed.
It's a snap in asp(which is my background).
Its a snap in all python based web apps I ever saw. You didn't tell us
what you actually using so we can't say. Also there is no notation
of "url beeing viewed" in HTTP if you are looking from server's point of
view. There is a request for an URI and a host where the request is
directed at then then the server decides to publish a resource based
on whatever rules. If that publishing results in a call to your python
script (or the script itself is the server) then you would deal with
whatever interface API you decided to use gives you.
Ah and last not least you can even use python in ASP (look for scripting
host) but's not a route to take these days :-) (You really want no
inline code but a decent templating engine like PageTemplates (TAL))
Tino
smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list
Re: Not fully OO ?
2008/9/23 Craig Allen <[EMAIL PROTECTED]>: > So python may turn out to be pure OO I think that's the sort of thing the pedants would hang that hats on, too. Python isn't *pure* OO, in that it lets the programmers do non-OO if they want to, but it is *fully* OO in that it includes everything required to do OO. But maybe the original blogger meant by "fully OO" what I mean by "Pure OO"? The question I usually ask is "Does this language help me get the job done?" Python often does. That's all that really matters, isn't it? -- Tim Rowe -- http://mail.python.org/mailman/listinfo/python-list
Re: Linq to Python
On Sep 23, 7:48 am, hrishy <[EMAIL PROTECTED]> wrote: > Hi > > Will LINQ be ported to Python ? > > regards > Hrishy I think this question is more appropriate to ask on an IronPython development list -- LINQ is pretty solidly intertwined with .Net, and so you'll likely want to look at the .Net implementation of Python. -- http://mail.python.org/mailman/listinfo/python-list
Matrix programming
I need an ebook or tutorial that teach matrix programming. -- http://mail.python.org/mailman/listinfo/python-list
Re: Docstrings for class attributes
On Sep 23, 1:23 am, "Tom Harris" <[EMAIL PROTECTED]> wrote: > Greetings, > > I want to have a class as a container for a bunch of symbolic names > for integers, eg: > > class Constants: > FOO = 1 > BAR = 2 > > Except that I would like to attach a docstring text to the constants, > so that help(Constants.FOO) will print some arbitrary string. Sort of > a very limited implementation of PEP 224. The only solution that I can > see is to subclass int.__new__(), since once I have an int all it's > attributes are immutable. Here's one approach, using metaclasses and descriptors; it sort of works, but it's less than ideal, both in usage and implementation. George #== usage class MyConstants: __metaclass__ = ConstantsMeta FOO = const(1, 'some docs about foo') BAR = const(2) print MyConstants.FOO.__doc__ help(MyConstants.FOO) print MyConstants.FOO - MyConstants.BAR print MyConstants.FOO - 2 print 1 - MyConstants.BAR #=== implementation === def ConstantsMeta(name, bases, namespace): for name,attr in namespace.iteritems(): if isinstance(attr, const): namespace[name] = _ConstDescriptor(name, attr.value, attr.doc) return type(name, bases, namespace) class const(object): def __init__(self, value, doc=None): self.value = value self.doc = doc class _ConstDescriptor(object): def __init__(self, name, value, doc): cls = type(name, (), dict( __doc__ = doc, __add__ = lambda self,other: value+other, __sub__ = lambda self,other: value-other, # ... __radd__ = lambda self,other: other+value, __rsub__ = lambda self,other: other-value, # XXX lots of boilerplate code for all special methods follow... # XXX Is there a better way ? )) self._wrapper = cls() def __get__(self, obj, type): return self._wrapper -- http://mail.python.org/mailman/listinfo/python-list
Re: Matrix programming
A. Joseph wrote: I need an ebook or tutorial that teach matrix programming. Perhaps you should start here: http://www.catb.org/~esr/faqs/smart-questions.html#intro Gary Herron -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Detecting the first time I open/append to a file
I have a simulation that runs many times with different parameters, and I want to aggregate the output into a single file with one rub: I want a header to be written only the first time. My program looks a bit like this: def main(): for param in range(10): simulate(param) def simulate(parameter): 'Lots of code followed by: with open(summaryFn, 'ab') as f: writer = csv.writer(f) writer.writerow(header) writer.writerow(Sigma) If I can sense that the file is being created in the first iteration, I can then use an if statement to decide whether or not I need to write the header. Question: how can I tell if the file is being created or if this its the first iteration? It's unrealistic to test the value of the parameter as in the real problem, there are many nested loops in main, and the bounds on the loop indices may change. Thanks in advance for your assistance Thomas Philips -- http://mail.python.org/mailman/listinfo/python-list
Re: Linq to Python
On Sep 23, 2:07 pm, Jason Scheirer <[EMAIL PROTECTED]> wrote: > On Sep 23, 7:48 am, hrishy <[EMAIL PROTECTED]> wrote: > > > Hi > > > Will LINQ be ported to Python ? > > > regards > > Hrishy > > I think this question is more appropriate to ask on an IronPython > development list -- LINQ is pretty solidly intertwined with .Net, and > so you'll likely want to look at the .Net implementation of Python. But surely the idea behind it will eventually spread. It's really just comprehensions generalized over XML and relational datasets, a noble goal. Besides, it's main purpose for .NET was to bring functional programming to it. Python already has that, somewhat... -- http://mail.python.org/mailman/listinfo/python-list
Re: adding in-place operator to Python
Arash Arfaee wrote: Hi All, Is there anyway to add new in-place operator to Python? Or is there any way to redefine internal in-place operators? Python does not have 'in-place operators'. It has 'augmented assignment statements' that combines a binary operation with an assignment. *If* the target being rebound is mutable, *then* (and only then) the operation can be and is recommended to be done 'in-place'. User-defined mutable classes (as most are) can implement in-place behavior with __ixxx__ methods. But for the reason given below, __ixxx__ methods should supplement and not replace direct mutation methods. Correct terminology is important for understanding what augmented assigments do and what they are basically about. First, most augmented assignments target immutables, in particular, numbers and strings, which do not have __ixxx__ methods. So the operation is *not* done in-place. The only difference from separately indicating the assignment and operation is that the programmer writes the target expression just once and the interpreter evaluates the target expression just once instead of each repeating themselves. (And consequently, any side-effects of that evaluation happen just once instead of twice.) The same __xxx__ or __rxxx__ method is used in either case. This non-repetition is the reason for augmented assigments. The optional in-place optimization for mutables is secondary. It was debated and could have been left out. Second, all augmented assignments perform an assignment, even if the operation is done in place. However, if a mutable such as a list is accessed as a member of an immutable collection such as a tuple, mutation is possible, but rebinding is not. So the mutation is done and then an exception is raised. To avoid the exception, directly call a mutation method such as list.extend. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 3:44 pm, Robert Singer <[EMAIL PROTECTED]> wrote: > Well, python is not a number crunching language. However much we would > like it to be (we would ? :-). > No scripting language is. Not even Matlab, R, IDL, Octave, SciLab, S-PLUS or Mathematica? > Before resorting to rewriting the problem try psyco. It speeds up > things sometimes. I did, Psyco did not help. > Also, (I'm not that familiar with python yet, so I don't know how to > do it in python), try finding the bottlenecks of your calculation. I did use a profiler, there is no particular single bottle-neck. > Well, personally, I try to combine fortran (being a fortran programmer > by trade) with python Good compilers are too expensive, and gfortran is not good enough yet. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 5:31 pm, [EMAIL PROTECTED] wrote: > Well written C++ code is generally faster or much faster than similar > Python code, but programming in Python is often simpler, and it > generally requires less time. So it may happen that to solve a problem > a Python program that runs in 1 hour that requires 1 hour to be > written allows you to find the solution in less time than a C++ > program that runs in 5-10 minutes that requires you 3-4 hours to be > written :-) I could easily sit down and wait half an hour. I could even wait a week for the calculation to complete. But this is a program that will be used many times, and not just by me. > Note that C++ is just one option, but there are other languages > around, like CLisp or D (or even a modern JavaVM), that are often an > acceptable compromise between Python and C/C++. Yes, if I knew Lisp, I would have used SBCL. Java I can program. But it is a pain in the ass for any scientific programming. F# and OCaml look promising though. > Note that I have written a kd-tree in both Python (with Psyco > compulsively) and D, this is the Psyco > version:http://code.activestate.com/recipes/572156/ Sure I could show you the code, Python and C++, if I had a place to post it. It looks very different form yours though. -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting the first time I open/append to a file
On Sep 23, 2:02 pm, [EMAIL PROTECTED] wrote: > I have a simulation that runs many times with different parameters, > and I want to aggregate the output into a single file with one rub: I > want a header to be written only the first time. My program looks a > bit like this: > > def main(): > for param in range(10): > simulate(param) > > def simulate(parameter): > 'Lots of code followed by: > with open(summaryFn, 'ab') as f: > writer = csv.writer(f) > writer.writerow(header) > writer.writerow(Sigma) > > If I can sense that the file is being created in the first iteration, > I can then use an if statement to decide whether or not I need to > write the header. Question: how can I tell if the file is being > created or if this its the first iteration? It's unrealistic to test > the value of the parameter as in the real problem, there are many > nested loops in main, and the bounds on the loop indices may change. You could use os.path.exists() to check if the file is there. However, the file could have been left over from a previous execution, etc. What might make sense is to open the file only once, store the file handle, and write to that throughout the execution. Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting the first time I open/append to a file
On Sep 23, 7:02 pm, [EMAIL PROTECTED] wrote: > I have a simulation that runs many times with different parameters, > and I want to aggregate the output into a single file with one rub: I > want a header to be written only the first time. My program looks a > bit like this: > > def main(): > for param in range(10): > simulate(param) > > def simulate(parameter): > 'Lots of code followed by: > with open(summaryFn, 'ab') as f: > writer = csv.writer(f) > writer.writerow(header) def simulate(parameter): 'Lots of code followed by: with open(summaryFn, 'ab') as f: writer = csv.writer(f) writer.writerow(header) writer.writerow(Sigma) > writer.writerow(Sigma) > > If I can sense that the file is being created in the first iteration, > I can then use an if statement to decide whether or not I need to > write the header. Question: how can I tell if the file is being > created or if this its the first iteration? It's unrealistic to test > the value of the parameter as in the real problem, there are many > nested loops in main, and the bounds on the loop indices may change. > > Thanks in advance for your assistance > > Thomas Philips You can use he os.path module: appending = os.path.exists(summaryFn) with open(summaryFn, 'ab') as f: writer = ... if not appending: writer.writerow(header) writer.writerow(Sigma) But if you only write to the file in one code location, you can set a flag. HTH -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing float and decimal
Gerhard Häring wrote:
D'Arcy J.M. Cain wrote:
I'm not sure I follow this logic. Can someone explain why float and
integer can be compared with each other and decimal can be compared to
integer but decimal can't be compared to float?
from decimal import Decimal
i = 10
f = 10.0
d = Decimal("10.00")
i == f
True
i == d
True
f == d
False
I can give you the technical answer after reading the sources of the
decimal module: you can only compare to Decimal what can be converted to
Decimal. And that is int, long and another Decimal.
The new fractions module acts differently, which is to say, as most
would want.
>>> from fractions import Fraction as F
>>> F(1) == 1.0
True
>>> F(1.0)
Traceback (most recent call last):
File "", line 1, in
F(1.0)
File "C:\Program Files\Python30\lib\fractions.py", line 97, in __new__
numerator = operator.index(numerator)
TypeError: 'float' object cannot be interpreted as an integer
>>> F(1,2) == .5
True
>>> .5 == F(1,2)
True
so Fraction obviously does comparisons differently.
Decimal is something of an anomaly in Python because it was written to
exactly follow an external standard, with no concessions to what would
be sensible for Python. It is possible that that standard mandates that
Decimals not compare to floats.
tjr
--
http://mail.python.org/mailman/listinfo/python-list
Re: python timers and COM/directshow
On Sep 23, 4:24 am, Tim Golden <[EMAIL PROTECTED]> wrote:
> Sayanan Sivaraman wrote:
> > So I've written a simple video player using directshow/COM in VC++,
> > and I'm in the process of translating it to python. For example, when
> > the avi starts playing, I have a call media_control.Run() , etc.
>
> > I'm wondering how I should go about updating my gtk.Hscale widget as a
> > trackbar for the avi player.
>
> > In C++, I have the following callbacks that update the scrollbar and
> > video position with a timer.
>
> [... snip callbacks ...]
>
>
>
> > I'm wondering how I would implement similar callbacks in Python for a
> > gtk.Hscale, and some sort of time [I'm not familiar with Pythons
> > timers/threading at all].
>
> You'd help your cause a lot here if you posted *Python*
> code to indicate what's calling what back where. Also if
> you stated whether you were using, eg, the GTK toolkit which
> your description suggests, or some other GUI toolkit. Because
> they tend to vary as to how they arrange their callbacks.
>
> In geeneral, Python callbacks are trivial: you create the
> function to do whatever and then pass the function as an
> object into the calling-back function call. Something
> like this (invented GUI toolkit):
>
>
> def handle_lbutton_click (event):
> #
> # do stuff with lbutton click
> #
>
> def handle_widget_slide (event):
> #
> # do stuff with widget slide
> #
>
> handle_event ("lbutton_click", handle_lbutton_click)
> widget.attach_event ("slide", handle_widget_slide)
>
>
>
> But the details will obviously depend on the toolkit you
> use.
>
> TJG
> TJG
Sorry, you make a very good point. I am using gtk. I don't have a
problem with callbacks for the gtk widgets. My question is about
timers and their callbacks. The reason I used c++ code is that
Microsoft's COM interface is natively in C++, and Python uses "import
comtypes" to access this functionality and the dll's.[ie
GetModule('quartz.dll')]
Essentially what I would like to have [as evidenced by the c++ code]
is something like the following:
def timer_callback(args):
while timer is active
update scrollbar position based on video progress
#here I am using microsoft's COM interface, so the function would
be something like
scrollbar.set_value(media_control.CurrentPosition)
def scrollbar_callback :
when the scrollbar is moved, update this video position
#this I understand. It would be something like
media_control.CurrentPosition= scrollbar.get_value()
def pauser :
media_control.Pause()
*somehow kill timer*
def player:
media_control.Run()
timer.run() #timer.run() would call timer_callback
So I would like to know how to construct and implement a timer that
would do the above, a la the first callback. In addition, the timer
has to be able to be paused/killed if I pause the video, and
implemented again if I play the video ie:
Thanks,
sayanan
--
http://mail.python.org/mailman/listinfo/python-list
Re: Docstrings for class attributes
Peter Pearson wrote: On Tue, 23 Sep 2008 15:23:35 +1000, Tom Harris <[EMAIL PROTECTED]> wrote: I want to have a class as a container for a bunch of symbolic names for integers, eg: class Constants: FOO = 1 BAR = 2 Except that I would like to attach a docstring text to the constants, so that help(Constants.FOO) will print some arbitrary string. [snip] Commiserating, not helping: I have a similar problem with a module that holds values of physical constants, http://webpages.charter.net/curryfans/peter/nature.py: boltzmanns_constant = 1.380622e-16 * erg / k stefan_boltzmann_constant = 5.66961e-5 * erg/s/cm/cm/k/k/k/k gravitational_constant = 6.6732e-8 * erg*cm/g/g I would like to reveal more details with, e.g., help( gravitational_constant ) . . . and maybe then I could use shorter names. gravitational_constant = g = 6.6732e-8 * erg*cm/g/g ... -- http://mail.python.org/mailman/listinfo/python-list
Re: python timers and COM/directshow
You're right. Let me be more specific. Firstly, the reason I
included c++ code is because I'm using Microsoft COM, which is
natively in c++, and in fact, to access them through Python I use the
comtypes module [import comtypes] and then GetModule('quartz.dll') to
access the dll's.
I am using the gtk GUI widgets. I have a gtk.Hscale scrollbar which I
would like to be a trackbar for the video playback. To coordinate
this in Python, much like in c++, I would like to have a timer thread
synchronizing the scrollbar update. ie:
def scrollbar_callback(args):
media_control.CurrentPosition= scrollbar.get_value()
def timer_callback(args):
#code to update the scrollbar based on video position, something
like
scrollbar.set_value(media_control.CurrentPosition)
>>>*And, I would like to be able to kill, run the timer based on whether the
>>>video is playing or paused, ie
def player(args):
media_control.Run() #plays video
timer.run()
def pauser(args):
media_control.Pause()
timer.kill
Any tips?
-sayanan
--
http://mail.python.org/mailman/listinfo/python-list
FREE INTERNATIONAL TRADE LEADS
http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# -- http://mail.python.org/mailman/listinfo/python-list
Re: Linq to Python
> But surely the idea behind it will eventually spread. It's really > just comprehensions generalized over XML and relational datasets, a > noble goal. Besides, it's main purpose for .NET was to bring > functional programming to it. Python already has that, somewhat... it's really any object out of the box, i think the sql linq stuff is more of a query compiler, IMO sqlalchemy does that. query = select(user_cols, and_(table_relationship.c.accept_user_id==user.id, table_relationship.c.start_date==None ), from_obj=join( table_relationship,table_user, onclause=table_user.c.id==table_relationship.c.init_user_id ).outerjoin(table_profile) ) session.execute(query).fetchall() XML? meh hopefully I would never need it. :) C# is my day job, and when I got my hands on LINQ back in January my initial thought was "Finally I have list comprehensions day job is fun again" For the most part, I think C# is catching up. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 10:57 am, Grant Edwards <[EMAIL PROTECTED]> wrote: > AFAICT, _everybody_ is bad at programming C++. Thankfully, at least Numpy developers are not bad at C programming. -- http://mail.python.org/mailman/listinfo/python-list
Re: Linq to Python
On Sep 23, 4:48 pm, hrishy <[EMAIL PROTECTED]> wrote: > Will LINQ be ported to Python ? No, because Python already has list comprehensions and we don't need the XML buzzword. -- http://mail.python.org/mailman/listinfo/python-list
Re: Linq to Python
> Will LINQ be ported to Python ? I have three suggestions: 1. When starting a new thread, start a *new* thread. Don't tack a new, unrelated subject onto an existing thread. Your post will not be seen by people with readers that collapse thread and who do not happen to read the 'Python is slow?' thread. 2. Also, give enough informaton that people can understand your question without searching the web and guessing. In particular, that do *you* mean by LINQ? The game? The .NET component? Or something else? 3. Before posting, search the Python manuals or the web a bit for an answer. If you mean the .NET component, googling 'Python LINQ' should partly answer your question. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
sturlamolden: >F# and OCaml look promising though.< I bet on the future of D and Haskell (and maybe Fortress) instead :-) We'll see. >Sure I could show you the code, Python and C++, if I had a place to post it.< I think the Python version suffices. If it's not too much private you may post the single minimal/reduced runnable Python module here, it will be deleted in some time (if you want you can also use a private paste): http://codepad.org/ >It looks very different form yours though.< Is this a good or bad thing? ;-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 8:52 pm, [EMAIL PROTECTED] wrote: > I think the Python version suffices. If it's not too much private you > may post the single minimal/reduced runnable Python module here, it > will be deleted in some time (if you want you can also use a private > paste):http://codepad.org/ http://codepad.org/rh8GzzJT Available 24 hours from now. > Is this a good or bad thing? ;-) It's just facinating how different people working on similar problems come up with different looking code. -- http://mail.python.org/mailman/listinfo/python-list
Re: Twisted: Get Protected HTTPS Page via Proxy with Authentication
This works:
# Proxy credentials
proxyAuth = base64.encodestring('%s:%s' % (proxy_username,
proxy_password))
proxy_authHeader = "Basic " + proxyAuth.strip()
# Web site credentials
basicAuth = base64.encodestring('%s:%s' % (username,
password))
authHeader = "Basic " + basicAuth.strip()
return client.getPage(url, headers={"Authorization":
authHeader, 'Proxy-Authenticate': proxy_authHeader})
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
[EMAIL PROTECTED] wrote: sturlamolden: Sure I could show you the code, Python and C++, if I had a place to post it.< I think the Python version suffices. If it's not too much private you may post the single minimal/reduced runnable Python module here, it will be deleted in some time (if you want you can also use a private paste): http://codepad.org/ You could also drop it on the scipy.org wiki in the Cookbook category. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting the first time I open/append to a file
Sean Davis a écrit : On Sep 23, 2:02 pm, [EMAIL PROTECTED] wrote: I have a simulation that runs many times with different parameters, and I want to aggregate the output into a single file with one rub: I want a header to be written only the first time. My program looks a bit like this: def main(): for param in range(10): simulate(param) def simulate(parameter): 'Lots of code followed by: with open(summaryFn, 'ab') as f: writer = csv.writer(f) writer.writerow(header) writer.writerow(Sigma) If I can sense that the file is being created in the first iteration, I can then use an if statement to decide whether or not I need to write the header. Question: how can I tell if the file is being created or if this its the first iteration? It's unrealistic to test the value of the parameter as in the real problem, there are many nested loops in main, and the bounds on the loop indices may change. You could use os.path.exists() to check if the file is there. However, the file could have been left over from a previous execution, etc. What might make sense is to open the file only once, store the file handle, and write to that throughout the execution. s/file handle/file object/ This being said, I can only second Sean's advice. And anyway, computing something and writing the result(s) of this computation to the file are orthogonal and mostly unrelated responsabilities, so they shouldn't be handled by the same function. Here's a possible reorganisation of your code: def simulate(parameter): # lots of code followed by return sigma def main(): # presumably some other code here with open(summaryFn, 'ab') as f: writer = csv.writer(f) writer.writerow(header) for param in range(10): writer.writerow(simulate(param)) -- http://mail.python.org/mailman/listinfo/python-list
Re: finding domain name
Bobby Roberts a écrit : hi group. I'm new to python and need some help and hope you can answer this question. I have a situation in my code where i need to create a file on the server and write to it. That's not a problem if i hard code the path. However, the domain name needs to be dynamic so it is picked up automatically. The path to our websites is home/sites/x/ where x represents the domain name. How can I find the domain name of the current url being viewed. What are you using exactly ? cgi ? wsgi ? Else ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 8:31 am, [EMAIL PROTECTED] wrote: Guys, this looks like a great data structure/algo for something I am working on. But... where do I find some definitions of the original BK-tree idea? I looked through Amazon and only a few books mention something like BK-Tree and these are mostly conference minutes books, at ungodly prices. I also did a quick Google on it and there isn't that much about the subject. http://blog.notdot.net/archives/30-Damn-Cool-Algorithms,-Part-1-BK-Trees.html is the one I mostly saw referred. So... 2 questions: 1. More bk-tree references? I can follow the code, but some understanding of the background would be nice. 2. What, if any, is a good book to understand the basic of fuzzy/ string matching? Proximity/affinity problems? Or, more generally, a good book on advanced algorithms? No, I don't wanna read Knuth's just yet, something more modern/easy to follow maybe? Something like 'Programming Collective Intelligence', ISBN 0596529325, would be very nice, though it is perhaps a bit too specific in its applications. Books using Java or C are fine. Lisp, hmmm, well... I have trouble reading its notation, sorry. Cheers JLuc -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Sep 23, 9:17 pm, Robert Kern <[EMAIL PROTECTED]> wrote: > You could also drop it on the scipy.org wiki in the Cookbook category. Yes, if I could figure out how to use it... -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
J Peyret wrote: On Sep 23, 8:31 am, [EMAIL PROTECTED] wrote: Guys, this looks like a great data structure/algo for something I am working on. But... where do I find some definitions of the original BK-tree idea? Uh, actually we're talking about kd-trees, not BK-trees. kd-trees are for searching through point sets in a k-dimensional space. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Docstrings for class attributes
George Sakkis wrote:
On Sep 23, 1:23 am, "Tom Harris" <[EMAIL PROTECTED]> wrote:
Greetings,
I want to have a class as a container for a bunch of symbolic names
for integers, eg:
class Constants:
FOO = 1
BAR = 2
Except that I would like to attach a docstring text to the constants,
so that help(Constants.FOO) will print some arbitrary string. Sort of
a very limited implementation of PEP 224. The only solution that I can
see is to subclass int.__new__(), since once I have an int all it's
attributes are immutable.
Here's one approach, using metaclasses and descriptors; it sort of
works, but it's less than ideal, both in usage and implementation.
George
#== usage
class MyConstants:
__metaclass__ = ConstantsMeta
FOO = const(1, 'some docs about foo')
BAR = const(2)
print MyConstants.FOO.__doc__
help(MyConstants.FOO)
print MyConstants.FOO - MyConstants.BAR
print MyConstants.FOO - 2
print 1 - MyConstants.BAR
#=== implementation ===
def ConstantsMeta(name, bases, namespace):
for name,attr in namespace.iteritems():
if isinstance(attr, const):
namespace[name] = _ConstDescriptor(name, attr.value,
attr.doc)
return type(name, bases, namespace)
class const(object):
def __init__(self, value, doc=None):
self.value = value
self.doc = doc
class _ConstDescriptor(object):
def __init__(self, name, value, doc):
cls = type(name, (), dict(
__doc__ = doc,
__add__ = lambda self,other: value+other,
__sub__ = lambda self,other: value-other,
# ...
__radd__ = lambda self,other: other+value,
__rsub__ = lambda self,other: other-value,
# XXX lots of boilerplate code for all special methods
follow...
# XXX Is there a better way ?
))
self._wrapper = cls()
def __get__(self, obj, type):
return self._wrapper
--
http://mail.python.org/mailman/listinfo/python-list
I think you get an equivalent result if you forget the descriptor
and adapt the metaclass:
def ConstantsMeta(name, bases, namespace):
for name,attr in namespace.iteritems():
if isinstance(attr, const):
cls = type(name, (type(attr.value),), {'__doc__': attr.doc})
namespace[name] = cls(attr.value)
return type(name, bases, namespace)
class const(object):
def __init__(self, value, doc=None):
self.value = value
self.doc = doc
#== usage
class MyConstants:
__metaclass__ = ConstantsMeta
FOO = const(1, 'some docs about foo')
BAR = const(2)
print MyConstants.FOO.__doc__
help(MyConstants.FOO)
print MyConstants.FOO - MyConstants.BAR
print MyConstants.FOO - 2
print 1 - MyConstants.BAR
#==
Alternatively, forget the metaclass and have:
def const(name, val, doc=None):
return type(name, (type(val),), {'__doc__': doc})(val)
#== usage
class MyConstants:
FOO = const('FOO', 1, 'some docs about foo')
BAR = const('BAR', 2)
MOO = const('MOO', 8.0, 'all about MOO')
#==
G.
--
http://mail.python.org/mailman/listinfo/python-list
Does anybody use this web framework ?
Hi, I just found this new? python web framework (http://pypi.python.org/pypi/nagare/0.1.0). Does anybody know or use it ? Regards, Phil -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is slow?
On Tue, 23 Sep 2008 11:07:22 -0700 (PDT), sturlamolden <[EMAIL PROTECTED]> wrote: >On Sep 23, 3:44 pm, Robert Singer <[EMAIL PROTECTED]> wrote: > >> Well, python is not a number crunching language. However much we would >> like it to be (we would ? :-). > >> No scripting language is. > >Not even Matlab, R, IDL, Octave, SciLab, S-PLUS or Mathematica? > No. And just to avoid eventual useless discussions which might arise, I ment to say that *in general* compiled languages are faster. We can always have discussions whether or not some newer scripting languages like some from the above list, come close, but that usually is just wasted time. Specifically, I cannot say about R, IDL or S-PLUS, since I never used those (not even heard of IDL till now). Octave and Mathematica have been with me for such a short time (we had a few licences for Wolfram's child for one year, but not my part of the company, so ...) that I would rather not give my opinion about those. I've used Matlab and Scilab for a longer time (still do actually - Matlab for measurement data acquisition, and Scilab ... well, it just sits on the disk somewhere actually), and although Matlab is quite fast when disk I/O is involved, it still comes far. >> Also, (I'm not that familiar with python yet, so I don't know how to >> do it in python), try finding the bottlenecks of your calculation. > >I did use a profiler, there is no particular single bottle-neck. You're talking about your c or your python version of the program? There is always a bottleneck - that's just the part which works most slowly. Try to find the part which takes the longest to execute, try to put it differently. If it cannot be done, go to the next slowest part. >Good compilers are too expensive, and gfortran is not good enough yet. > ? Gfortran is one of the better compilers on the market. There was, just the other day, a nice discussion on comp.lang.fortran how it is marvellous what a group of enthousiasts managed do in their time, what commercial giants still didn't. May I ask what are your main objections to it ? Best regards Bob -- http://mail.python.org/mailman/listinfo/python-list
