datetime

2012-09-13 Thread Max
How do I set the time in Python?

Also, is there any *direct* way to shift it?

Say, it's 09:00 now and Python makes it 11:30 *without* me having specified
"11:30" but only given Python the 2h30m interval.

Note that any "indirect" methods may need complicated ways to keep
track of the milliseconds lost while running them. It even took around one
second in some virtual machine guest systems. So I'm hoping Python happens to
have the magic needed to do the job for me.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extended slicing and negative stop value problem

2011-08-20 Thread Max
On Aug 20, 11:29 am, Chris Angelico  wrote:
> If you're using a variable for the stop value, you just need to set it
> to an explicit None if it would fall negative:
>
> >>> a[10:None:-1]
>

That doesn't work if it's set in a loop or if it's calculated as a
formula. For example, this very simple code doesn't work because of
the "-1 problem".

# find the longest substring that reads the same left to right and
right to left
for substr_length in range(len(input),0,-1):
for starting_pos in range(len(input)-substr_length+1):
ending_pos = starting_pos + substr_length - 1
if input[starting_pos:ending_pos+1] == input[ending_pos :
starting_pos-1 : -1]:
   print(input[starting_pos:ending_pos+1])
   exit(0)

Of course you can rewrite it, but it becomes quite ugly.

(Not to mention, people who learn the language would not always know
this, and will end up with a bug.)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extended slicing and negative stop value problem

2011-08-21 Thread Max
On Aug 20, 1:40 pm, Steven D'Aprano  wrote:
> Pardon me for breaking threading, but I don't have Max's original post.

Not sure why; I also can't see it! I'll copy it at the end just in
case.

> On Sat, Aug 20, 2011 at 7:20 PM, Max Moroz  wrote:
> > Would it be a good idea to change Python definition so that a[10, -1, -1]
>
> I presume you mean slice notation a[10:-1:-1].
>
> > referred to the elements starting with position 10, going down to the
> > beginning?
>
> If this was going to be "fixed", the time was probably
> about three years ago, when Python3 was just starting. Now such a change
> will probably need to wait for the hypothetical Python 4000.

Yeah, I was surprised that it didn't bother anyone..

> The usual advice is to do your slicing twice, reversing it the second time:
>
> a[0:11][::-1]
> # Instead of a[10:-1:-1], which looks like it should work, but doesn't.

It works nicely, but it is 1.3 times slower in my code (I am surprised
the interpreter doesn't optimize this).

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using Which Version of Linux

2005-11-06 Thread Max
[EMAIL PROTECTED] wrote:
> ok, i m going to use Linux for my Python Programs, mainly because i 
> need to see what will these fork() and exec() do. So, can anyone tell 
> me which flavour of linux i should use, some say that Debian is more 
> programmer friendly, or shold i use fedora, or Solaris. Because these 
> three are the only ones i know of that are popular and free.

Ubuntu comes with lots of Python stuff (Mark Shuttleworth, its sponsor,
really loves Python - he gave me quite a lot of money for using it). For
example, it's comes with Python scripting for the GIMP.

It uses DEB packages, which are apparently better, but software (I find)
is much easier to find in RPM format. Also, it tries to emulate a 
Windows-style file hierarchy. This is very irritating because:

a) Windows-style file hierarchy is ugly and stupid, and certainly not 
worth emulating
b) it is emulated badly.

However, this is only apparent to the user. For the programmer, it is 
pure unix. (But it does its mounts in /media instead of /mnt)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Annoying behaviour of the != operator

2005-06-23 Thread Max
Jordan Rastrick wrote:
> I don't want to order the objects. I just want to be able to say if one
> is equal to the other.
> 
> Here's the justification given:
> 
>   The == and != operators are not assumed to be each other's
>   complement (e.g. IEEE 754 floating point numbers do not satisfy
>   this).  It is up to the type to implement this if desired.
>   Similar for < and >=, or > and <=; there are lots of examples
>   where these assumptions aren't true (e.g. tabnanny).
> 
> Well, never, ever use equality or inequality operations with floating
> point numbers anyway, in any language, as they are notoriously
> unreliable due to the inherent inaccuracy of floating point. Thats
> another pitfall, I'll grant, but its a pretty well known one to anyone
> with programming experience. So I don't think thats a major use case.
> 

I think this is referring to IEEE 754's NaN equality test, which 
basically states that x==x is false if-and-only-if x.isNaN() is true.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question: Explain this behavior - a followup

2005-07-15 Thread max
David Smith <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> range statements, the example doesn't work.
> 
> Given that the beginning and ending values for the inner range
> statement are the same, the inner range statement will never be

Is your question about the semantics of for else blocks or about the 
suitability of the algorithm given in the example? The for else block 
is behaving exactly as expected...

>>> range(1,1)
[]
>>> range(500,500)
[]
>>> 

see 
http://groups-
beta.google.com/group/comp.lang.python/browse_frm/thread/d6c084e791a00
2f4?q=for+else&hl=en&

for a good explanation of when the else part of the loop is executed. 
Basically, whenever the loop is exited normally, which is what happens 
when you iterate over an empty list like the one returned by 
range(1,1)


max


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with images

2005-07-18 Thread max
"Chad" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> I have installed a TWAIN module(from
> http://twainmodule.sourceforge.net) today and figured out how to
> acquire an image.  The only problem is that the image is way too
> large in terms of filesize.  It is over 1MB.
> 
> I can do either one of two things.  Try to figure out how to
> manupilate the image with this module(which I am been doing all
> day) or just use a module that can compress jpegs.  Can anybody
> help? 
> 
> 

Check out PIL:
http://www.pythonware.com/products/pil/
http://www.pythonware.com/library/pil/handbook/


but also be sure to read the "Setting Capababilities" section of this 
document:

http://twainmodule.sourceforge.net/docs/caps.html

max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: UCALC equivalent

2005-08-12 Thread max
Larry Bates <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Python has built in eval function and doesn't require
> a library.
> 
> Larry Bates
> 

Are you kidding? Read the original post a little more closely. The 
o.p. is looking for a library that evaluates mathematical expressions 
and is callable from python code.

max
-- 
http://mail.python.org/mailman/listinfo/python-list


servers in python

2005-08-19 Thread Max
I am writing a Hashcash program in python. Rather than create an email 
client plugin, I have done this thru a proxy server which adds the 
Hashcash before forwarding.

What I want to know is whether this is safe. I currently use this code:

class HashcashServer (smtpd.PureProxy):
 def process_message (self, peer, mailfrom, rcpttos, data):
 if peer[0] in trusted_peers:
 # add Hashcash and forward
 else:
 pass

where trusted_peers is a list of peers that are allowed to use the 
service (it is currently just ["localhost"]).

Is there risk of any hacking, or of this becoming an open relay?

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Light Revisted?

2005-08-21 Thread Max
Steve M wrote:
> I agree with you in part and disagree in part.
> 
> I don't see the point to making the distribution any smaller. 10MB for
> the installer from python.org, 16MB for ActiveState .exe installer. How
> is 5MB "lightweight" while 10MB isn't? The Windows XP version of Java
> at java.com is 16+ MB, and the .NET framework is, well, I don't know
> how big, but I doubt it's much less than 10MB.
> 

AFAIR, it's closer to 50MB.

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Code run from IDLE but not via double-clicking on its *.py

2005-08-30 Thread max
"n00m" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> When I double-click on "some.py" file console window appears just
> for a moment and right after that it's closed. If this script is
> started from inside of IDLE (F5 key) then it executes as it
> should be (e.g. executing all its print statements).
> 
> Any ideas? OS: Windows; Python 2.3.4. Thanks.
> 
> 

It's a windows thing. The shell windows opens to run the script in is 
closing when the script finishes.

Try opening a shell (Start->Run: cmd.exe on NT/2k/XP or Start->Run: 
command.com on 95/98) and then either type the full path to the script 
or navigate to it and execute it.

max
-- 
http://mail.python.org/mailman/listinfo/python-list


Python scope is too complicated

2005-03-20 Thread Max
Yeah, I know. It's the price we pay for forsaking variable declarations. 
But for java programmers like me, Py's scoping is too complicated. 
Please explain what constitutes a block/namespace, and how to refer to 
variables outside of it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Pre-PEP: Dictionary accumulator methods

2005-03-20 Thread Max
Paul Rubin wrote:
Reinhold Birkenfeld <[EMAIL PROTECTED]> writes:
Any takers for tally()?
Well, as a non-native speaker, I had to look up this one in my
dictionary. That said, it may be bad luck on my side, but it may be that
this word is relatively uncommon and there are many others who would be
happier with increment.

It is sort of an uncommon word.  As a US English speaker I'd say it
sounds a bit old-fashioned, except when used idiomatically ("let's
tally up the posts about accumulator messages") or in nonstandard
dialect ("Hey mister tally man, tally me banana" is a song about
working on plantations in Jamaica).  It may be more common in UK
English.  There's an expression "tally-ho!" which had something to do
with British fox hunts, but they don't have those any more.
Has anyone _not_ heard Jeff Probst say, "I'll go tally the votes"?!
:)
--Max
--
http://mail.python.org/mailman/listinfo/python-list


Re: Refactoring a generator function

2004-12-04 Thread max
Kent Johnson <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> Here is a simple function that scans through an input file and
> groups the lines of the file into sections. Sections start with
> 'Name:' and end with a blank line. The function yields sections
> as they are found.
> 
> def makeSections(f):
>  currSection = []
> 
>  for line in f:
>  line = line.strip()
>  if line == 'Name:':
>  # Start of a new section
>  if currSection:
>  yield currSection
>  currSection = []
>  currSection.append(line)
> 
>  elif not line:
>  # Blank line ends a section
>  if currSection:
>  yield currSection
>  currSection = []
> 
>  else:
>  # Accumulate into a section
>  currSection.append(line)
> 
>  # Yield the last section
>  if currSection:
>  yield currSection
> 
> There is some obvious code duplication in the function - this bit
> is repeated 2.67 times ;-): 
>  if currSection:
>  yield currSection
>  currSection = []
> 
> As a firm believer in Once and Only Once, I would like to factor
> this out into a separate function, either a nested function of
> makeSections(), or as a separate method of a class
> implementation. Something like this:
> 
> 
> The problem is that yieldSection() now is the generator, and
> makeSections() is not, and the result of calling yieldSection()
> is a new iterator, not the section... 
> 
> Is there a way to do this or do I have to live with the
> duplication? 
> 
> Thanks,
> Kent
> 
>

This gets rid of some duplication by ignoring blanklines altogether, 
which might be a bug...

 def makeSections2(f):
currSection = []
for line in f:
line = line.strip()
if line:
if line == 'Name:':
if currSection:
yield cs
currSection = []
currSection.append(line)
if currSection:
yield currSection

but 

 def makeSections2(f):
currSection = []
for line in f:
line = line.strip()

if line:
if line == 'Name:':
if currSection:
yield currSection
currSection = []
currSection.append(line)

elif currSection:
yield currSection

if currSection:
yield currSection

should be equivalent.
-- 
http://mail.python.org/mailman/listinfo/python-list


Resticted mode still active (error?)

2005-04-06 Thread Max
I thought restricted mode had been removed from Python
but it seems to be active for Python 2.3.5 +.

