Re: Changing size of Win2k/XP console?

2005-07-14 Thread Jason Drew
SetConsoleWindowInfo looks like a better candidate. See
http://tinyurl.com/budzk
(I.e.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/setconsolewindowinfo.asp)

Haven't tried it though. Good luck!

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


Re: tuple to string?

2005-07-22 Thread Jason Drew
''.join((chr(e) for e in (0x73, 0x70, 0x61, 0x6D)))

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


Re: retrieve data from 2 database

2005-07-28 Thread Jason Drew
For a start, asking a better question will get better answers:
http://www.catb.org/~esr/faqs/smart-questions.html

Googling for python odbc gives this as the first result:
http://www.python.org/windows/win32/odbc.html

In general, how you compare database tables will depend a lot on the
nature of the tables: e.g. are you comparing names to names, rows to
rows, apples to oranges, etc.?

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


Re: Hiding

2005-07-29 Thread Jason Drew
Well, using the open function in Python doesn't launch any application
associated with the file (such as Media Player). It just makes the
contents of the file accessible to your Python code. Also, I think
using file("C:\file.txt") is now preferred to open("C:\file.txt").

To answer the specific question of how to play a music file in Python,
search Google Groups for: pygame.mixer.music.load("music.mp3")
That will bring up a useful thread. Note that you will need to install
a module such as pygame or pymedia; they are not in the standard
library.

In general, I would also recommend some of the many good Python
tutorials. Some are listed here:
http://wiki.python.org/moin/BeginnersGuide

Good luck!

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


Re: Hiding

2005-08-01 Thread Jason Drew
Ah, good point, thanks. Must stop forgetting that "C:\file.txt" is bad.