I'm using the JEP product which allows integration
of Java with Python (see http://jepp.sourceforge.net) via
starting a Python interpreter in the same process as the
JVM.
This integrates with python via the C interface, allowing
the user to 'eval' python code (amongst other features).

It seems that since Python 2.3.5 any threads (using the
threading module) created via code that has been
evaluated through the jep.eval() interface (i.e.Python C
interface )are executed in restricted mode and cannot,
for example, create files. Code that is just evaled (i.e not
in a subthread) thread has no restrictions.

The error reported is:
IOError: file() constructor not accessible in restricted
mode

(see http://sourceforge.net/forum/forum.php?
thread_id=1247793&forum_id=376782) - I've given a JEP
specific example here.

There seems to be a similar problem with mod_python
(see
http://www.modpython.org/pipermail/mod_python/2005-
January/017129.html)

Reading through the release notes for Python 2.3.5
I see:
Bug #754449: threading.Thread will no longer mask
exceptions raised during interpreter shutdown with
another exception caused by attempting to output the
initial exception. This fix also includes a backport of rev.
1.41 from HEAD.

This might be the problem as it seems to involve the
porting of 2.4 threading code back to the 2.3 tree.

The error output is:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python24\Lib\threading.py", line 442, in
__bootstrap
File "", line 5, in run
IOError: file() constructor not accessible in restricted
mode

2.4.1c1 (#63, Mar 10 2005, 10:36:41) [MSC v.1310 32
bit (Intel)]
Creating file from main thread...
Done
Creating file from sub thread...
Done

Has anyone got any ideas about this?

Thanks in advance,
Max


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Resticted mode still active (error?)

2005-04-07 Thread Max
Not that I know of - the problem only seems to occur when using the Python C
API.
I'm trying to come up with a C programs that shows the error but it'll take
a few days to set up
the emvironment.


>"Jeff Epler" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to name Exceptions that aren't Errors

2005-04-07 Thread Max
Leo Breebaart wrote:
I've recently become rather fond of using Exceptions in Python to
signal special conditions that aren't errors, but which I feel
are better communicated up the call stack via the exception
mechanism than via e.g. return values.
Ummm... yeah, I quite agree.
LOOK EVERYONE, it's Leo Breebart. This guys famous in the alternative 
universe of alt.fan.pratchett.

You are the same Leo Breebart, right?
Well done, APF9 is excellent. But what did we expect.
--Max
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is unique about Python?

2005-12-23 Thread Max
gsteff wrote:
> I'm a computer science student, and have recently been trying to
> convince the professor who teaches the programming language design
> course to consider mentioning scripting languages in the future.  Along
> those lines, I've been trying to think of features of Python, and
> scripting languages in general, that can't be found in older languages,
> and have been having a surprising amount of trouble.  Dynamic typing
> can be found in Smalltalk, the module concept can be found in Ada,
> functional parameters and the dynamic creation of functions can be
> found in Lisp.  The indentation-based syntax seems to be unique, but
> that's not really what I'm looking for.  So I'm wondering, what is
> innovative about Python, either in its design or implementation?  Or is
> its magic really just in combining many useful features of prior
> languages in an unusually pleasant way?
> 
> Greg
> 

I find that development in python is much faster than anything else. But 
one of the noticeable features, for me and presumably computer science 
students, is the pseudocode-python translation: I've been working 
through a CS textbook to train for the IOI, and noticed how much my 
python implementations look like the textbook's pseudocode (whereas the 
C++ versions look nothing like the pcode).

If anything, python is _more_ expressive - where list comprehensions and 
generators are the natural way of doing things, the textbook has to 
kludge because its target audience is C++, Java and Pascal programmers.

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Enumeration idioms: Values from different enumerations

2005-12-23 Thread Max
Steven D'Aprano wrote:
> 
>>They certainly don't look much further from being integers than
>>booleans do. 
> 
> 
> You think?
> 
> hamburger, steak, fish, chicken, pizza
> 
> What meaning do you give to steak**fish? Should that meaning change if I
> happened to have written pizza first instead of last?

What meaning do you give to True**False?

> 
> The fact that they can be counted shouldn't fool you into thinking they
> are numbers. 
> 
> 
> 

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting milliseconds to human amount of time

2006-01-07 Thread Max
Harlin Seritt wrote:
> How can I take a time given in milliseconds (I am doing this for an
> uptime script) and convert it to human-friendly time i.e. "4 days, 2
> hours, 25 minutes, 10 seonds."? Is there a function from the time
> module that can do this?
> 
> Thanks,
> 
> Harlin Seritt
> 

seconds = millis / 1000 # obviously

minutes = seconds / 60
seconds %= 60

hours = minutes / 60
minutes %= 60

days = hours / 24
hours %= 24

All this using integer division, of course. This is probably much more 
verbose than the tersest soln, but it works (or should do - I haven't 
tested it). It's not strictly accurate (from a scientific/UTC 
perspective, as some minutes have 59 or 61 seconds rather than 60, but 
it's probably the best you need.

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Marshal Obj is String or Binary?

2006-01-14 Thread Max
Giovanni Bajo wrote:
>>
>>What you see isn't always what you have. Your database is capable of
>>storing \ x 0 0 characters, but your string contains a single byte of
>>value zero. When Python displays the string representation to you, it
>>escapes the values so they can be displayed.
> 
> 
> He can still store the repr of the string into the database, and then
> reconstruct it with eval:
> 

Yes, but len(repr('\x00')) is 4, while len('\x00') is 1. So if he uses
BLOB his data will take almost a quarter of the space, compared to your
method (stored as TEXT).

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is 'everything' a refrence or isn't it?

2006-01-17 Thread Max
Terry Hancock wrote:
> On Sat, 07 Jan 2006 01:29:46 -0500
> Mike Meyer <[EMAIL PROTECTED]> wrote:
> 
>>From what I can tell, Liskov proposed *three* different
>>names for
>>passing references to objects: call-by-sharing,
>>call-by-object, and call-by-object-reference.
> 
> 
> "Call by object reference" makes the most sense to me. Names
> in Python are object references: they refer to objects.  You
> might almost say "call by name" but that sort of implies
> that you are passing the strings around (which is generally
> untrue), and it doesn't convey what happens when the name is
> something complex like "ham['spam'][0].eggs()[42]" (i.e.
> "name" carries the conotation of being a simple string,
> although you could argue that it doesn't have to mean that).
> 

Except that what is passed is not "ham['spam'][0].eggs()[42]" -
that's the *name of where one copy of the objects name is*. The
name is ham['spam'][0].eggs()[42].id() - usually something like
0xBEEFBABE.

When I fill in a form (say if I applied for a visa) - three
things could happen:

a) Pass by object reference/name: I write "8x0323xx081" (my
ID number) or "Max X Rabkin" (my name) on the form, so they
know who I am.

b) Your method (pass by container reference?): I write
"The youngest male living at:
 32 Xyz Road
 Rondebosch
 Cape Town".
They know who I am, until I move house or I get a baby brother.

c) Pass by value: I staple myself to the form. Painful, but
it works. Unless I need a vaccination for the visa. Then I have
to make a copy of myself; one copy gets vaccinated while the
other is getting the visa. Unfortunately, I still can't get
into Italy, because the guy with the visa doesn't have a
vaccination and vice versa.

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


httplib.ResponseNotReady question

2006-11-13 Thread Max
Hi, Group.

I'm not a Python programmer so this question may be really basic or
stupid. :)  I have some code that sends a simple request to an
end-point and reads the response.  That works just fine.  When I put
the code in a for loop though I get httplib.ResponseNotReady error
message.  It seems to me that I cannot call the requestor.getreply()
multiple times on the same requestor object.  Anyway, here's the part
of my code that is causing the problem (I hope the format is
preserved...).

def sendRequest( msg, loops ):
requestor = httplib.HTTP(SERVER_ADDR, SERVER_PORT)
requestor.putrequest("POST", "/path/to/endpoint")
requestor.putheader("Host", SERVER_ADDR)
requestor.putheader("Content-Type", "text/xml")
requestor.putheader("Content-Length", str(len( msg ) ) )
requestor.endheaders()
for i in range(loops):
requestor.send( msg )
print "[" + str(i) + "] Message Sent  : " +
time.strftime('%H:%M:%S', time.localtime())
(status_code, message, reply_headers) = requestor.getreply()
print "[" + str(i) + "] Response Received : " +
str(status_code)
print "[" + str(i) + "] Status: " +
time.strftime('%H:%M:%S', time.localtime())
print "-[ break ]-"

If I run this with loops=1 then everything works fine.  If I use a
number greater than 1 then I get the error.  Is there a method call
that I need to restore the requestor object to a condition where it's
eligible to receive another response?

Thanks, Max

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: httplib.ResponseNotReady question

2006-11-13 Thread Max

Fredrik Lundh wrote:
> Max wrote:
>
> > If I run this with loops=1 then everything works fine.  If I use a
> > number greater than 1 then I get the error.  Is there a method call
> > that I need to restore the requestor object to a condition where it's
> > eligible to receive another response?
>
> I'm pretty sure that to get a new response from the server, you need to
> make a new request.
>
> 

I think you are right.  I found a note in the documentation that says
the connection is good for one transaction.

Thanks, Max

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python for Visual Basic or C# programmers

2006-06-01 Thread Max
Metalone wrote:

> 
> This might be a little too tricky.
> [" %d", "%d][n < 0] % n  --> selects list[0] or list[1] based upon sign
> of number
> 

("%+d" % 123).replace("+", " ") is slightly longer but instantly 
comprehensible, although I for one think your boolean indexing trick is 
cool.

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to create a cgi folder???

2006-06-01 Thread Max
elekis wrote:
> So I would like to know how to create a CGI folder ??? I installed
> apache (I m under Ubuntu-linux) php and mysql cause in a first time it
> was that I used. but...

AFAIR it's all in the apache docs. When I did my first CGI I had no web 
access (still don't on this PC), so if I managed to do it, it must have 
been in the apache docs or python docs (and I did manage).

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


if not CGI:

2006-06-01 Thread Max
I've never done anything on the web. I mean, never developed anything. 
(I've got accounts on dA and wikipedia and half-a-dozen other things; I 
know HTML and enough JavaScript to hack away at it when friends need help).

Mostly because I've never had anything worth doing: I've written a set 
of python CGI programs (an eCards site) and set up apache, just because 
I wanted to learn how. It used raw files; no database. And it sits 
there, working just about flawlessly, at http://localhost/maxecards/. 
I've even done a minor security audit, just to learn how (I met a hacker 
and he impressed me).

But now I'm ready to do it in the real world. Nothing complicated, but a 
real project. And I have to choose my tools. Zope, Plone, Django, what 
are these? I don't have to stick with Python, although it's my preferred 
language. I know Python, Java and C++. But I'm ready to learn Ruby if 
RoR is as good as they say.

I could do it in Python cgi (or mod_python). But it seems from all the 
hype that this is not a good way to write scaleable, extensible web 
applications.

There's a reason I'm asking here: I like Python. But I only learned it 
because I had incentive (3 local monetary units in the computer 
olympiad; I won 1). Is RoR incentive enough?

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: if not CGI:

2006-06-04 Thread Max
Bruno Desthuilliers wrote:
> Max a écrit :
(snip)
> 
> RoR is not bad, but really over-hyped. There's no shortage of at least 
> as good solutions in Python. You may want to look at Django, Turbogears, 
> Pylons, web.py etc. for fullstack MVC frameworks.

That's what I thought!

(snip)
> 
> So the problem is not  "are there good solutions", but "which one to 
> choose" !-) The answer of course depends on what you want and what you 
> like, but taking a few days to play with Turbogears, Django and Pylons 
> might be a good idea.

Good stuff. I'm downloading them now.


Thanks.

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie: python application on a web page

2006-06-06 Thread Max
puzz wrote:
> sorry about the missunderstanding...
> 
> but my question is "how" and not "where" to put it online
> and that's where the "newbie" comes from
> 
> P M

If you just want to make it available for download, that's easy. If you 
want to make it open source, you could upload it to 
planet-source-code.com (I used to put a lot there; don't know if they 
have a python section) or SourceForge depending on your "market".

But what I think you want is a web interface (where a user goes to your 
site and uses it in the browser window). This is more tricky, but you're 
almost certainly going to have to abandon Tkinter. You could try doing 
an applet in Jython (which compiles Python to Java bytecode so you could 
in theory do a Java-style applet).

The alternative is to have the curve drawn server-side, so you would 
have an HTML form on the page, and on clicking a button, load the graph 
(into an "iframe" or something perhaps [I have a feeling iframes have 
been deprecated - check first]). In which case you'd want to look up 
CGI, AJAX, etc.

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Printing HTML

2006-01-27 Thread Max
How can I print (as in laser printer, not the python print statement) 
HTML from Python (actually it doesn't have to be HTML - it's tabular 
data with some rows/columns highlited).

The project currently uses Python 2.4 with wxPython and pywin/winpy 
(whatever it's called, for MS Access ODBC), so if it can be done easily 
in one of those, that'd be great, but if there's a module which makes it 
a breeze, I'm happy to download that too.

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2-dimensional data structures

2006-01-27 Thread Max
Claudio Grondi wrote:
> 
> Another approach as already proposed could be, that you define your grid 
> as a dictionary in a following way:
> grid = {}
> for column in range(1,10):
>   for row in range(1,10):
> grid[(column, row)] = None
> # then you can refer to the cells of the 'array' like:
> colNo=5; rowNo=4
> valueInCellOfGrid = grid[(colNo, rowNo)]
> # and set them like:
> grid[(colNo, rowNo)] = 9
> print valueInCellOfGrid
> print grid[(colNo, rowNo)]
> 

FWIW, if you leave out the parentheses, it looks more like a genuine 2D 
array, which can be nice (actually I think it's the main advantage over 
lists of lists):

print grid[colNo, rowNo]

> 
> Claudio

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Printing HTML

2006-01-27 Thread Max
Rene Pijlman wrote:
> Max <[EMAIL PROTECTED]>:
> 
>>How can I print (as in laser printer, not the python print statement) 
>>HTML from Python 
> 
> 
> Is the printer attached to your server, or are you printing over the
> internet?
> 

I'm not sure if the printer is attached to the workstation (probably) or 
over the network, but it'll definitely be installed as one of the 
windows printers. (I guess I should have mentioned the fact that I'm 
working for windows - but I did say I was using MS Access and pywin32).

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Returning a value from code string

2006-01-28 Thread Max
Kirk McDonald wrote:
> Another kind of node (I'm still deciding
> whether to call them Codenodes or Opcodes or maybe Pynodes) is a chunk
> of code that can be asked to run itself, and which can be edited, on the 
> fly, from within the website. Thus, one can both alter the functionality 
> of the site, and add functionality, from the site itself (so long as you 
> have the user permissions to do so).
> 

As Steven said, "U R pwn3d". 1f you d0n't sp3a|< l33t (if you don't 
speak leet), that means you are screaming "hack me, use me to launch 
attacks on other computers, and than attack my computer". Unless you 
have some revolutionary ideas in code-security analysis. In which case 
you can a lot more money than from implementing Everything2 in python.

> -Kirk McDonald

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: generating method names 'dynamically'

2006-01-29 Thread Max
Magnus Lycka wrote:
> Daniel Nogradi wrote:
> 
>> Well, I would normally do what you suggest, using parameters, but in
>> the example at hand I have to have the method names as variables and
>> the reason is that the whole thing will be run by apache using
>> mod_python and the publisher handler. There a URL
>> http://something.com/program2/Bob is mapped to the 'Bob' method of the
>> file program2.py and I want to be able to have URL's with different
>> names. I know I can solve this problem with parameters and functions
>> and using the GET http method, but I would like to have pretty URL's
>> without & and ? signs. I didn't want to ask this on the mod_python
>> list because after all it's a pure python question.
> 
> 
> Ouch! This certainly seems like a possible security hole!
> 
I wouldn't think so, as long as Klass doesn't have /other/ methods - as 
long as it only has methods that are meant to be viewed externally. 
Which would probably not be the way one would ordinarily write the 
class, but if one knew one had to, one should be fine.

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: stumped by tricky logic

2006-01-29 Thread Max
Dave wrote:
> So I'm trying to write a CSS preprocessor.
> 
> I want to add the ability to append a selector onto other selectors.
> So, given the following code:
> =
> #selector {
> 
>   { property: value; property: value; }
> .other_selector   { property: value; property: value; }
> 
> #selector_2 {
> 
>  .more_selector { property: value; }
> 
> }
> 
> }

> =
> 
> I want to return the following:
> =
> #selector { property: value; property: value; }
> #selector .other_selector { property: value; property: value; }
> #selector #selector_2 .more_selector { property: value; }
> =
> 

Should the properties of #selector be "inherited" by .other_selector? 
That's what I'd think the most logical approach, but by your example it 
seems not.

> What I think I need to do is match the "{" character with its "}" pair,
> then see if there's another "{" before a matching "}" - but that's
> about as far as my brain will go. The actually code to make this
> actually happen is not coming out when I type.
> 
> Any suggestions would be very appreciated. And handsomely rewarded (by
> karma, not me).
> 

I'd use a class called Style or somesuch with three attributes:
-Selector (containing "#selector" for example)
-Props (containing the property: value pairs, either as-is or in a 
dictionary)
-Parent (containing a reference to the style that contains this one, or 
None)

Use a recursive function to read the file, and pass the containing Style 
object to it. It reads the props into the class, and recurses on any 
"sub-styles".

After this, you'll have constructed a tree (keep a reference to root). 
Now you can use an extension of a standard pre-order traversal to output it.

> - Dave
> 

Hope this helps.


--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generators vs. Functions?

2006-02-04 Thread Max
Joseph Garvin wrote:
> 
> I am not a CPython or PyPy hacker, but I would guess that it will always 
> be slower as a matter of principal. When resuming a generator you have 
> to resetup the state the function was in when it was last called, which 
> I think should always be more costly than calling the function with a 
> clean state.
> 
> Someone want to correct me?

In cases where there are thousands of (large) values to return, the list 
(as returned by the function) may be large enough to require memory 
paging, whereas the generator only returns one value at a time.

> 
> Whether or not the difference is that significant though I am unsure. It 
> may be small enough that for most applications no one cares.

I just wrote an application which retrieves values from a 300mb 
database, and got a significant speedup using iterators.

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Should we still be learning this?

2006-02-18 Thread Max
On monday I start a semester course in Python (the alternative was 
Java). I was looking through the course outline and noticed the following:

1) UserDict is used. This is deprecated, right?
2) There is no mention of list comprehensions, but map and filter are 
taught early and then revisited later. I don't think this is good: list 
comprehensions are, IMO, one of Python's great features, Psyco prefers 
them, they're more pythonic, and map and filter seem to be going out the 
window for Python 3000.

What do you think?

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Should we still be learning this?

2006-02-18 Thread Max
Felipe Almeida Lessa wrote:
> Em Sáb, 2006-02-18 às 14:38 +0200, Max escreveu:
> 
> Urgh. This sucks. Did they mention generators, at least? Sometimes list
> comprehensions are even faster (I didn't check, but I think this one can
> be an example of this: [i*2+2 for i in iterator] vs. map(lambda x: x*2
> +2, iterator)).
> 

No mention of generators in the outline.

> They should have taught both.
> 
> 
>>What do you think?
> 
> 
> I wonder if they need some updating.
> 

And so does Dive Into Python (our textbook, diveintopython.org) which 
has the same deficiencies in its outline.

> 
> Just my two cents,
> Felipe.
> 

Thanks,
Max
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Should we still be learning this?

2006-02-19 Thread Max
Felipe Almeida Lessa wrote:
> Em Sáb, 2006-02-18 às 15:13 +0200, Max escreveu:
> 
>>>I wonder if they need some updating.
>>>
>>
>>And so does Dive Into Python (our textbook, diveintopython.org) which 
>>has the same deficiencies in its outline.
> 
> 
> Are they being *paid* for teaching? Then they should overcome this issue
> of Dive Into Python by either using their own material our by improving
> Dive Into Python and giving it back to the community.
> 

Indeed they are. It is a university course. It doesn't actually cover 
anything I don't know, but it's a choice between relearning Java and 
relearning Python (since I plan to major in computer science, I have to 
do first year)

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Should we still be learning this?

2006-02-19 Thread Max
John Zenger wrote:
> Don't overly concern yourself with your course being 100% up to date. 
> When learning programming, the concepts are what is important, not the 
> syntax or libraries you happen to be using.  Even if they were to teach 
> you the latest and greatest features of 2.4.2, that would be out of date 
> in a few months/years when the next version comes along and the Python 
> gods decide to deprecate the entire os module or something.
> 

All of us know how to program: the idea is that those who got more than 
70% for Java in high school can learn a second language instead of doing 
Java all over again.

> 
> And BTW, map and filter are such useful concepts that it makes sense to 
> teach them to students even if they will one day be deprecated in 
> Python.  If you want to teach yourself Haskell or a Lisp dialect (and 
> you should!), knowing those concepts will come in very handy.
> 

True. But I think list comprehensions are also damn useful (and AFAIR, 
Haskell has them too).

I already know some Scheme (I've played the "game" Lists And Lists, a 
Scheme tutorial, and used the GIMP's script-fu). I have tried to learn 
Haskell, but - though I think I understand everything I read on it - I 
can't get my programs to run.

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


That's really high-level: bits of beautiful python

2006-02-21 Thread Max
I have a friend who has been programming in C for many years, and he is 
a great fan of the language. However, he (and I) are about to start a 
python course, and he has been asking me a lot of questions. He often 
responds to my answers with "Urgh! Object-orientation!" and suchlike.

But today we were discussing the problem of running externally-provided 
code (e.g. add-on modules). Neither of us knew how to do it in C, though 
I suggested using DLLs. However, I quickly installed python on his 
laptop and coded this:

exec "import %s as ext_mod" % raw_input("Module: ")
ext_mod.do()

And created to sample modules with do() functions to demonstrate. He was 
impressed ("That's really high-level" were his words).

I was just thinking perhaps we should create some kind of collection of 
bits of "impressive" code like this.

He also liked 99 Bottles in one line:

print '\n'.join(["%d bottles of beer on the wall." % i for i in 
range(100,0,-1)])

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Little tool - but very big size... :-(

2006-02-22 Thread Max
Giovanni Bajo wrote:
> There are also other choices that can be made. For instance, wxWidgets is
> *HUGE*.

Indeed. Remember Tkinter is built-in. (I never got the hang of Tkinter 
and prefer wx, but if size is important...)

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: anygui,anydb, any opinions?

2005-05-31 Thread max
rzed <[EMAIL PROTECTED]> wrote in news:Xns9667883C1D343jreeder@
63.223.7.253:

> So what do you think? What's wrong with the picture? Why isn't 
> there a greater priority to work in this direction?
> 

Without giving any reasons beyond intuition, I would have to say that 
it boils down to 2 things: The size and scope of gui and database 
frameworks, and the fact that opinions differ about what is 'ideal'.

max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Software licenses and releasing Python programs for review

2005-06-06 Thread max
Steven D'Aprano <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> By law, corporations (and possibly some other organisations)
> *are* people. Not natural people like you or I, but nevertheless
> people. For good or bad, this is the legal fact (or perhaps
> "legal fiction") in most countries, and not a myth.

s/myth/legal absurdity/

This is one thing that bothers me about the gpl. It essentially tries 
to create 'code as a legal entity'. That is, it gives rights not to 
the creator of some code, but to the code itself. For me, the fact 
that corporations are considered people by the law is ridiculous. 
Using a license that ends up doing the same thing with code leaves a 
bad taste in my mouth.

max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Software licenses and releasing Python programs for review

2005-06-06 Thread max
Steven D'Aprano <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> On Mon, 06 Jun 2005 16:12:18 +, max wrote:
> 
>> This is one thing that bothers me about the gpl. It essentially
>> tries to create 'code as a legal entity'. That is, it gives
>> rights not to the creator of some code, but to the code itself. 
> 
> Can you please show me where in the GPL it gives rights to the
> code itself? Because, frankly, I think you are mistaken.
> 
> Of course, I might be wrong in this instance, and I always
> welcome corrections.
> 
>> For me, the fact 
>> that corporations are considered people by the law is
>> ridiculous. 
> 
> Ridiculous? I don't think so. Take, for example, Acme Inc. Acme
> purchases a new factory. Who owns the factory? The CEO? The
> Chairperson of the Board of Directors? Split in equal shares
> between all the directors? Split between all the thousands of
> shareholders? Society has to decide between these methods.
> 
> (Of course, society can choose to hedge its bets by creating
> multiple entities that use different rules, such as partnerships,
> trusts, public corporations, limited corporations, etc.)
> 
> None of these alternatives are *wrong*, but they all have various
> disadvantages. The legal fiction that corporations are legally
> persons is a work-around for these disadvantages, and it works
> quite well in many circumstances. To call it ridiculous is, well,
> ridiculous. Ownership is a legal fiction in any case, so it is no
> more ridiculous to say that a collective entity such as a
> corporation owns property than it is to say that an individual
> being owns property. 
> 
> However, if you wanted to argue that giving corporations all the
> privileges of legal personhood with none of the responsibilities
> caused more harm than good, I would agree with you. I take it
> you've seen "The Corporation"?
> 

I haven't seen "The Corporation", but yes, I was reaching for the 
priviledges/responsibilities balance.

> 
>> Using a license that ends up doing the same thing with code
>> leaves a bad taste in my mouth.
> 
> Of course you are free to use some other licence. But without
> evidence, I do not accept that the GPL attempts to give rights to
> code. 
> 
> 
Perhaps 'attempts' is too strong a word. Maybe 'ends up giving' would 
help my argument more. The best example I can come up with at the 
moment is programmer A releases a project under the gpl. Programmer B 
makes a substantial contribution to the project, which pA reads 
through and accepts. Later, pA decides that he would like to release 
the project under a more liberal license. To me, whether he legally 
can under the gpl is a very murky subject, as pB might not agree, and 
pA, having looked through/thought about pB's contribution might have 
some trouble proving that he implemented any matching functionality 
without referencing pB's earlier contribution, which if he did 
reference it(even by memory), would presumably require him to continue 
using the gpl.

I guess my argument is that with multiple contributors, the gpl, in 
comparison to say, a BSD style license, grants power to the code. If 3 
people work on a gpl project, they must agree to any changes. If 3 
people work on a BSD style project, they each can do whatever the hell 
they like with the code. So, in my opinion, the gpl ends up giving 
perhaps not rights, but certainly power, to the actual code base.



Based on the limited coherence of this answer I probably need to think 
about it somemore,
max

-- 
http://mail.python.org/mailman/listinfo/python-list


Python Genetic Algorithm

2008-01-27 Thread Max
Hi all. I'm just getting introduced to Python (mostly through Dive
Into Python), and I've decided to use it for a project where I have to
write my own Genetic Algorithm. Even if you don't know about GAs, you
might be able to help with an issue I'm having. I'm just starting the
project off, so I'm still in the conceptual phase, and I'm stuck on
how I'm going to be able to implement something.

In GAs, you operate on a Population of solutions. Each Individual from
the Population is a potential solution to the problem you're
optimizing, and Individuals have what's called a chromosome - a
specification of what it contains. For example, common chromosomes are
bit strings, lists of ints/floats, permutations...etc. I'm stuck on
how to implement the different chromosomes. I have a Population class,
which is going to contain a list of Individuals. Each individual will
be of a certain chromosome. I envision the chromosomes as subclasses
of an abstract Individual class, perhaps all in the same module. I'm
just having trouble envisioning how this would be coded at the
population level. Presumably, when a population is created, a
parameter to its __init__ would be the chromosome type, but I don't
know how to take that in Python and use it to specify a certain class.

I'm doing something similar with my crossover methods, by specifying
them as functions in a module called Crossover, importing that, and
defining

crossover_function = getattr(Crossover, "%s_crossover" % xover)

Where xover is a parameter defining the type of crossover to be used.
I'm hoping there's some similar trick to accomplish what I want to do
with chromosomes - or maybe I'm going about this completely the wrong
way, trying to get Python to do something it's not made for. Any help/
feedback would be wonderful.

Thanks,
Max Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Genetic Algorithm

2008-01-27 Thread Max
On Jan 27, 6:35 pm, Wildemar Wildenburger
<[EMAIL PROTECTED]> wrote:
> Max wrote:
> > In GAs, you operate on a Population of solutions. Each Individual from
> > the Population is a potential solution to the problem you're
> > optimizing, and Individuals have what's called a chromosome - a
> > specification of what it contains. For example, common chromosomes are
> > bit strings, lists of ints/floats, permutations...etc. I'm stuck on
> > how to implement the different chromosomes. I have a Population class,
> > which is going to contain a list of Individuals. Each individual will
> > be of a certain chromosome. I envision the chromosomes as subclasses
> > of an abstract Individual class, perhaps all in the same module. I'm
> > just having trouble envisioning how this would be coded at the
> > population level. Presumably, when a population is created, a
> > parameter to its __init__ would be the chromosome type, but I don't
> > know how to take that in Python and use it to specify a certain class.
>
> I'm not sure I'm following you here. So a "chromosome" is bit of
> functionality, right? So basically it is a function. So my advice would
> be to write these functions and store it to the "indivuals"-list like so:
>
> class Population(object):
>  def __init__(self, *individuals):
>  self.individuals = list(individuals)
>
> Then you can say:
> p = Population(indiv1, indiv2, indiv3)
> for individual in p.individual:
>  individual(whatever_your_problem)
>
> (Don't know if this is the way GA's are supposed to work)
>
> You can also create callable classes (that is, classes that implement
> the __call__ method), and use instances of these as the individuals. For
> example you can create a Permutation class that returns a permutation
> (defined in it's __init__()) when it's __call__ method is called. (Am I
> making sense?)
>
> This is just generic advice, maybe this helps and maybe it doesn't at
> all. :)
>
> > I'm doing something similar with my crossover methods, by specifying
> > them as functions in a module called Crossover, importing that, and
> > defining
>
> > crossover_function = getattr(Crossover, "%s_crossover" % xover)
>
> > Where xover is a parameter defining the type of crossover to be used.
> > I'm hoping there's some similar trick to accomplish what I want to do
> > with chromosomes - or maybe I'm going about this completely the wrong
> > way, trying to get Python to do something it's not made for. Any help/
> > feedback would be wonderful.
>
> This isn't too bad, but for such things dictionaries are your Go-To
> datatype. Just have a dictionary of xover-functions handy and call the
> thusly:
>
> crossover_function = Crossover.function[xover]
>
> > Thanks,
> > Max Martin
>
> If that helps :)
>
> regards
> /W

This is definitely useful information, but I don't think I explained
chromosomes very well.

A chromosome is a choice of representation. So let's say your problem
is diagnosis, so a representation of a solution will be a list of
diagnoses (e.g. Disease1 = yes, Disease2 = no, Disease3 = yes, etc.).
Your chromosome choice could be a bitstring, in which the previous
solution would = 101, or it could be a list of floats to represent the
probability that you have Disease x, etc. So a chromosome is like a
choice of representation. In the case of humans, the chromosome is,
well, chromosomes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Genetic Algorithm

2008-01-27 Thread Max
On Jan 27, 7:01 pm, "Steven Clark" <[EMAIL PROTECTED]> wrote:
> Why not make chromosome itself a class?
>
> class BasicChromosome(object):
> def __init__(self, data):
> self.data = data
>
> def crossover(self):
> [stuff here]
>
> You can subclass this as needed, altering the crossover method as necessary.
>
> ...perhaps I didn't understand your question.
> -Steven
>
> On Jan 27, 2008 6:35 PM, Wildemar Wildenburger
>
> <[EMAIL PROTECTED]> wrote:
> > Max wrote:
> > > In GAs, you operate on a Population of solutions. Each Individual from
> > > the Population is a potential solution to the problem you're
> > > optimizing, and Individuals have what's called a chromosome - a
> > > specification of what it contains. For example, common chromosomes are
> > > bit strings, lists of ints/floats, permutations...etc. I'm stuck on
> > > how to implement the different chromosomes. I have a Population class,
> > > which is going to contain a list of Individuals. Each individual will
> > > be of a certain chromosome. I envision the chromosomes as subclasses
> > > of an abstract Individual class, perhaps all in the same module. I'm
> > > just having trouble envisioning how this would be coded at the
> > > population level. Presumably, when a population is created, a
> > > parameter to its __init__ would be the chromosome type, but I don't
> > > know how to take that in Python and use it to specify a certain class.
>
> > I'm not sure I'm following you here. So a "chromosome" is bit of
> > functionality, right? So basically it is a function. So my advice would
> > be to write these functions and store it to the "indivuals"-list like so:
>
> > class Population(object):
> >  def __init__(self, *individuals):
> >  self.individuals = list(individuals)
>
> > Then you can say:
> > p = Population(indiv1, indiv2, indiv3)
> > for individual in p.individual:
> >  individual(whatever_your_problem)
>
> > (Don't know if this is the way GA's are supposed to work)
>
> > You can also create callable classes (that is, classes that implement
> > the __call__ method), and use instances of these as the individuals. For
> > example you can create a Permutation class that returns a permutation
> > (defined in it's __init__()) when it's __call__ method is called. (Am I
> > making sense?)
>
> > This is just generic advice, maybe this helps and maybe it doesn't at
> > all. :)
>
> > > I'm doing something similar with my crossover methods, by specifying
> > > them as functions in a module called Crossover, importing that, and
> > > defining
>
> > > crossover_function = getattr(Crossover, "%s_crossover" % xover)
>
> > > Where xover is a parameter defining the type of crossover to be used.
> > > I'm hoping there's some similar trick to accomplish what I want to do
> > > with chromosomes - or maybe I'm going about this completely the wrong
> > > way, trying to get Python to do something it's not made for. Any help/
> > > feedback would be wonderful.
>
> > This isn't too bad, but for such things dictionaries are your Go-To
> > datatype. Just have a dictionary of xover-functions handy and call the
> > thusly:
>
> > crossover_function = Crossover.function[xover]
>
> > > Thanks,
> > > Max Martin
> > If that helps :)
>
> > regards
> > /W
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list

This is sort of what I'm trying to do. The super class would be
Individual, and subclasses would be BitStringIndividual,
IntIndividual, PermutationIndividual...etc. I just am feeling lost as
to how I'm going to implement my Population class, because when a
Population is initially created, it's going to fill itself up with
individuals by creating them, so it's going to need to know which
class it's creating instances of (which will be input when creating
the population somehow; I'm just not sure how to implement this).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Genetic Algorithm