The whole open()/file() clairification is useful too. The Python docs
for the file() constructor simply state that, "File objects ... can be
created with the built-in constructor file() described in section 2.1,
'Built-in Functions.'"
(http://python.org/doc/2.4.1/lib/bltin-file-objects.html)

That's followed by a footnote that states, "file() is new in Python
2.2. The older built-in open() is an alias for file()."

At first sight, that to me suggests that open() has been somewhat
deprecated by file().

However, the description of many of the file methods on the same page
refers to opening files using open(), e.g.:
"mode:  The I/O mode for the file. If the file was created using the
open() built-in function, this will be the value of the mode
parameter."

It all becomes relatively clear in section 2.1, "Built-in Functions"
where the entry for file() states, "The file() constructor is new in
Python 2.2 and is an alias for open(). Both spellings are equivalent.
The intent is for open() to continue to be preferred for use as a
factory function which returns a new file object. The spelling, file is
more suited to type testing (for example, writing 'isinstance(f,
file)')."

I guess that clears it up. Though perhaps the Python doc for the file()
constructor should add that open() is the preferred general-purpose way
to open a file or file-like object?

Thanks again

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


Re: Documentation

2005-08-10 Thread Jason Drew
The standard pydoc module is very useful. A simple example of how you
could use it:

>>> import pydoc
>>> mymodule = pydoc.importfile(r"C:\My Py\my_foo.py")
>>> html = pydoc.html.page(pydoc.describe(mymodule), 
>>> pydoc.html.document(mymodule))
>>> open("foo.html", "w").write(html)

Then you have a nice foo.html document for your module.

The above isn't necessarily the best way to use pydoc though it's
useful for a single-file bunch of classes. The documentation on pydoc
seems pretty sketchy, but reading the pydoc.py file is a good way to
learn how to use it.

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


Re: What is Python?!

2005-08-10 Thread Jason Drew
Roy Smith wrote: "there's a system called Jython, which lets you
compile Java source to Python byte code."

Don't you have that the wrong way 'round? From the Jython website:
"Jython is an implementation of the high-level, dynamic,
object-oriented language Python written in 100% Pure Java, and
seamlessly integrated with the Java platform. It thus allows you to run
Python on any Java platform."

In the case of Jython you could perhaps say that Python bytecode is
"exactly like Java". However, in the case of regular Python, it's
closer to say that Python bytecode is much the same _idea_ as Java
bytecode.

Jason

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


Re: Sorta noob question - file vs. open?

2005-08-23 Thread Jason Drew
Both your code snippets above work should work OK. If it seems like a
file isn't being written, maybe you should specify its full path so you
are sure about where to check for it.

On the file-or-open question, the Python docs state, "The intent is for
open() to continue to be preferred for use as a factory function which
returns a new file object."

I happen to know that because it was clarified for me recently by a few
posters in this informative thread:
http://groups.google.com/group/comp.lang.python/browse_frm/thread/fbc7fbacf0866763
(which didn't start out as a file-or-open discussion, but there you
go).

Hope this helps,
Jason

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


Re: converting sqlite return values

2006-02-20 Thread Jason Drew
Hi,

You can use the built-in function "eval" to return how Python evaluates
your string. For example:
>>> eval( '(1,2,3,4)' )
(1, 2, 3, 4)

In other words, eval will take your string that looks like a tuple, and
return an actual tuple object.

Note that the 'u' prefix in your string will cause an error if you pass
it to eval, so you should drop that, e.g.:
>>> utuple = 'u(1,2,3,4)'
>>> eval( utuple[1:] )
(1, 2, 3, 4)

In general, though, converting your strings/tuples back and forth like
this might not be the best idea, depending on the situation. If the
numbers represent consistent items, like (price, tax, code, quantity),
then you would do better to use a field for each item in your database
and insert/fetch the numbers appropriately.

Storing whole Python objects in single database fields isn't unheard
of, but in general you should only do it when you really need to do it.
When you do, there are various Python modules to help, though I haven't
used this approach much myself.

Jason

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


Re: How to move optparse from main to function?

2006-02-23 Thread Jason Drew
As pointed out, the module documentation is helpful.

For your 'test' option, I don't think 'action="count"' is the best
action. 'Test' is basically an on/off option, so why count it? I would
use:

parser.add_option("-t", "--test", action="store_true",
dest="optparse_test", default=False, help="testing optparse")

Then your code can use
if options.optparse_test == True: ...
or briefer:
if options.optparse_test: ...


As for putting the optparse code into a function, I sometimes use:

def parserSetup():
"""Return a configured option parser for this program."""
parser = OptionParser()
parser.add_option( ... your option stuff ... )
parser.add_option( ... )
return parser

if __name__=="__main__":
parser = parserSetup()
(options, args) = parser.parse_args()
# Then in your case:
if options.optparse_test: ...

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


Re: How to move optparse from main to function?

2006-02-24 Thread Jason Drew
You're welcome!

As usual, each of us is free to write the code whichever way works best
for the particular problem at hand. That's why the module documentation
often avoids advocating here-is-the-one-best-way-to-do-it.  I just like
sticking all the option setup stuff in a single function because it's
conceptually all the same and it makes the main() function or whatever
read shorter. It's partly down to experience, what little of it I can
claim.

Good luck!

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


Re: CGI on Windows

2005-05-16 Thread Jason Drew
I believe you're experiencing a bug that I also encountered, and for
which there is a patch. See:
http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1110478

Fixing os.py as described in the patch fixed all my CGI-related
problems. Hope it does for you too!

Jason

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


Re: CGI on Windows

2005-05-16 Thread Jason Drew

Rainer Mansfeld wrote:
> Jason Drew wrote:
> > I believe you're experiencing a bug that I also encountered, and
for
> > which there is a patch. See:
> >
http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=detail&aid=1110478
> >
> > Fixing os.py as described in the patch fixed all my CGI-related
> > problems. Hope it does for you too!
> >
> > Jason
> >
>
> It did!
>
> Thanks a lot Jason.
> You just saved my mental health.
>
>Rainer


You're welcome! (And thanks too to June Kim and Martin v. Löwis for
posting and fixing the bug, respectively, I think.)

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


Re: Convert from numbers to letters

2005-05-19 Thread Jason Drew
It seems strange to want to set the values in actual variables: a, b,
c, ..., aa, ab, ..., aaa, ..., ...