2008-01-27 Thread Max
On Jan 27, 7:25 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sun, 27 Jan 2008 15:09:52 -0800, Max wrote:
> > Hi all. I'm just getting introduced to Python (mostly through Dive Into
> > Python), and I've decided to use it for a project where I have to write
> > my own Genetic Algorithm. Even if you don't know about GAs, you might be
> > able to help with an issue I'm having. I'm just starting the project
> > off, so I'm still in the conceptual phase, and I'm stuck on how I'm
> > going to be able to implement something.
>
> > In GAs, you operate on a Population of solutions. Each Individual from
> > the Population is a potential solution to the problem you're optimizing,
> > and Individuals have what's called a chromosome - a specification of
> > what it contains. For example, common chromosomes are bit strings, lists
> > of ints/floats, permutations...etc. I'm stuck on how to implement the
> > different chromosomes. I have a Population class, which is going to
> > contain a list of Individuals.Each individual will be of a certain
> > chromosome.
>
> Presumably all the individuals in the same population need to have the
> same kind of chromosome (differing only in the specific genes).
>
> > I envision the chromosomes as subclasses of an abstract
> > Individual class, perhaps all in the same module.
>
> How would that work? Shouldn't the different kinds of chromosomes
> (strings, lists of ints, etc.) be subclasses of an abstract Chromosome
> kind?
>
> What you need to think of is the difference between Is-A and Has-A
> relationships. An individual Has A chromosome, so you want a relationship
> something like this:
>
> class Individual(object):
> def __init__(self):
> self.chromosome = get_chromosome()
>
> On the other hand, something like a string chromosome Is A chromosome,
> and so is a list-of-ints Chromosome:
>
> class Chromosome(object):
> pass  # abstract class
>
> class StringChromosome(Chromosome):
> pass  # implement extra/different functionality
>
> class ListIntsChromosome(Chromosome):
> pass
>
> > I'm just having
> > trouble envisioning how this would be coded at the population level.
>
> There are so many ways... here's one possibility that doesn't even use a
> Population class.
>
> chromosome = StringChromosome  # the class, not an instance
> default_genes = "GATACATATGGATTAGGGACCACTAC"
> size = 100
> population = []
> for i in range(size):
> genes = chromosome(default_genes)
> genes.mutate()
> population.append(Individual(genes))
>
> I'm sure you can modify that to work on a class instance basis.
>
> > Presumably, when a population is created, a parameter to its __init__
> > would be the chromosome type, but I don't know how to take that in
> > Python and use it to specify a certain class.
>
> Just pass the class itself. For example:
>
> # Define a class.
> class Parrot(object):
> pass
>
> x = "Parrot"  # x is the NAME of the class
> y = Parrot  # y is the CLASS itself
> z = Parrot()  # z is an INSTANCE of the class
>
> You can use the class as a object, exactly the same as you can use a dict
> or a string or a float or any other object. y() will create a new Parrot
> instance exactly the same way that Parrot() would.
>
> Here's one possibility:
>
> class Population(object):
> def __init__(self, size=1000, chromosome_type=StringChromosome):
> individuals = []
> for i in xrange(size):
> genes = chromosome_type()  # create new set of genes
> x = Individual(genes)  # add them to a new individual
> individuals.append(x)  # and store it in the population
> self.individuals = individuals
>
> > I'm doing something similar with my crossover methods, by specifying
> > them as functions in a module called Crossover, importing that, and
> > defining
>
> > crossover_function = getattr(Crossover, "%s_crossover" % xover)
>
> > Where xover is a parameter defining the type of crossover to be used.
>
> The only time you need something like that is when you need to go from
> user-input (a string) to a binary object (e.g. a class, a function...).
> Suppose you read the crossover type from a text config file, or user
> input:
>
> import Crossover
> xover = raw_input("Enter a crossover type: valid values are X, Y, Z: ")
> crossover_function = getattr(Crossover, "%s_crossover" % xover)
>
> Instead of passing the string xover a

Re: Python Genetic Algorithm

2008-01-27 Thread Max
On Jan 27, 8:01 pm, "Terry Reedy" <[EMAIL PROTECTED]> wrote:
> "Max" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
> | In GAs, you operate on a Population of solutions. Each Individual from
> | the Population is a potential solution to the problem you're
> | optimizing, and Individuals have what's called a chromosome - a
> | specification of what it contains. For example, common chromosomes are
> | bit strings, lists of ints/floats, permutations...etc. I'm stuck on
> | how to implement the different chromosomes. I have a Population class,
> | which is going to contain a list of Individuals. Each individual will
> | be of a certain chromosome. I envision the chromosomes as subclasses
> | of an abstract Individual class, perhaps all in the same module. I'm
> | just having trouble envisioning how this would be coded at the
> | population level. Presumably, when a population is created, a
> | parameter to its __init__ would be the chromosome type, but I don't
> | know how to take that in Python and use it to specify a certain class.
> |
> | I'm doing something similar with my crossover methods, by specifying
> | them as functions in a module called Crossover, importing that, and
> | defining
> |
> | crossover_function = getattr(Crossover, "%s_crossover" % xover)
> |
> | Where xover is a parameter defining the type of crossover to be used.
> | I'm hoping there's some similar trick to accomplish what I want to do
> | with chromosomes - or maybe I'm going about this completely the wrong
> | way, trying to get Python to do something it's not made for. Any help/
> | feedback would be wonderful.
>
> 'Python genetic algorithm' returns 25000 hits with Google.
> But here is what I would do without looking at them.
>
> Start with the Individual base class and common methods, some virtual (not
> implemented).  An example of a virtual method would be the
> crossover(self,other) method, since its implementation depends on the
> concrete chromosome implementation.  Make subclasses with concrete
> chromosome types (initialized in .__init__).  For each, implement the
> methods that depend on that type.  In particular, the mutate(self, args)
> and crossover(self,other, args) methods.
>
> For the Population class, give  __init__ an 'individual' parameter and
> store it as an attribute.  If you want, check that it
> 'issubclass(Individual)'.  To add members to the population, call the
> stored subclass.  To operate on the population, write Population methods.
> There should not depend on the particular chromosome implementations.  To
> operate on the members within the Population methods, call their Individual
> methods.  b = a.mutate(args); c = a.crossover(b, args).
>
> I see two ways to deal with scoring the fitness of individuals within a
> Population instance.  Once is to write a particular fitness function, pass
> it to the Population init to save as an attribute, and then call as needed.
> The other is to subclass an Individual subclass, give it that funtion
> fitness method, and pass that subsubclass to Population.  The difference is
> between having Population methods calling self.fitness(some_member) versus
> some_member.fitness().
>
> I hope this is helpful for getting started.
>
> Terry Jan Reedy

Yeah, I looked up some of those GAs, but talking with people about
code helps me a lot more than looking at other code. I know it's
strange for a programmer to prefer social interaction, but...just
something about how I'm wired.

This sounds a lot like what I was thinking of doing. In particular, I
was planning on having the problem's program itself (which would
create an instance of a GA to optimize something) specify the fitness
function and pass it upwards to the population (or maybe to the GA,
which contains a population).

Thanks for the help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Genetic Algorithm

2008-01-28 Thread Max
On Jan 27, 7:25 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> Just pass the class itself. For example:
>
> # Define a class.
> class Parrot(object):
> pass
>
> x = "Parrot"  # x is the NAME of the class
> y = Parrot  # y is the CLASS itself
> z = Parrot()  # z is an INSTANCE of the class
>
> You can use the class as a object, exactly the same as you can use a dict
> or a string or a float or any other object. y() will create a new Parrot
> instance exactly the same way that Parrot() would.
>

Okay, I'm getting into the thick of things, and I want to make sure
I'm implementing this correctly. I have a module Individual.py which
contains the abstract class Individual and the class BitString. My
population __init__ takes chromosome as a parameter, and checks:

if chromosome is not issubclass(Individual):
 raise Exception("Chromosome type must be a subclass of
Individual.")

Then it creates individuals as instances of chromosome (x =
chromosome(params)). I'm pretty sure this is all right - what I'm
wondering is, when actually creating a population, would I pass
Individual.BitString as a parameter? That's what I have now.

I have similar worries about my selection scheme. Right now I have the
function rouletteWheel defined as a member of Population, so I pass
the selector to my GA class as Population.rouletteWheel (making sure I
have Population imported). I just want to ensure that this is correct.
-- 
http://mail.python.org/mailman/listinfo/python-list


Equivalent of system()?

2008-02-22 Thread Max
Is there a Python equivalent of C++'s system()?

TIA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Equivalent of system()?

2008-02-22 Thread Max
Thanks for the help!

-- 
http://mail.python.org/mailman/listinfo/python-list


no inputstream?

2008-05-15 Thread max
hey folks,

coming from java, new to python.  i'm trying to port a java app to
python that writes an inputstream to a buffer, then parses the buffer
(specifically, i'm getting ID3 tags from mp3s online).  i understand
that this java approach to the task may not apply to python, but i'm
having trouble finding a working approach in python.

i currently have locations of the mp3s in question as strings, which
works for parsing local files, but gives me a "No such file or
directory" error when it tries to process URLs.  it seems terribly
inefficient to download each mp3 just to get at that small tag data,
and i assume there's a way to do this with file() or open() or
something, i just can't get it to work.

anyone know how i can fix this?  thanks in advance for any help!

best,
max



--
http://mail.python.org/mailman/listinfo/python-list


Re: no inputstream?

2008-05-15 Thread max
On May 15, 9:51 am, castironpi <[EMAIL PROTECTED]> wrote:
> On May 15, 8:37 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>
> > On Thu, 15 May 2008 06:08:35 -0700, max wrote:
> > > i currently have locations of the mp3s in question as strings, which
> > > works for parsing local files, but gives me a "No such file or
> > > directory" error when it tries to process URLs.  it seems terribly
> > > inefficient to download each mp3 just to get at that small tag data,
> > > and i assume there's a way to do this with file() or open() or
> > > something, i just can't get it to work.
>
> > You can use `urllib2.urlopen()` to open URLs as files.  But if you deal
> > with ID3 V1 tags you'll have to download the file anyway because those are
> > in the last 128 bytes of an MP3 file.
>
> > Ciao,
> >         Marc 'BlackJack' Rintsch
>
> Just don't import time.  What would you do with an autolocking timer,
> such as time.sleep( ) on a thread?  I am tongue tied in the presence
> of a lady.

thanks guys.  i guess i just figured there'd be a way to get at those
id3 bytes at the end without downloading the whole file.  if java can
do this, seems like i should just stick with that implementation, no?
--
http://mail.python.org/mailman/listinfo/python-list


Re: no inputstream?

2008-05-15 Thread max
you're right, my java implementation does indeed parse for Id3v2
(sorry for the confusion).  i'm using the getrawid3v2() method of this
bitstream class (http://www.javazoom.net/javalayer/docs/docs0.4/
javazoom/jl/decoder/Bitstream.html) to return an inputstream that then
i buffer and parse.  apologies if i misrepresented my code!

back to python, i wonder if i'm misusing the mutagen id3 module.  this
brief tutorial (http://www.sacredchao.net/quodlibet/wiki/Development/
Mutagen/Tutorial) leads me to believe that something like this might
work:

from mutagen.mp3 import MP3
id3tags = MP3(urllib2.urlopen(URL))

but this gives me the following TypeError: "coercing to Unicode: need
string or buffer, instance found".  does this mean i need to convert
the "file-like object" that is returned by urlopen() into a unicode
object?  if so, do i just decode() with 'utf-8', or is this more
complex?  as of now, doing so gives me mostly "No such file or
directory" errors, with a few HTTP 404s.

anyway, thanks again


On May 15, 1:02 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> "John Krukoff" <[EMAIL PROTECTED]> writes:
> > I'd love to know how Java handles all that automatically through a
> > generic stream interface, though.
>
> It could be that their stream interface supports seek(), and that
> seek()ing on HTTP connection sends the appropriate range request and,
> if it fails, throws an appropriate exception which the client code
> interprets as "seeking impossible, read the whole file".
>
> But that doesn't apply to the InputStream interface described 
> athttp://java.sun.com/j2se/1.5.0/docs/api/java/io/InputStream.html-- no
> seeking there.

--
http://mail.python.org/mailman/listinfo/python-list


Re: no inputstream?

2008-05-15 Thread max
On May 15, 6:18 pm, MRAB <[EMAIL PROTECTED]> wrote:
> On May 15, 9:00 pm, max <[EMAIL PROTECTED]> wrote:
>
> > you're right, my java implementation does indeed parse for Id3v2
> > (sorry for the confusion).  i'm using the getrawid3v2() method of this
> > bitstream class (http://www.javazoom.net/javalayer/docs/docs0.4/
> > javazoom/jl/decoder/Bitstream.html) to return an inputstream that then
> > i buffer and parse.  apologies if i misrepresented my code!
>
> > back to python, i wonder if i'm misusing the mutagen id3 module.  this
> > brief tutorial (http://www.sacredchao.net/quodlibet/wiki/Development/
> > Mutagen/Tutorial) leads me to believe that something like this might
> > work:
>
> > from mutagen.mp3 import MP3
> > id3tags = MP3(urllib2.urlopen(URL))
>
> > but this gives me the following TypeError: "coercing to Unicode: need
> > string or buffer, instance found".  does this mean i need to convert
> > the "file-like object" that is returned by urlopen() into a unicode
> > object?  if so, do i just decode() with 'utf-8', or is this more
> > complex?  as of now, doing so gives me mostly "No such file or
> > directory" errors, with a few HTTP 404s.
>
> [snip]
> I think it's expecting the path of the MP3 but you're giving it the
> contents.

cool, so how do i give it the path, if not in the form of a URL
string?  maybe this is obvious...
--
http://mail.python.org/mailman/listinfo/python-list


Re: no inputstream?

2008-05-16 Thread max
On May 15, 10:31 pm, castironpi <[EMAIL PROTECTED]> wrote:
> On May 15, 6:49 pm, castironpi <[EMAIL PROTECTED]> wrote:
>
>
>
> > On May 15, 6:42 pm, John Krukoff <[EMAIL PROTECTED]> wrote:
>
> > > On Thu, 2008-05-15 at 17:32 -0600, John Krukoff wrote:
> > > > On Thu, 2008-05-15 at 17:11 -0600, John Krukoff wrote:
> > > > > On Thu, 2008-05-15 at 15:35 -0700, max wrote:
> > > > > > On May 15, 6:18 pm, MRAB <[EMAIL PROTECTED]> wrote:
> > > > > > > On May 15, 9:00 pm, max <[EMAIL PROTECTED]> wrote:
>
> > > > > > > > you're right, my java implementation does indeed parse for Id3v2
> > > > > > > > (sorry for the confusion).  i'm using the getrawid3v2() method 
> > > > > > > > of this
> > > > > > > > bitstream class (http://www.javazoom.net/javalayer/docs/docs0.4/
> > > > > > > > javazoom/jl/decoder/Bitstream.html) to return an inputstream 
> > > > > > > > that then
> > > > > > > > i buffer and parse.  apologies if i misrepresented my code!
>
> > > > > > > > back to python, i wonder if i'm misusing the mutagen id3 
> > > > > > > > module.  this
> > > > > > > > brief tutorial 
> > > > > > > > (http://www.sacredchao.net/quodlibet/wiki/Development/
> > > > > > > > Mutagen/Tutorial) leads me to believe that something like this 
> > > > > > > > might
> > > > > > > > work:
>
> > > > > > > > from mutagen.mp3 import MP3
> > > > > > > > id3tags = MP3(urllib2.urlopen(URL))
>
> > > > > > > > but this gives me the following TypeError: "coercing to 
> > > > > > > > Unicode: need
> > > > > > > > string or buffer, instance found".  does this mean i need to 
> > > > > > > > convert
> > > > > > > > the "file-like object" that is returned by urlopen() into a 
> > > > > > > > unicode
> > > > > > > > object?  if so, do i just decode() with 'utf-8', or is this more
> > > > > > > > complex?  as of now, doing so gives me mostly "No such file or
> > > > > > > > directory" errors, with a few HTTP 404s.
>
> > > > > > > [snip]
> > > > > > > I think it's expecting the path of the MP3 but you're giving it 
> > > > > > > the
> > > > > > > contents.
>
> > > > > > cool, so how do i give it the path, if not in the form of a URL
> > > > > > string?  maybe this is obvious...
> > > > > > --
> > > > > >http://mail.python.org/mailman/listinfo/python-list
>
> > > > > It doesn't look like you can, with mutagen. So, time to find a 
> > > > > different
> > > > > library that supports arbitrary file objects instead of only file 
> > > > > paths.
> > > > > I'd suggest starting here:
> > > > >http://pypi.python.org/pypi?%3Aaction=search&term=id3&submit=search
>
> > > > > Possibly one with actual documentation, since that would also be a 
> > > > > step
> > > > > up from mutagen.
>
> > > > After a bit of time looking around, looks like nearly all the python id3
> > > > modules expect to work with filenames, instead of file objects.
>
> > > > I can't vouch for it, and the documentation still looks sparse, but this
> > > > module at least looks capable of accepting a file object:
> > > >http://pypi.python.org/pypi/tagpy
>
> > > > Looks like it'd be a challenge to build if you're on windows, since it
> > > > depends on an external library.
>
> > > > Alternately, you could probably create a subclass of the mutagen stuff
> > > > that used an existing file object instead of opening a new one. No idea
> > > > what that might break, but seems like it would be worth a try.
>
> > > > As last ditch option, could write the first few kb of the file out to a
> > > > temp file and see if mutagen will load the partial file.
>
> > > Okay, now I'm officially spending too much time looking through this
> > > stuff.
>
> > > However, looks like the "load" method of the MP3 class is what you'd
> > > want to override to change mutagen's file loading behavior. Probably
> > > pass the URL as the filename, and take a cut & paste version of the
> > > default load method from ID3FileType and change it to use urllib2 to
> > > open it instead of a local file open.
>
> > > Might work. Might not. No warranty express or implied.
> > > --
> > > John Krukoff <[EMAIL PROTECTED]>
> > > Land Title Guarantee Company- Hide quoted text -
>
> > > - Show quoted text -
>
> > I'm supposed to question "time.toomuch.spend".  NAMERS!- Hide quoted text -
>
> > - Show quoted text -
>
> Is there a way 'time.toomuch.spend' can be scanned for in code?  If
> not, let's play!

really, really appreciate your help, john.  gonna have to ponder my
next move here...
--
http://mail.python.org/mailman/listinfo/python-list


HTTP basic authentication with form-based authentication

2008-08-07 Thread Max
Following the tutorial at http://personalpages.tds.net/~kent37/kk/00010.html,
I understand how to access HTTP basic authenticated pages or form-
based authenticated pages. How would I access a page protected by both
form-based authentication (using cookies) *and* HTTP basic
authentication?
--
http://mail.python.org/mailman/listinfo/python-list


Re: HTTP basic authentication with form-based authentication

2008-08-08 Thread Max
On Aug 7, 3:54 pm, Wojtek Walczak
<[EMAIL PROTECTED]> wrote:
> Dnia Thu, 7 Aug 2008 11:14:05 -0700 (PDT), Max napisa³(a):

> Use ClientCookie or even better - 
> mechanize:http://pypi.python.org/pypi/mechanize/
> The docs aren't perfect, but you should easily
> find what you are searching for.

Thank you; mechanize is perfect. The example at 
http://wwwsearch.sourceforge.net/mechanize/
provided enough information for my problem.
--
http://mail.python.org/mailman/listinfo/python-list


Re: HTTP basic authentication with form-based authentication

2008-08-08 Thread Max
On Aug 7, 3:54 pm, Wojtek Walczak
<[EMAIL PROTECTED]> wrote:
> Dnia Thu, 7 Aug 2008 11:14:05 -0700 (PDT), Max napisa³(a):

> Use ClientCookie or even better - 
> mechanize:http://pypi.python.org/pypi/mechanize/
> The docs aren't perfect, but you should easily
> find what you are searching for.

Thank you; mechanize is perfect. The example at 
http://wwwsearch.sourceforge.net/mechanize/
provided enough information for my problem.
--
http://mail.python.org/mailman/listinfo/python-list


Re: detecting drives for windows and linux

2006-03-26 Thread Max
BWill wrote:

> oh, I wasn't expecting a single solution for both platforms, just some 
> good solutions
> 
> thanks

Are you aware that this idea is somewhat foreign to Linux? (Maybe you 
are and want to do it anyway?) Linux puts the whole file system 
(including mounted iPods, ISOs and NTFS drives) in one hierarchy.

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


StringIO.readline() returns ''

2006-04-09 Thread Max
I'm using StringIO for the first time (to buffer messages recieved from 
a socket). I thought it would be a simple matter of writing the stuff to
the buffer and then calling readline, but that doesn't seem to work:

 >>> buf = StringIO.StringIO()
 >>> buf.write("Foo\n")
 >>> buf.write("Bar\n")
 >>> buf.flush()
 >>> buf.readline()
''

I expected buf.readline() to return 'Foo\n'. What am I doing wrong?

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: StringIO.readline() returns ''

2006-04-09 Thread Max
Fredrik Lundh wrote:
> you forgot to rewind the file:
> 

Thank you.

> 
> 
> 

--Max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert simple B/W graphic to the dot matrix for the LED display/sign

2012-03-04 Thread Max Erickson
Petr Jakes  wrote:

> 
>> What file format is the graphic in? How big is it?
>>
>> What file format do you want it to be?
>>
> 
> Now, I am able to create the png file with the resolution 432x64
> using PIL (using draw.text method for example).
> 
> I would like to get the 432x64 True/False (Black/White) lookup
> table from this file, so I can switch LEDs ON/OFF accordingly.
> 
> --
> Petr
> 

The convert and load methods are one way to do it:

>>> import Image
>>> im=Image.new('L', (100,100))
>>> im=im.convert('1')
>>> px=im.load()
>>> px[0,0]
0

That's the numeral one in the argument to convert. The load method 
returns a pixel access object.


Max

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: installing 2 and 3 alongside on MS Windows

2012-05-25 Thread Max Erickson
Ulrich Eckhardt  wrote:

> Hi!
> 
> I'm using Python 2.7 for mostly unit testing here. I'm using
> Boost.Python to wrap C++ code into a module, in another place I'm
> also embedding Python as interpreter into a test framework. This
> is the stuff that must work, it's important for production use.
> I'm running MS Windows XP here and developing C++ with
> VS2005/VC8. 
> 
> What I'm considering is installing Python 3 alongside, in order
> to prepare the code for this newer version. What I'd like to know
> first is whether there are any problems I'm likely to encounter
> and possible workarounds.
> 
> Thank you!
> 
> Uli
> 
> PS: Dear lazyweb, is there any way to teach VC8 some syntax
> highlighting for Python?
> 

One hassle is that .py files can only be associated with one 
program. The proposed launcher works fine for me:

https://bitbucket.org/vinay.sajip/pylauncher/downloads

(I'm not sure that is the most up to date place for the launcher, 
but that's the one I am using)


Max

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to call a function for evry 10 secs

2011-06-29 Thread Max Countryman
Yeah it won't work. Recursion depth will be reached. Steven's suggestion is 
much better.

-- 
Max Countryman
+1-917-971-8472


On Wednesday, June 29, 2011 at 2:05 PM, santosh h s wrote:

> how to end ths over a period of time
> 
> On Wed, Jun 29, 2011 at 11:25 PM, Max Countryman  (mailto:m...@me.com)> wrote:
> > How about this?
> > 
> > import time
> > 
> > def func():
> > #do stuff
> > time.sleep(10)
> > return func()
> > 
> > 
> > On Wednesday, June 29, 2011 at 1:39 PM, hisan wrote:
> > 
> > > Hi All,
> > > I need to call a function for evry 10 secs
> > > how can i achieve this in python
> > > -- 
> > > http://mail.python.org/mailman/listinfo/python-list
> > 
> 
> 
> 
> -- 
> Regards,
> Santosh

-- 
http://mail.python.org/mailman/listinfo/python-list


extended slicing and negative stop value problem

2011-08-20 Thread Max Moroz
Would it be a good idea to change Python definition so that a[10, -1, -1]
referred to the elements starting with position 10, going down to the
beginning?

This would require disabling the "negative stop value means counting from
the end of the array" magic whenever the step value is negative.

The reason for this idea is that many people (me including) try to use
extended slices with negative step values, only to realize that they are
messed up. For example, if your stop value is reduced in a loop from a
positive number to -1, the behavior breaks whenever it hits -1.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PUT with proxy-support

2011-08-25 Thread Max Countryman
Check out the python Requests module: 
http://docs.python-requests.org/en/latest/index.html

Sent from my iPhone

On Aug 25, 2011, at 7:07, Shashwat Anand  wrote:

> I want to make a PUT request.
> I need some headers of my own ( certificates etc ) and I need to mandatorily 
> use a proxy.
> Also the url is of the form http://www.xyz.com/abc and I don't have 
> permission to put data
> on http://www.xyz.com while I do have permission to put data on 
> http://www.xyz.com/abc
> 
> I tried httplib, httplib2, urllib2 with no avail.
> I managed to do this via command line curl:
> 
> $ curl http:/xyz.com/testing/shashwat/test.txt -T test.txt -H "sw-version: 
> 1.0" -H 
> "CA-Cert-Auth:v=1;a=yxyz.prod;h=10.10.0.1;t=1316594650;s=.AeEYJMMfElN74fnWD3GlXJ4J.1KiQFg--"
>  --proxy proxy.xyz.com:3128 -H "Content-Type:text/plain"
> 
> Is there a way to do it in python apart from using command line curl in 
> python.
> The machine is RHEL4 and is giving hard time installing pycurl.
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


http://DuplicateFilesDeleter.com - This software deletes duplicate files in media collection of any type

2011-04-15 Thread Max Loger
http://DuplicateFilesDeleter.com - find duplicates

http://DuplicateFilesDeleter.com is an innovative tool that can
recognize duplicate audio files even if they are stored in different
file formats and not marked with ID3 tags.

It will find fast all similar or exact duplicate audio files in a
folder and its sub folders.

Unlike common duplicate file finders it will actually "listen" to your
music and can recognize a song even if it is saved in different file
formats.

Supports MP3, MP2, MP1, MPA, WAV, OGG, AIFF, AAC, MP4, FLAC, AC3,
WavPack (WV), Musepack (MPC) and Windows Media Audio (WMA) file
formats, has an intuitive user interface and is well documented.

http://DuplicateFilesDeleter.com - find duplicates
-- 
http://mail.python.org/mailman/listinfo/python-list


Use Chrome's / Firefox's dev-tools in python

2021-05-20 Thread max pothier



My school has a website for homework called pronote (no problem if you don't 
know it). After logging in on parisclassenumerique.fr (works with selenium but 
I cant get requests to work), I want to read one of the packets that is sent: 
All the info about my day, my homework, etc. are in there and it is the perfect 
file: header request response stack trace

The file's download address looks random. The login works only for a limited 
period of time in the same browser.

Any ideas for using that tool of Firefox or same of Chrome?

Thanks!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Use Chrome's / Firefox's dev-tools in python

2021-05-21 Thread max pothier
Hello,
Thanks for you answer!
Actually my goal is not to automatically get the file once I open the page, but 
more to periodically check the site and get a notification when there's new 
homework or, at the morning, know when an hour is cancelled, so I don't want to 
have to open the browser every time.
I have pretty good javascript knowledge so if you could better explain that 
idea, it would be a great help.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Use Chrome's / Firefox's dev-tools in python

2021-05-23 Thread max pothier
Hi,
Seems like that could be a method of doing things. Just one clarification: the 
website has unselectable text, looks like it's an image strangely generated, so 
if I can get the packet with it, it would be perfect. As I said (I think), 
logging in with Selenium was already possible, and I could get a screenshot of 
the page after logging in.
If you got this working like a packet listener in browser capable of seeing 
packet data, I'd gladly accept the code.
I've tried to do this for 3 years now (since I came into that school 
basically), looks like it's coming to an end!
Thanks!
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Use Chrome's / Firefox's dev-tools in python

2021-05-23 Thread max pothier
@Curt: That is notifications for the ENT app, I want the notifications for the 
app named ProNote. ENT is for e-mails and Pronote for homework, quotes, etc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Use Chrome's / Firefox's dev-tools in python

2021-05-23 Thread max pothier
Already tried this, only works for messages and not for homework etc.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Use Chrome's / Firefox's dev-tools in python

2021-05-24 Thread max pothier
Ok,
So here's a screenshot:
https://ibb.co/2dtGr3c
1 is the website's scrollbar and 2 is Firefox's scrollbar.
Seems like it uses a strange embed thing.
The packet follows:
https://pastebin.com/2qEkhZMN
@Martin Di Paola: I sent you the pastebin password per email so that you're the 
only one who can access it, I just don't want anyone who passes by to be able 
to see my quotes...
What is that CSS tag? I could try to disable it in the inspector.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Use Chrome's / Firefox's dev-tools in python

2021-05-24 Thread max pothier
Found this:
https://pastebin.com/fvLkSJRp
with use-select tags.
I'll try to use selenium and select the page.
But using the JSON packet that's sent will still be more practical.
-- 
https://mail.python.org/mailman/listinfo/python-list


Socket.py SSM support

2019-06-01 Thread Max Franke
Hi,

as of right now there appears to be a lack of setsockoptions required to enable 
SSM, MCAST_JOIN_SOURCE_GROUP or something a kin to that in particular. Is there 
currently any effort to add those options or any other workaround to make SSM 
work in python natively? 

Best regards
Max
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Where to find python c-sources

2005-09-29 Thread Max M
Erik Max Francis wrote:
> Tor Erik Sønvisen wrote:
> 
>> I need to browse the socket-module source-code. I believe it's 
>> contained in the file socketmodule.c, but I can't locate this file... 
>> Where should I look?
> 
> The source tarball, available on python.org.  Are people really too lazy 
> to do elementary research on Google?

Don't know, have you checked Google?


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New project coming up...stay with Python, or go with a dot net language??? Your thoughts please!

2005-10-04 Thread Max M
spiffo wrote:
> The Main Issue in a nutshell
> 
> I am a corporate developer, working for a single company. Got a new project
> coming up and wondering if I should stay with Python for this new, fairly
> large project, are jump back on the 'safe' M$ bandwagon using a dot net
> language?


Hehe ...

I can run my very first Python program right now in the current version 
of Python. I cannot even find a platform to run my .asp code from that 
same timeframe ... So much for 'safe'!


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python reliability

2005-10-10 Thread Max M
Ville Voipio wrote:
> In article <[EMAIL PROTECTED]>, Paul Rubin wrote:
> 
>>I would say give the app the heaviest stress testing that you can
>>before deploying it, checking carefully for leaks and crashes.  I'd
>>say that regardless of the implementation language.
> 
> Goes without saying. But I would like to be confident (or as
> confident as possible) that all bugs are mine. If I use plain
> C, I think this is the case. Of course, bad memory management
> in the underlying platform will wreak havoc.

Python isn't perfect, but I do believe that is as good as the best of 
the major "standard" systems out there.

You will have *far* greater chances of introducing errors yourself by 
coding in c, than you will encounter in Python.

You can see the bugs fixed in recent versions, and see for yourself 
whether they would have crashed your system. That should be an indicator:

http://www.python.org/2.4.2/NEWS.html


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Windows installer, different versions of Python on Windows

2005-10-10 Thread Max M
I would like to install several copies of Python 2.4.2 on my machine, 
but it doesn't seem to be possible.

If I allready has a version installed, the installer only gives the 
options to:

- change python 2.4.2
- repair python 2.4.2
- remove python 2.4.2

I would like to install different versions of Zope 3, and since it is 
installed under a specific python version, the simplest solution would 
be to install several Python versions, and install a different zope3 
version under each python install.

Have I misunderstood something here?


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to do *args, **kwargs properly

2005-10-11 Thread Max M
Lasse Vågsæther Karlsen wrote:
> I must be missing something but what is the proper way to do a function 
> using such arguments ?

> - ability to take an unspecified number of "positional arguments"

You should probably pass a sequence to the method instead. You can do it 
the other way, but it's poor coding style in most cases.


> - ability to take optional named arguments that follows the first arguments

Setting the default value to a value that cannot exist as an argument is 
the normal way. Eg. None.

def fn(vals, cmp=None)


> - raise appropriate errors if I use the wrong named arguments

def fn(*values, cmp=None):
 if cmp is None:
 raise TypeError, "'%s' is an invalid keyword argument for this 
function" % key


If you insist on doing it the other way:

FN_LEGAL_ARGS = set( ('cmp',) )

def fn(*values, **options):
 for key in options.keys():
 if not key in FN_LEGAL_ARGS:
 raise TypeError, "'%s' is an invalid keyword argument for 
this function" % key


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to do *args, **kwargs properly

2005-10-11 Thread Max M
Lasse Vågsæther Karlsen wrote:
> Max M wrote:

> So what you're saying is that instead of:
> 
> def fn(*values, **options):
> 
> I should use:
> 
> def fn(values, cmp=cmp):
> 
> in this specific case?
> 
> and then instead of:
> 
> fn(1, 2, 3, cmp=...)
> 
> this:
> 
> fn([1, 2, 3], cmp=...)

Precisely. Sometimes you need different interfaces for a method. In that 
case it is fine.

But if you are just doing it instead of passing sequences, you are just 
(ab)using the * and ** operators.

The method definition, like any python code, is made for humans not 
machines. The more obvious you can make the function definition, the 
happier anyone will be.

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python vs Ruby

2005-10-23 Thread Max M
Mike Meyer wrote:

> There were studies done in the 70s that showed that programmers
> produced the same number of debugged lines of code a day no matter
> what language they used. So a language that lets you build the same
> program with fewer lines of code will let you build the program in
> less time.

In my experience the LOC count is *far* less significant than the levels 
of indirections.

Eg. how many levels of abstraction do I have to understand to follow a 
traceback, or to understand what a method relly does in a complex system.


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


lambda functions within list comprehensions

2005-10-29 Thread Max Rybinsky
Hello!

Please take a look at the example.

>>> a = [(x, y) for x, y in map(None, range(10), range(10))] # Just a list of 
>>> tuples
>>> a
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8,
8), (9, 9)]