Where do you draw the line?

A function seems more reasonable. "In terms of lines of code" here is
my terse way of doing it:

nrFromDg = lambda dg: sum(((ord(dg[x])-ord('a')+1) * (26 **
(len(dg)-x-1)) for x in xrange(0, len(dg

Then, for example
nrFromDg("bc")
gives
55
and
nrFromDg("aaa")
gives
703
and so on for whatever you want to evaluate.

This is efficient in terms of lines of code, but of course the function
is evaluating ord("a") and len(dg) multiple times, so it's not the most
efficient in terms of avoiding redundant calculations. And
nrFromDg("A") gives you -31, so you should really force dg into
lowercase before evaluating it. Oh, and it's pretty hard to read that
lambda expression.

"Least amount of code" == "best solution"
False

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


Re: Convert from numbers to letters

2005-05-19 Thread Jason Drew
We weren't really backwards; just gave a full solution to a half-stated
problem.

Bill, you've forgotten the least-lines-of-code requirement :-)

Mine's still a one-liner (chopped up so line breaks don't break it):

z = lambda cp: (int(cp[min([i for \
i in xrange(0, len(cp)) if \
cp[i].isdigit()]):])-1,
sum(((ord(cp[0:min([i for i in \
xrange(0, len(cp)) if \
cp[i].isdigit()])][x])-ord('A')+1) \
* (26 ** (len(cp[0:min([i for i in \
xrange(0, len(cp)) if \
cp[i].isdigit()])])-x-1)) for x in \
xrange(0, len(cp[0:min([i for i in \
xrange(0, len(cp)) if \
cp[i].isdigit()])]-1)

print z("B14")
# gives (13, 1)

Maybe brevity isn't the soul of wit after all ...

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


Re: Convert from numbers to letters

2005-05-19 Thread Jason Drew
Oh yeah, oops, thanks. (I mean the line continuations, not the alleged
sin against man and nature, an accusation which I can only assume is
motivated by jealousy :-) Or fear? They threw sticks at Frankenstein's
monster too. And he turned out alright.

My elegant "line" of code started out without the enclosing
parentheses; forgot I didn't need the \s when I embraced it.

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


Re: Convert from numbers to letters

2005-05-20 Thread Jason Drew
Er, yes! It's REALLY ugly! I was joking (though it works)! I retract it
from the code universe. (But patent pending nr. 4040404.)

Here's how I really would convert your (row_from_zero, col_from_zero)
tuple to spreadsheet "A1" coords, in very simple and easy to read code.

##def tuple2coord(tupl):
##def colnr2digraph(colnr):
##if colnr <= 26:
##return chr(ord('A') + colnr-1)
##m = colnr % 26
##if m == 0:
##m = 26
##h = (colnr - m) / 26
##return colnr2digraph(h) + colnr2digraph(m)
##
##rowfromzero, colfromzero = tupl
##row = rowfromzero+1
##col = colfromzero+1
##return colnr2digraph(col) + str(row)
##
##print tuple2coord((13,702))
### gives AAA14
### (because the tuple counts rows and columns from zero)

Note that this allows column nrs of any size, not just up to "ZZ". If
you really know the column limit is ZZ, then a lookup dictionary would
be a more efficient speed-wise solution. (Though I'd still use my nice
recursive no-brainer colnr2digraph function to populate the
dictionary.)

P.S. the line that says
h = (colnr - m) / 26
could really, in current Python, be just
h = colnr / 26
but the former is more language- and future-neutral.

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


Re: Convert from numbers to letters

2005-05-20 Thread Jason Drew
Sorry, scratch that "P.S."! The act of hitting Send seems to be a great
way of realising one's mistakes.

Of course you need colnr - m for those times when m is set to 26.
Remembered that when I wrote it, forgot it 2 paragraphs later!

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


Re: Convert from numbers to letters

2005-05-20 Thread Jason Drew
Hey, that's good. Thanks Steve. Hadn't seen it before. One to use.

Funny that Pythonwin's argument-prompter (or whatever that feature is
called) doesn't seem to like it.

E.g. if I have
def f(tupl):
print tupl

Then at the Pythonwin prompt when I type
f(
I correctly get "(tupl)" in the argument list pop-up box.

But if I have
def f((a, b)):
print a, b

then when I type
f(
I just get "(.0)" in the argument list pop-up box.

Or with
def f(p, q, (a, b)):
pass
Pythonwin prompts with
"(p, q, .4)"


However in each case the help() function correctly lists all the
arguments. Strange. I'll check if it's a known "feature".

This is with
"PythonWin 2.4 (#60, Feb  9 2005, 19:03:27) [MSC v.1310 32 bit (Intel)]
on win32."

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


Re: Lists in classes

2007-07-12 Thread Jason Drew
Thanks for clearing up the other incorrect answers! In true Python
fashion, I would also remind everyone of the *documentation* - in
particular the Python tutorial. These are very elementary mistakes to
be making - even worse as part of attempted answers.

The Python tutorial is at http://docs.python.org/tut/tut.html

In particular see the section on classes: http://docs.python.org/tut/node11.html

Note however that the tutorial doesn't show the current best practice
of subclassing your classes from "object", i.e.
class MyClass(object):
   #...etc...

-Jason

On Jul 12, 11:51 am, Wildemar Wildenburger <[EMAIL PROTECTED]>
wrote:
> Bart Ogryczak wrote:
> > On 12 jul, 17:23, Jeremy  Lynch <[EMAIL PROTECTED]> wrote:
>
> >> Hello,
>
> >> Learning python from a c++ background. Very confused about this:
>
> >> 
> >> class jeremy:
> >> list=[]
>
> > You've defined list (very bad choice of a name, BTW), as a class
> > variable. To declare is as instance variable you have to prepend it
> > with "self."
>
> Ouch!
>
> 'self' is *not* a reserved ord in python, it doesn't do anything. So
> just popping 'self' in front of something doesn't bind it to an instance.
> Here is how it works:
>
> class Jeremy(object):  # you better inherit from 'object' at all times
> classlist = []  # class variable
> def __init__(self):  # "constructor"
> self.instancelist = []  # instance variable
> def add_item(self, item):
> self.instancelist.append(item)
>
> 'self' is the customary name for the first argument of any instance
> method, which is always implicitly passed when you call it. I think it
> translates to C++'s 'this' keyword, but I may be wrong. Simply put: The
> first argument in an instance-method definition (be it called 'self' or
> otherwise) refers to the current instance.
> Note however that you don't explicitly pass the instance to the method,
> that is done automatically:
>
> j = Jeremy()  # Jeremy.__init__ is called at this moment, btw
> j.add_item("hi") # See? 'item' is the first arg you actually pass
>
> I found this a bit confusing at first, too, but it's actually very
> clean, I think.
> /W


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


Re: simple regular expression problem

2007-09-17 Thread Jason Drew
You just need a one-character addition to your regex:

regex = re.compile(r'', re.S)

Note, there is now a question mark (?) after the .*

By default, regular expressions are "greedy" and will grab as much
text as possible when making a match. So your original expression was
grabbing everything between the first opening tag and the last closing
tag. The question mark says, don't be greedy, and you get the
behaviour you need.

This is covered in the documentation for the re module.
http://docs.python.org/lib/module-re.html

Jason

On Sep 17, 9:00 am, duikboot <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I am trying to extract a list of strings from a text. I am looking it
> for hours now, googling didn't help either.
> Could you please help me?
>
> >>>s = """ 
> >>>\n\n28996\n\n\n28997\n"""
> >>> regex = re.compile(r'', re.S)
> >>> L = regex.findall(s)
> >>> print L
>
> ['organisatie>\n28996\n
> \n\n28997\n
> I expected:
> [('organisatie>\n28996\n
> \n), (\n28997\n organisatie')]
>
> I must be missing something very obvious.
>
> Greetings Arjen


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


Re: simple regular expression problem

2007-09-17 Thread Jason Drew
You're welcome!

Also, of course, parsing XML is a very common task and you might be
interested in using one of the standard modules for that, e.g.
http://docs.python.org/lib/module-xml.parsers.expat.html

Then all the tricky parsing work has been done for you.

Jason


On Sep 17, 9:31 am, duikboot <[EMAIL PROTECTED]> wrote:
> Thank you very much, it works. I guess I didn't read it right.
>
> Arjen
>
> On Sep 17, 3:22 pm, Jason Drew <[EMAIL PROTECTED]> wrote:
>
> > You just need a one-character addition to your regex:
>
> > regex = re.compile(r'', re.S)
>
> > Note, there is now a question mark (?) after the .*
>
> > By default, regular expressions are "greedy" and will grab as much
> > text as possible when making a match. So your original expression was
> > grabbing everything between the first opening tag and the last closing
> > tag. The question mark says, don't be greedy, and you get the
> > behaviour you need.
>
> > This is covered in the documentation for the re 
> > module.http://docs.python.org/lib/module-re.html
>
> > Jason
>
> > On Sep 17, 9:00 am, duikboot <[EMAIL PROTECTED]> wrote:
>
> > > Hello,
>
> > > I am trying to extract a list of strings from a text. I am looking it
> > > for hours now, googling didn't help either.
> > > Could you please help me?
>
> > > >>>s = """ 
> > > >>>\n\n28996\n\n\n28997\n"""
> > > >>> regex = re.compile(r'', re.S)
> > > >>> L = regex.findall(s)
> > > >>> print L
>
> > > ['organisatie>\n28996\n
> > > \n\n28997\n
> > > I expected:
> > > [('organisatie>\n28996\n
> > > \n), (\n28997\n > > organisatie')]
>
> > > I must be missing something very obvious.
>
> > > Greetings Arjen


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


Re: greatest and least of these...

2007-10-23 Thread Jason Drew
What do you mean when you say the menu doesn't kick in? Do you get an
exception, or does simply nothing happen?

Before the if statements, you should put "print choice" so you can see
what value is being returned by the input function. Also maybe "print
type(choice)" for a bit more inspection.

Speaking of which, you should probably be using something like
"int(raw_input())" instead of just "input()" - if you read the help on
the two functions you should see why.

Hope this helps.

Jason

On Oct 23, 11:56 am, Shawn Minisall <[EMAIL PROTECTED]> wrote:
> I just wrote a program to let the user input a series of whole numbers
> and tell them which is least and which is greatest based off of a menu.
> However, the menu isn't kicking in after they pick a number.  I included
> a while statement for a loop just for the menu and compared it to my
> other programs that have a similar setup and are working, but I'm
> stumped.   Here's the program...
>
> def main():
>
> #define and initialize variables
> #choice as int
> choice = 0
> #number as int
> number = 0
>
> #intro
> print "WELCOME TO THE GREATEST AND LEAST NUMBER PROGRAM!"
> print
>
> #Menu loop
> while choice != 2:
> #display menu
> print "Please choose from the following menu: "
> print "1. Enter a number"
> print "2. Exit"
> print
>
> #prompt user for their menu choice
> choice = input("Enter your choice here: ")
>
> #if statements to determine which choice
> if choice == 1:
> nums = []
> while number >=0:
> nums.append(number)
> number = input("Please enter a number.")
>
> elif choice == 2:
> print "Have a great day!"
>
> if len(nums) > 0:
> print "The smallest number that you entered was:",min(nums)
> print "The largest number that you entered was:",max(nums)
>
> else:
> #invalid
> print "Invalid selection.  Enter either one or two."
> print
>
> Also, if they quit the program with choice #2 and entered numbers, it
> should display the greatest and least of them.  If they just started and
> didn't enter anything and want to quit, I get an error message saying
> UnboundLocalError: local variable 'nums' referenced before assignment.
> Isn't the if statement supposed to keep python from going there since if
> they didn't enter any input, the length of the list should just be zero.


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