Now i want to get a list of functions x*y/n, for each (x, y) in a:

>>> funcs = [lambda n: x * y / n for x, y in a]

It looks consistent!

>>> funcs
[ at 0x010F3DF0>,  at 0x010F7CF0>,
 at 0x010F7730>,  at 0x010FD270>,
 at 0x010FD0B0>,  at 0x010FD5B0>,
 at 0x010FD570>,  at 0x010FD630>,
 at 0x01100270>,  at 0x011002B0>]

...and functions are likely to be different.

>>> funcs[0](1)
81

But they aren't!

>>> for func in funcs:
... print func(1)
...
81
81
81
81
81
81
81
81
81
81

It seems, all functions have x and y set to 9.
What's wrong with it? Is it a bug?

On the other hand, this problem has a solution:

>>> def buldFunc(x, y):
... return lambda n: x * y / n
...
>>> funcs = [buldFunc(x, y) for x, y in a]

... and it does work!

But why not to save several lines of code? ;)

Thanks in advance.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda functions within list comprehensions

2005-10-29 Thread Max Rybinsky
Thank you for explanation, Alex.
It appears that almost every beginner to Python gets in trouble with
this ...feature. :)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda functions within list comprehensions

2005-10-30 Thread Max Rybinsky
OK.
The thing i've got is an obscure semantic bug, occured because of my
unawareness of the following Python "features":
1. (In major)
http://mail.python.org/pipermail/python-dev/2005-September/056508.html
2. "late" bindings of the function's body

Got to know! :)

Thanks for your attention.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda functions within list comprehensions

2005-10-30 Thread Max Rybinsky
Valid link in my previews message is

http://mail.python.org/pipermail/python-dev/2005-September/056669.html

Sorry.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sending email in utf-8?

2005-11-08 Thread Max M
morphex wrote:
> That works, kinda.  I get strange characters now like this
> 
> """
> Date: Mon, 7 Nov 2005 11:38:29 -0700 (MST)
> Message-Id: <[EMAIL PROTECTED]>
> To: [EMAIL PROTECTED], [EMAIL PROTECTED]
> From: [EMAIL PROTECTED]
> Subject:  Order confirmation
> Content-Type: text/plain; charset="utf-8"
> X-Bogosity: No, tests=bogofilter, spamicity=0.00, version=0.92.8
> 
> Thank you for your order, it is copied here for your convenience, and
> we will process it shortly.
> 
> Name:  ø
> Phone: ø
> Email:  [EMAIL PROTECTED]
> Comments:  asdf
> """
> 
> but at least it doesn't raise any errors.
> 

This is a method I have clipped from one of my projects. It should 
pretty much cover everything you would want to do while sending mails.


 def Workgroup_mailFormAction(self, to=None, cc=None, bcc=None, 
inReplyTo=None,
  subject=None, body='', 
attachments=None, mfrom=None,
  REQUEST=None):
 """
 Sends a message. Many of the input parameters are not currently 
used,
 but can be used for skinning the functionlity.
 """
 site_encoding = self._site_encoding()
 ##
 # Create the message
 msg = Message()
 msg.set_payload(body, site_encoding)
 #
 # if attachment, convert to multipart
 # file fields are posted even if empty, so we need to remove 
those :-s
 if attachments is None:
 attachments = []
 attachments = [a for a in attachments if a]
 if attachments:
 mimeMsg = MIMEMultipart()
 mimeMsg.attach(msg)
 for attachment in attachments:
 # Add the attachment
 tmp = email.message_from_string(str(attachment.headers))
     filename = tmp.get_param('filename', 'Attachment', 
'Content-Disposition')
 # clean up IE paths
 filename = filename[max(filename.rfind('/'),
 filename.rfind('\\'),
 filename.rfind(':')
)+1:]
 contentType = tmp['Content-Type']
 attach_part = Message()
 attach_part.add_header('Content-Type', contentType, 
name=filename)
 attach_part.add_header('Content-Disposition', 
'attachment', filename=filename)
 attach_part.set_payload(attachment.read())
 Encoders.encode_base64(attach_part)
 mimeMsg.attach(attach_part)
 msg = mimeMsg
 
 # set headers on message
 
 if to is None:
 to = []
 if mfrom:
 to.append(mfrom)
 msg['From'] = mfrom
 msg['Reply-To'] = mfrom
 to = ','.join(to)
 if to: msg['To'] = to
 
 if cc is None:
 cc = []
 cc = ','.join(cc)
 if cc: msg['Cc'] = cc
 
 if bcc is None:
 bcc = []
 bcc = ','.join(bcc)
 if bcc: msg['Bcc'] = bcc
 
 msg['Date'] = self.ZopeTime().rfc822() # needed by some servers
 if inReplyTo:
 msg['In-Reply-To'] = inReplyTo
 msg['Subject'] = Header(subject, site_encoding)
 ##
 # Send the message
 SMTPserver = self._mailhost()
 success = 0
 try:
 cleaner = lambda adresses: [adress.strip() for adress in 
adresses.split(',') if adress.strip()]
 all_receivers = cleaner(to) + cleaner(cc) + cleaner(bcc)
 all_receivers = list(set(all_receivers))
 if all_receivers: # only send if any recipients
 self._mailhost().send(str(msg), mto=all_receivers, 
mfrom=mfrom)
 success = 1
 except:
 pass


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: append to non-existing list

2005-11-09 Thread Max M
Yves Glodt wrote:
> bruno at modulix wrote:
> 
>> Yves Glodt wrote:
>>
>>> Hello,
>>>
>>> if I do this:
>>>
>>> for row in sqlsth:
>>> pkcolumns.append(row[0].strip())
>>> etc
>>>
>>>
>>> without a prior:
>>>
>>> pkcolumns = [];
>>>
>>>
>>> I get this error on first iteration:
>>> UnboundLocalError: local variable 'pkcolums' referenced before 
>>> assignment
>>>
>>>
>>> I guess that's normal as it's the way python works...?!?


Well you could do something like this. (Untested and unrecommended)

 self.__dict__.setdefault('pkcolumns', []).append(row[0].strip())

Personally I find

 pkcolumns = []
 pkcolumns .append(row[0].strip())

to be nicer ;-)

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython newbie question, creating "mega widgets" , and DnD

2005-11-10 Thread Max Erickson
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote in
news:[EMAIL PROTECTED]: 

> A side question - why is their a EVT_LIST_BEGIN_DRAG but no
> EVT_LIST_END_DRAG, unlike tree's which have BEGIN and END?  I
> need a draggable list box, and would prefer to not handle low
> level mouse events.

My intuition(so take it with a grain of salt) says that it wouldn't 
make any sense for the list control to generate an event when the drag 
and drop lands on a different control.

max
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tutorial example

2005-11-11 Thread Max Erickson
>>> import math
>>> def distance1(x1, y1, x2, y2): 
   dx = x2 - x1 
   dy = y2 - y1 
   dsquared = dx**2 + dy**2 
   result = math.sqrt(dsquared) 
   print result
   return result

>>> def distance2(x1, y1, x2, y2): 
   dx = x2 - x1 
   dy = y2 - y1 
   dsquared = dx**2 + dy**2 
   result = math.sqrt(dsquared) 
   print result

 
They don't do the same thing here...
  
>>> distance1(1,2,3,4)
2.82842712475
2.8284271247461903
>>> distance2(1,2,3,4)
2.82842712475


the 'return result' line passes the result object in the function 
back to where the function was called. Functions without a return 
statement  default to returning 'None'. Calling the functions within 
a print statement illustrates the difference:

>>> print distance1(1,2,3,4)
2.82842712475
2.82842712475
>>> print distance2(1,2,3,4)
2.82842712475
None
>>> 

As you can see, distance2 does not actually return the result of the 
calculation to the interactive prompt...

max

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tutorial example

2005-11-12 Thread Max Erickson

Not in python.

For example, what would you call the following?

def rsum(n, m):
print n+m
return n+m


In python a method is callable attached to an object. A function is a 
callable object constructed with a def statement.

max

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Midi Package: writing events non-chronologically

2005-11-24 Thread Max M

tim wrote:
Someone using Python Midi Package from 
http://www.mxm.dk/products/public/ lately?


I want to do the following :
write some note events in a midi file
then after doing that, put some controllers at the beginning of the 
midifile
(because I want to be able to make those dependant on what notes were 
just written)


def midctrls():
   global roffset, melchan, roffset, gmt, timedisplay, out_file, midi, 
usednotes, n

   midi.reset_time()  #seems to do nothing
   for cha in range(16):
   if cha==1:
   midi.abs_time=0   #seems to do nothing
   midi._relative_time = 0   #seems to do nothing, but I can 
imagine why

   midi._absolute_time = 0   #seems to do nothing
   midi.update_time(new_time=0, relative=0)  #although I give 
the variable relative=0 it seems to be relative ?

   midi.continuous_controller(cha, 0, 122)
(snip)

With this code I want a controller number 0 with value 122 to be written 
at the beginning of my midifile.

It is written at the end, how I move the writing position to the beginning?




You should make a wrapper around the library that handles the midi 
events in a data structure.


When your musical structure is then is complete, you use the midi 
library to write it to disk.


I have attached a simple example here.

--

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
# event classes. Only used internally by notes2midi
class NoteOn:

def __init__(self, time=0, pitch=64, velocity=64):
self.time = time
self.pitch = pitch
self.velocity = velocity

def __str__(self):
r = []
a = r.append
a('NoteOn')
a('time %s' % self.time)
a('pitch %s' % self.pitch)
a('velocity %s' % self.velocity)
return '\n'.join(r)

def render(self, channel, mididevice):
"Writes the event to a midi stream"
mididevice.note_on(channel=channel, note=self.pitch, 
velocity=self.velocity)



class NoteOff:

def __init__(self, time=0, pitch=64, velocity=64):
self.time = time
self.pitch = pitch
self.velocity = velocity

def __str__(self):
r = []
a = r.append
a('NoteOff')
a('time %s' % self.time)
a('pitch %s' % self.pitch)
a('velocity %s' % self.velocity)
return '\n'.join(r)

def render(self, channel, mididevice):
"Writes the event to a midi stream"
mididevice.note_off(channel=channel, note=self.pitch, 
velocity=self.velocity)




def notes2midi(notes, midi):
"Turns a list of notes into a midi stream"
# notes have absolute time values!!!

# first turn notes into events (split into note-on / note-off)
events = []
for note in notes:
on_event = NoteOn(note.time, note.pitch, note.velocity)
events.append(on_event)
off_event = NoteOff(note.time+note.duration, note.pitch, note.velocity)
events.append(off_event)
# sort them in order of time
events.sort(lambda x,y: cmp(x.time, y.time))

# midi device writing
# non optional midi framework
midi.header()
midi.start_of_track()
midi.reset_time()
absolute_time = 0
for event in events:
delta_time = event.time - absolute_time
absolute_time = event.time
# write the data
midi.update_time(delta_time)
event.render(0, midi)
midi.end_of_track()
# non optional midi framework
midi.update_time(0)
midi.end_of_track()

midi.eof()


if __name__ == '__main__':

from Pattern import Note

# a short example using notes, with no limits to number of simultaneous 
voices
# creates a list of ascending notes
track = [
Note(time=24*i, pitch=64+i, velocity=127, duration=24)
for i in range(16)
]


##
# write the notes to the file

from midi.MidiOutFile import MidiOutFile

out_file = 'note-test.mid'
midi = MidiOutFile(out_file)
notes2midi(track, midi)
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Newbie question - clearing screen @ interactive prompt

2005-12-09 Thread Max Ischenko
Well, you can run any system command from within Python as well:

import os
os.system('clear')

But I'm not sure this will help in this case. Are you trying to program
a console app in Python?  If so, you may want to look into curses
module or other console lib that  has Python bindings (like newt).

http://docs.python.org/lib/module-curses.html

HTH,
Max // http://max.textdriven.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling Function Without Parentheses!

2005-01-02 Thread Max M
Kamilche wrote:
What a debug nightmare! I just spent HOURS running my script through
the debugger, sprinkling in log statements, and the like, tracking down
my problem.
I called a function without the ending parentheses. I sure do WISH
Python would trap it when I try to do the following:
MyFunc

Actually you want use a method as an ordinary variable without calling 
it in many cases. It is often used in a dynamic language.

A simple example is:
result = []
a = result.append
if something:
 a('some result')
elif something_else:
 a('another result')
else:
 a('default result')
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: csh to Python

2005-01-04 Thread Max M
Nader Emami wrote:
Hello,
I am new in Python world, and would like to begin with
translate a csh file to a python script. Could somebody give
me an advise (documentation or web-site) where I can do that.

You are probably interrested in the os 6 os.path modules.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)

2005-01-04 Thread Max M
[EMAIL PROTECTED] wrote:
uhm ... then there is a misprint in the discussion of the recipe;
BTW what's the difference between .encode and .decode ?
(yes, I have been living in happy ASCII-land until now ... ;)

# -*- coding: latin-1 -*-
# here i make a unicode string
unicode_file = u'Some danish characters æøå' #.encode('hex')
print type(unicode_file)
print repr(unicode_file)
print ''
# I can convert this unicode string to an ordinary string.
# because æøå are in the latin-1 charmap it can be understood as
# a latin-1 string
# the æøå characters even has the same value in both
latin1_file = unicode_file.encode('latin-1')
print type(latin1_file)
print repr(latin1_file)
print latin1_file
print ''
## I can *not* convert it to ascii
#ascii_file = unicode_file.encode('ascii')
#print ''
# I can also convert it to utf-8
utf8_file = unicode_file.encode('utf-8')
print type(utf8_file)
print repr(utf8_file)
print utf8_file
print ''
#utf8_file is now an ordinary string. again it can help to think of it 
as a file
#format.
#
#I can convert this file/string back to unicode again by using the 
decode method.
#It tells python to decode this "file format" as utf-8 when it loads it 
onto a
#unicode string. And we are back where we started

unicode_file = utf8_file.decode('utf-8')
print type(unicode_file)
print repr(unicode_file)
print ''
# So basically you can encode a unicode string into a special 
string/file format
# and you can decode a string from a special string/file format back 
into unicode.

###

u'Some danish characters \xe6\xf8\xe5'

'Some danish characters \xe6\xf8\xe5'
Some danish characters æøå

'Some danish characters \xc3\xa6\xc3\xb8\xc3\xa5'
Some danish characters æøå

u'Some danish characters \xe6\xf8\xe5'


--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)

2005-01-04 Thread Max M
Thomas Heller wrote:
It seems also the error messages aren't too helpful:
"ä".encode("latin-1")
Traceback (most recent call last):
  File "", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x84 in position 0: ordinal 
not in range(128)
Hm, why does the 'encode' call complain about decoding?
Because it tries to print it out to your console and fail. While writing 
to the console it tries to convert to ascii.

Beside, you should write:
u"ä".encode("latin-1") to get a latin-1 encoded string.
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   4   5   6   7   8   9   10   >