ANN: ConfigObj 4.6.0 and Validate 1.0.0 released

2009-04-18 Thread Fuzzyman
Finally a fresh release ConfigObj and Validate.

* ConfigObj Home page: http://www.voidspace.org.uk/python/configobj.html
* Validate Home page: http://www.voidspace.org.uk/python/validate.html

**ConfigObj** is a simple to use but powerful Python library for the
reading and writing of configuration (ini) files. Through **Validate**
it integrates a config file validation and type conversion system.

Features of ConfigObj include:

* Nested sections (subsections), to any level
* List values
* Multiple line values
* Full Unicode support
* String interpolation (substitution)
* Integrated with a powerful validation system

- including automatic type checking/conversion
- and allowing default values
- repeated sections

* All comments in the file are preserved
* The order of keys/sections is preserved
* Powerful ``unrepr`` mode for storing/retrieving Python data-types

Release 4.6.0 fixes bugs and adds new features, particularly making
configspec handling more flexible.

Full details on the changes can be found at:
http://www.voidspace.org.uk/python/weblog/arch_d7_2009_04_11.shtml#e1078

The changelog for ConfigObj 4.6.0 is:

* Pickling of ConfigObj instances now supported (thanks to Christian
Heimes)
* Hashes in confgspecs are now allowed (see note below)
* Replaced use of hasattr (which can swallow exceptions) with getattr
* ``__many__`` in configspecs can refer to scalars (ordinary values)
as well as sections
* You can use ``___many___`` (three underscores!) where you want to
use ``__many__`` as well
* You can now have normal sections inside configspec sections that use
``__many__``
* You can now create an empty ConfigObj with a configspec,
programmatically set values and then validate
* A section that was supplied as a value (or vice-versa) in the actual
config file would cause an exception during validation (the config
file is still broken of course, but it is now handled gracefully)
* Added ``as_list`` method
* Removed the deprecated ``istrue``, ``encode`` and ``decode`` methods
* Running test_configobj.py now also runs the doctests in the
configobj module
* Through the use of validate 1.0.0 ConfigObj can now validate multi-
line values

As the public API for Validate is stable, and there are no outstanding
issues or feature requests, I've bumped the version number to 1.0.0.
The full change log is:

* BUGFIX: can now handle multiline strings
* Addition of 'force_list' validation option
--
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: Domain Driven Design and Python

2009-04-18 Thread Terry Reedy

José María wrote:


DDD is more or less a methodology. I've used it with C# and I like it
very much.
The objetive of DDD is to create software that mirror the domain of
the problem,
you isolate this domain from the technical problems (persistence,
services,GUI).


I presume that many Python programmers do this without calling it 'DDD'.

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


Re: question about xrange performance

2009-04-18 Thread bearophileHUGS
Paul McGuire:

xrange is not really intended for in testing,

Let's add the semantic of a good and fast in to xrange (and to the
range of Python3). It hurts no one, allows for a natural idiom
(especially when you have a stride you don't want to re-invent the
logic of skipping absent numbers), and it's readable.

My xrange() I have written in D language has a fast OpIn_r() method. I
haven't found any bad side effect to such capability yet.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Beginner: Portable Python, BeautifulSoup ScrapeNFeed

2009-04-18 Thread Brian
Was this code a complete waste of my time?

On Wed, Apr 15, 2009 at 1:09 AM, Brian brian.min...@colorado.edu wrote:

 On Ubuntu:

 sudo apt-get install python-pyrss2gen python-beautifulsoup # download
 ScrapeNFeed

 Python:
 Not sure what's wrong with this but it's most of the code you'll need:
 ---
 from urllib import urlopen
 from BeautifulSoup import BeautifulSoup
 from PyRSS2Gen import RSSItem, Guid
 import ScrapeNFeed
 import re

 url='http://jobs.spb.ca.gov/exams_title.cfm'
 job_html = urlopen(url).read()
 job_soup = BeautifulSoup(job_html)
 jobs = job_soup.findAll('strong', text=re.compile('.*RESEARCH.*'))

 class JobFeed(ScrapeNFeed.ScrapedFeed):
 def HTML2RSS(self, headers, body):
 items = [RSSItem(title=job,
  link=url,
  description=job_soup.h2.string.strip())
  for job in jobs]

 self.addRSSItems(jobs)

 JobFeed.load(job_soup.title.string.strip(),
  url,
  'jobs.rss',
  'jobs.pickle',
  managingEditor='',
  )







 On Tue, Apr 14, 2009 at 4:17 PM, Joe Larson j...@joelarson.com wrote:

 Hello list!

 I am a Python Beginner. I thought a good beginning project would be to use
 the Portable Python environment http://www.portablepython.com/ with
 Beautiful Soup http://www.crummy.com/software/BeautifulSoup/ and Scrape
 'N' Feed http://www.crummy.com/software/ScrapeNFeed/ to create and RSS
 feed of this page http://jobs.spb.ca.gov/exams_title.cfm - ideally
 filtering just for positions with the string 'Research Analyst'.

 In my day job I work on the Windows OS (hence the Portable Python) - at
 home I use Ubuntu but also carry Portable Ubuntu as well.

 I just wanted to shoot this to the list - see if anyone had any
 suggestions or tips. I'm reading O'Reilly's Learning Python and The Python
 Tutorial, but it's still very challenging as this is my first programming
 language. Thanks all! Sincerely ~ joelar
  --
 http://mail.python.org/mailman/listinfo/python-list



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


Re: Question to python C API

2009-04-18 Thread Stefan Behnel
Andreas Otto wrote:
   just my first step in Cython
 
   1. download Cython-0.11.1
 
   2. read INSTALL.txt
 
 
 (1) Run the setup.py script in this directory
 as follows:
 
 python setup.py install
 
 This will install the Pyrex package
 into your Python system.
 
 
 Question 1: Why you wall it Pyrex package ?

That's a left-over. We fixed the name almost everywhere by now, but that
slipped through.

That shows that the installation instructions haven't been touched in years
(although they should work in general).


   3. this happen
 
 python ./setup.py install
 Traceback (most recent call last):
   File ./setup.py, line 5, in module
 from Cython.Compiler.Version import version
   File /home/dev1usr/src/Cython-0.11.1/Cython/__init__.py, line 2, in
 module
 from Shadow import *
 ImportError: No module named Shadow

Relative imports have changed in Py3, so as you write:

   4. I use a thread enabled python V3 

That's the core problem. :) Like many other Python packages, Cython doesn't
currently run in Py3. You can run it in any Py2 version starting from 2.3,
and the code it generates will run on 2.3 through 3.1a1. But the Cython
compiler itself requires 2.x. This is being fixed up as we speak, and the
2to3 conversion tool works pretty well on the source by now, so there's a
fair chance that Cython 0.12 will run on Py3.

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


Re: Is there a programming language that is combination of Python and Basic?

2009-04-18 Thread Steven D'Aprano
On Fri, 17 Apr 2009 22:26:32 -0700, norseman wrote:

 The
 average programmer, who takes a moment to think it out, 

A moment? As in, a second or less?

 can out optimize
 all but the best commercial compilers. The meticulous individual can
 usually match or best the best commercials with fewer 'iterations' of
 review when using assembly.

That might have been true in the 1970s and 80s, but it hasn't been true 
for 10-20 years now. The best machine-optimized code is significantly 
better than the best human beings can do today, and even free optimizing 
compilers can do better than most people.

However, human programmers can, sometimes, hand-optimize the output of 
the optimizing compiler in order to gain a slight upper-hand. To 
paraphrase Charles Fiterman, the human should always win, because the 
human can use the machine, but the machine can't use the human.

http://www.linux.com/base/ldp/howto/Assembly-HOWTO/howtonot.html


 Since one is already looking at the
 registers and addresses, self optimization is simple.

If only modern day programming was that simple. The interaction with 
modern CPU makes optimization an order of magnitude harder than it was 
back in the days of hand-tuned assembly. I quote from the above link:

The biggest problems on modern architectures with fast processors are 
due to delays from memory access, cache-misses, TLB-misses, and page-
faults; register optimization becomes useless, and you'll more profitably 
re-think data structures and threading to achieve better locality in 
memory access.


Toto-I-don't-think-we're-in-1975-anymore-ly  y'rs, 


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


Re: Suggestions wanted on Tkinter problem

2009-04-18 Thread Steven D'Aprano
On Thu, 16 Apr 2009 16:18:03 -0700, norseman wrote:

 At this point the program runs, but I cannot control gray-out of a
 specific Radiobutton.
 
  If I:
 
  counter=0
  for mode, text 
  c[counter] = Radiobuton(specified_frame,..
  c[counter].pack()
  counter += 1
  .
  .
  blockUseOf= $varSetElsewhere

What language are you programming in? $varSetElsewhere isn't legal Python.


  c[blockUseOf].config(state = strSetElsewhere)
 
 Program crashes on Radiobutton line.


No no, don't tell us *what* error you got! We LOVE guessing games!!!

Hmm, this guessing game might be harder than I like. Not only aren't we 
told what the error is, but half of the line that contains the error is a 
secret.

How about telling us what the actual error is, and the actual line that 
causes the error? Chances are very good that the error message will tell 
you everything you need to know about why the program fails.




 There are a number of Frames containing Radiobuttons in the program. The
 individual lists are long enough no one in their right mind wants to
 hand code such repetition and then try to maintain it. 

Then perhaps you should think about changing the user interface to make 
it simpler to manage, and simpler to use. Not every task requires a 
hammer.



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


Re: Is there a programming language that is combination of Python and Basic?

2009-04-18 Thread Steven D'Aprano
On Fri, 17 Apr 2009 20:45:30 -0700, Mensanator wrote:

 Nevertheless, somebody *has* implemented such functionality in Python.
 Not just GOTO, but also COMEFROM.
 
 Really? Well, _I_ for one, won't be beating a path to his door.

Well you should. It's very clever code, and the way he solved the 
problem is intriguing. It was also a great April Fools joke.

For reference, here's that URL again: http://entrian.com/goto/


 GOTO in Pascal required that you defined a label in your code, then you
 could jump to that label. You can't jump to arbitrary parts of the
 program, only within the current procedure.
 
 And I deliberately made no effort to learn how to use them. And I never
 had a situation I couldn't solve the proper way.

You need to distinguish between the use of unstructured jumps like Basic-
style GOTOs and COMEFROMs, which can jump anywhere, and the use of 
structured GOTOs and jumps that have well-defined meanings. GOTO, after 
all, is just a jump, and we use jumps in Python all the time:

raise Exception
break
continue
if... elif... else...
for... else...
etc.

Often -- well, sometimes -- you can write cleaner, simpler code with GOTO 
than without. Fortunately, 95% of those cases can be dealt with a break 
or continue in a loop. In a high level language, GOTO is never necessary 
and rarely useful, but it is useful on occasion. Any time you find 
yourself creating a flag variable just so you can skip a code block, or 
enter a code block, then a structured GOTO *could* be a clean 
replacement. But probably isn't. (This is not a call for Python to 
develop a GOTO, just a defence that they aren't always the Wrong Thing.)

COMEFROM on the other hand is just the purest evil imaginable.



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


Re: script question

2009-04-18 Thread Peter Otten
pyt...@bdurham.com wrote:

 Peter,
 
 Another eval-free variant:
 
 [x() for x in vars().values() if hasattr(x, _included)]
 
 If you use getattr(x, _included, False) instead of hasattr()
 you can un-include functions with ...
 
 YES! That's what I was struggling to do with my in-elegant use of
 eval(), eg. replacing eval() to expand dir() strings with a dictionary
 of local objects.
 
 Question: why vars() vs. globals()? My tests in IDLE (Python 2.6) show
 vars() and globals() returning the same items.

Indeed, it doesn't matter here.

I chose vars() because it uses the same logic as dir(), i. e. vars().keys()
should give you the same names as dir(). Note that both vars() and dir()
give you the same namespace as locals() which just happens to be the same
as globals() on the module level. Inside a function you have to use
globals() or vars(module) to access the module's global namespace.

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


Re: Registering Cron using CronTab

2009-04-18 Thread gurcharan . saini
On Apr 18, 5:21 am, Lawrence D'Oliveiro l...@geek-
central.gen.new_zealand wrote:
 In message mailman.4054.1239976986.11746.python-l...@python.org, Philip

 Semanchuk wrote:

  On Apr 17, 2009, at 9:51 AM,gurcharan.sa...@gmail.com wrote:

  I'm stuck with the issue - if we execute the code from Apache the
  crontab is not getting updated, while it get updated if we run it from
  Django in-built webserver.

  Sure sounds like a permissions problem to me.

 Same here. Note that you can run a CGI under its owning user in Apache with
 the suexec feature. That might give you the permissions you need.

Thanks, will go through the docs.
--
http://mail.python.org/mailman/listinfo/python-list


Re: binary file compare...

2009-04-18 Thread Piet van Oostrum
 Adam Olsen rha...@gmail.com (AO) wrote:

AO The Wayback Machine has 150 billion pages, so 2**37.  Google's index
AO is a bit larger at over a trillion pages, so 2**40.  A little closer
AO than I'd like, but that's still 56294995000 to 1 odds of having
AO *any* collisions between *any* of the files.  Step up to SHA-256 and
AO it becomes 1915619400 to
AO 1.  Sadly, I can't even give you the odds for SHA-512, Qalculate
AO considers that too close to infinite to display. :)

AO You should worry more about your head spontaneously exploding than you
AO should about a hash collision on that scale.  To do otherwise is
AO irrational paranoia.

And that is the probability if there being two files in that huge
collection with the same hash. If you just take two files, not
fabricated to collide, the probability of them having the same hash
under MD5 is 2**-128 which I think is way smaller than the probability
of the bit representing the answer being swapped by some physical cause
in your computer. But then again, it doesn't make sense to use that
instead of byte-by-byte comparison if the files are on the same machine.
-- 
Piet van Oostrum p...@cs.uu.nl
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question to python C API

2009-04-18 Thread Wolfgang Strobl
Andreas Otto aotto1...@onlinehome.de wrote
about his attempts to install and run Cython:

  5. and start to build the hello world example

I changed:  print Hello World
to: print(Hello World)- this is V3

AFAIK Cython doesn't support Python 3, yet. See
http://trac.cython.org/cython_trac/ticket/234

I suggest staying with Python 2.x.  What C compiler are you going to
use, btw.?


-- 
Wir danken für die Beachtung aller Sicherheitsbestimmungen
--
http://mail.python.org/mailman/listinfo/python-list


Re: Play sound at wanted frequency

2009-04-18 Thread Matteo
On 15 Apr, 19:25, Scott David Daniels scott.dani...@acm.org wrote:
 Diez B. Roggisch wrote:
  Matteo schrieb:
  I need to playback a sound on a linux machine of a pre-determined
  frequency like, say, 440 Hz. How can I do that with python? I found
  the ossaudiodev package, but it says that the ossaudiodev.write()
  method accepts data as a raw string. It doesn't explain what the
  string should be like, and the oss documentation is mainly about C++.

  Do you have any tips to share?

  Try pygame. You can create samples with it, and play them.

  See e.g. this:http://www.pygame.org/docs/ref/sndarray.html

 And realize that if you can get that to work, you can always cut into
 pygame to see how _it_ accomplishes your task, and mimic that.

 --Scott David Daniels
 scott.dani...@acm.org

I'll give it a try, thanks ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Condition.wait(0.5) doesn't respect it's timeout

2009-04-18 Thread Piet van Oostrum
 stephane.bisin...@gmail.com (SB) wrote:

SB Hi all,
SB I have a problem with Condition.wait(), it doesn't return after the
SB given timeout. The thing is that if I try to create a simple program,
SB it works as expected, but in the actual code, the timeout is not
SB respected (albeit the notify()s work as expected).
SB You can find the code I am talking about here:
SB 
http://github.com/Kjir/amsn2/blob/6688da4c0b7cc16c0fe04d6d6018bc1b16d992a6/amsn2/gui/front_ends/curses/contact_list.py

SB If you clone the repository, then you can run the program like this:
SB $ python amsn2.py -f curses 2 run.log
SB and in another term watch for prints with a tail -f run.log (You need
SB an MSN account). You'll notice that after the initial downloading of
SB the contact list, there won't be any logs (unless some of your
SB contacts changes status, which will trigger a notify)

SB Has anyone the slightest idea on what I may be doing wrong? Or am I
SB just lucky enough to have stumbled across a bug? Maybe pollution from
SB another module in other parts of the code? (Like gobject...)

I haven't run it (too much hassle to setup) but I noticed one strange
thing in your code:

,
| def groupUpdated(self, gView):
| # Acquire the lock to do modifications
| self._mod_lock.acquire()
|  
| if not self._groups.has_key(gView.uid):
| return
`

In case the return is taken, the lock will not be released thereby
blocking the rest. It could be that the timeout is taken, but before the
wait can continue it has to acquire the lock again.

It is best to put all your code after the acquire in a try: finally:
like 

,
| self._mod_lock.acquire()
| try:
| do something
| finally:
| self._mod_lock.release()
`

or even better use the with statement:

,
| with self._mod_lock:
|  do something
`
It will do the releasing automatically

And then something else:
,
| def __thread_run(self):
|while True:
|import sys
|print  sys.stderr, at loop start
|self._mod_lock.acquire()
|t = time.time()
|# We don't want to work before at least half a second has passed
|while time.time() - t  0.5 or not self._modified:
|print  sys.stderr, Going to sleep\n
|self._mod_lock.wait(timeout=1)
|print  sys.stderr, Ok time to see if we must repaint
|self.__repaint()
|t = time.time()
|self._mod_lock.release()
|print  sys.stderr, at loop end
|self._mod_lock.acquire()
`

Your loop ends with self._mod_lock.acquire() but in the next round there
is another self._mod_lock.acquire() at the beginning of the loop. So the
acquire at the end isn't necessary.

-- 
Piet van Oostrum p...@cs.uu.nl
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a programming language that is combination of Python andBasic?

2009-04-18 Thread Hendrik van Rooyen
baykus b..@gmail.com wrote:


 I guess I did not articulate myself well enough. I was just looking
 for a toy to play around. I never suggested that Python+Basic would be
 better than Python and everyone should use it. Python is Python and
 Basic is Basic. I am not comparing them at all. I understand the
 merits of Python but that does not mean I can play with ideas?

Apparently this is not allowed by the CS thought police.

The reasoning is based on an Argument from Authority,
namely the Dijkstra link.

Now it looks to me when I read that article, that the jump
is deprecated because it leads to code that is difficult to
understand, which was based on the difficulty that Dijkstra 
had to construct a co-ordinate system for storing the state
of a program at any given line of code.  This was done 
without giving any reason as to why this should be important,
or even desirable, except towards the end where he wanted to
define instances in time when a count could conceivably be
off by one, and he asserted without proof that having jumps 
in the code makes this more difficult.  Even if this assertion
were to be provably true, it does not really follow that jumps
should be banned, but merely that one runs such a risk if one
were to use them.  Now to some minds, this difficulty may
not be a difficulty at all: 

Processors and interrupt service routines are storing the state
of multiple programmes at arbitrary points in the code, even 
as I type - and every one of those programmes include jumps.
It is a non - issue.

Mensanator had the same complaint based on difficulty 
earlier in this thread, when he described how he struggled
to untangle some spaghetti code.  He did not mention if
the spaghetti was actually doing it's job, bug free, which
IMO is the only rational test for the quality of a piece
of code, because it is the reason for its existence.  
The aesthetics are, like all aesthetics, a matter of opinion.

I do not agree with the reasoning that effectively says:
If it is difficult to comprehend, it must be wrong

If this were to be a tenet, then using the pickle module 
should be forbidden too, as it is a complex piece of 
code that (to me at least) is not easily understood on a 
first read-through.

So does that mean I must stop using pickles?

All Strength to Arnaud for his goto code!
I am looking forward to the gosub and return.
:-)

- Hendrik


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


Re: send() to a generator in a for loop with continue(val)??

2009-04-18 Thread Peter Otten
Dale Roberts wrote:

 I've started using generators for some real work (love them!), and I
 need to use send() to send values back into the yield inside the
 generator. When I want to use the generator, though, I have to
 essentially duplicate the machinery of a for loop, because the for
 loop does not have a mechanism to send into the generator. Here is a
 toy example:
 
 def TestGen1():
 for i in xrange(3):
 sendval = yield i
 printgot %s in TestGen() % sendval
 
 g = TestGen1()
 sendval = None
 try:
 while True:
 val = g.send(sendval)
 print 'val in while loop %d' % val
 sendval = val * 10
 except StopIteration: pass
 
 I have to explicitly create the generator with an assignment, send an
 initial None to the generator on the first go, then have to catch the
 StopIteration exception. In other words, replicate the for
 mechanism, but use send() instead of next().
 
 It would be nice if I could just do this instead:
 
 for val in TestGen1():
 print 'val in for loop %d' % val
 continue(val*10)
 
 ...or something similar. Is this an old idea? Has it been shot down in
 the past already? Or is it worth pursuing? I Googled around and saw
 one hit here:
 http://mail.python.org/pipermail/python-ideas/2009-February/003111.html,
 but not much follow-up.
 
 I wonder if people want to keep the idea of an iterator style
 generator (where send() is not used) separate from the idea of a co-
 routine style generator (where send() is used). Maybe combining the
 two idioms in this way would cause confusion?
 
 What do folks think?

If it were up to me I'd rip out send() immediatly. At first I thought I
would see a compelling use case and be enlightened, but it never happened.

I just grepped the python 3 source for '= yield' and the only matches were
in the unit tests for generators and parser.

Let it die while it hasn't polluted the wider code base.

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


pyqt4 qTableWidget add items help

2009-04-18 Thread ookrin
I've been searching around the internet for an example of how to add a
list of items to the qTableWidget for the last few hours with little
success.

I have a list orders [[34,940,30,50,67], [50,56,35,30,57]] as my
example here

I built the qTableWidget in designer, so it already has the header
columns filled out.

Date | time | Number | Price | Buyer

ui.tb1_tblOrders.setRowCount(len(orders))

gives me the correct number of rows I want, but how do I fill the
rows?

I've been trying

while(len(orders) i):
ui.tb1_tblOrders.setCurrentCell(i,0,orders[i][1])
i+=1

which to me, says go add in the first column row with the first order,
and it makes sense to me

 It just says Error: argument 3 of QTableWidget.setCurrenCell() has
invalid type, I know it's the orders, but I can't figure out what the
proper way of giving it what it wants is.
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyqt4 qTableWidget add items help

2009-04-18 Thread Diez B. Roggisch

ookrin schrieb:

I've been searching around the internet for an example of how to add a
list of items to the qTableWidget for the last few hours with little
success.

I have a list orders [[34,940,30,50,67], [50,56,35,30,57]] as my
example here

I built the qTableWidget in designer, so it already has the header
columns filled out.

Date | time | Number | Price | Buyer

ui.tb1_tblOrders.setRowCount(len(orders))

gives me the correct number of rows I want, but how do I fill the
rows?

I've been trying

while(len(orders) i):
ui.tb1_tblOrders.setCurrentCell(i,0,orders[i][1])
i+=1

which to me, says go add in the first column row with the first order,
and it makes sense to me

 It just says Error: argument 3 of QTableWidget.setCurrenCell() has
invalid type, I know it's the orders, but I can't figure out what the
proper way of giving it what it wants is.



I don't find setCurrentCell in the docs for QTableWidget - only for Q3Table.

http://doc.trolltech.com/4.0/q3table.html#setCurrentCell

However, that call isn't about setting the value of a cell, instead it's 
about giving a cell the focus.


Use setItem instead.

And don't use the wicked while-loop for generating indices - this is 
done in python using the enumerate-function:



for i, order in enumerate(orders):
...

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


Re: pyqt4 qTableWidget add items help

2009-04-18 Thread Sebastian Wiesner
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

ookrin – Samstag, 18. April 2009 11:58

[...]
 I've been trying
 
 while(len(orders) i):
 ui.tb1_tblOrders.setCurrentCell(i,0,orders[i][1])
 i+=1
 
 which to me, says go add in the first column row with the first order,
 and it makes sense to me
Read the documentation [1] to learn, what .setCurrentCell() actually does 
and what its arguments are!  And please stop this wild guessing ...

The method you're searching for is .setItem() [2], which adds a new 
QTableWidgetItem [3] to a QTableWidget. 

[1] http://doc.trolltech.com/4.5/qtablewidget.html#setCurrentCell
[2] http://doc.trolltech.com/4.5/qtablewidget.html#setItem
[3] http://doc.trolltech.com/4.5/qtablewidgetitem.html

- -- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.11 (GNU/Linux)

iEYEARECAAYFAknpr4sACgkQGV4vxEMMOxdnawCfTXO55EffBJMQ7h91RGtMIpZ/
hcYAoLQ9yF5u/hBgNRvqxGRlIy5lPDgb
=Q6ef
-END PGP SIGNATURE-

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


Re: Is there a programming language that is combination of Python andBasic?

2009-04-18 Thread Aaron Brady
On Apr 18, 4:44 am, Hendrik van Rooyen m...@microcorp.co.za wrote:
 baykus b..@gmail.com wrote:
  I guess I did not articulate myself well enough. I was just looking
  for a toy to play around. I never suggested that Python+Basic would be
  better than Python and everyone should use it. Python is Python and
  Basic is Basic. I am not comparing them at all. I understand the
  merits of Python but that does not mean I can play with ideas?

 Apparently this is not allowed by the CS thought police.

 The reasoning is based on an Argument from Authority,
 namely the Dijkstra link.

Boo, Appeal to Authority!

snip
 to untangle some spaghetti code.  He did not mention if
 the spaghetti was actually doing it's job, bug free, which
 IMO is the only rational test for the quality of a piece

I don't use 'rational' in the same way.  Do you mean objective?  Do
readability, brevity, simplicity, purity, etc. contribute to quality?
Is program quality equivalent (or identical) to code quality?

 of code, because it is the reason for its existence.  
 The aesthetics are, like all aesthetics, a matter of opinion.

 I do not agree with the reasoning that effectively says:
 If it is difficult to comprehend, it must be wrong

Wrong no, but impractical, possibly or probably or almost certainly,
notwithstanding the subject-dependence of ease of comprehension.
Simple code is more future-resilient than that which is difficult to
comprehend, even holding the language (version) constant.  It is a
matter of priorities, which have no objective right.  The amount of
people that can comprehend a code structure is a competing value to
that of exploration, pioneering, research, and development.  However,
even in simplest terms, some structures e.g. recursion, may be
difficult to comprehend, but that doesn't mean they would be better
more complicated.
--
http://mail.python.org/mailman/listinfo/python-list


Re: question about xrange performance

2009-04-18 Thread mmanns
On Fri, 17 Apr 2009 23:40:32 -0700 (PDT)
bearophileh...@lycos.com wrote:

 Paul McGuire:
 
 xrange is not really intended for in testing,
 
 Let's add the semantic of a good and fast in to xrange (and to the
 range of Python3). It hurts no one, allows for a natural idiom
 (especially when you have a stride you don't want to re-invent the
 logic of skipping absent numbers), and it's readable.

A fast in to xrange would be great.
Why was it taken away?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Modifying the value of a float-like object

2009-04-18 Thread Eric . Le . Bigot
On Apr 15, 5:33 pm, Arnaud Delobelle arno...@googlemail.com wrote:
 I still don't think mutable floats are necessary.  Here is an approach
 below - I'll let the code speak because I have to do some shopping!

Hats off to you, Arnaud!  I'm very impressed by the ideas found in
your code. :)

Your UExpr object is almost a mutable float, though (x=UVal(...);
y=x; x.value =...; print y+0 gives a new value).  What was not needed
was some kind of external access to numbers with error, that would
have allowed an external routine to modify them so as to perform
calculations of Python expressions with different parameters.  Your
idea of building an expression (UExpr) that keeps track of the
variables involved in it (basis) was great!  I was somehow stuck with
the idea that float with uncertainty objects should return a float,
when involved in mathematical calculations.

I adjusted your code in a few ways, and put the result at
http://code.activestate.com/recipes/576721/ (with due credit):

1) There was a strange behavior, which is fixed (by performing only
dynamic calculations of UExpr, with an optimization through a new
constant class):

 x = UVal(100., 1.)
 y = 2*x
 x.value = 3.14
 print y, should equal, y+0  # Values not equal!
200.0 +- 2.06348273 should equal 6.2802 +-
2.00131024

2) More operations are supported: calculations with integers (UVal
(1)), comparisons, unary operators + and - (+Uval(1.)),...

3) The code is documented, and identifiers are longer and more
explicit.

Voilà!

Thank you all for this lively and productive thread!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a programming language that is combination of Python and Basic?

2009-04-18 Thread greg

Steven D'Aprano wrote:
To 
paraphrase Charles Fiterman, the human should always win, because the 
human can use the machine, but the machine can't use the human.


Unless the machine is Omnius.

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


Re: Is there a programming language that is combination of Python and Basic?

2009-04-18 Thread BJörn Lindqvist
I first started programming basic and i don't think it has hurt me much.


I can somewhat sympathise with the op, neither python nor any other
mainstream language can still do this:

SCREEN 13
PSET 160,100,255

2009/4/17, Leguia, Tony legui...@grinnell.edu:
 Though I don't know why you would want to reference lines numbers, I assume
 it's for goto statements or something similar.
 With that said please read:
 1)
 http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html

 I would also like to put forth my opinion, shared by many in the community,
 that Basic is actually dangerous as an educational programming language, and
 that writing
 large professional code in it is hard, and actually hampered by the
 language. I'm not trying to to start a flame war here but this post almost
 made me cry.

 Also python is functional, it's so powerful. Grow and learn to take
 advantage of that. Why hold yourself back?

 
 From: python-list-bounces+leguiato=grinnell@python.org
 [python-list-bounces+leguiato=grinnell@python.org] On Behalf Of baykus
 [baykusde...@gmail.com]
 Sent: Friday, April 17, 2009 3:37 PM
 To: python-list@python.org
 Subject: Is there a programming language that is combination of Python and
Basic?

 Hi

 I am looking for one of those experimental languages that might be
 combination of python+basic. Now thta sounds weird and awkward I know.
 The reason I am asking is that I always liked how I could reference-
 call certain line number back in the days. It would be interesting to
 get similar functionality in Python.
 --
 http://mail.python.org/mailman/listinfo/python-list
 --
 http://mail.python.org/mailman/listinfo/python-list



-- 
mvh Björn
--
http://mail.python.org/mailman/listinfo/python-list


Too early implementation

2009-04-18 Thread Filip Gruszczyński
I am not a very disciplined person. Usually I rush to my next
assignment and code furiously, hoping that my initial understanding of
the stated problem will be just fine. And Python does very little to
stop me ;-) If I had to do something in C++, I know I would have to
write all those header files, fill stubs, etc., which is a lot of
work, which I don't want to do twice. So I take a while and start to
think, because it's better to be safe, than sorry.

With Python you rarely are sorry, because you can do everything so
quickly. And yet, at some point you see, that flaws in design get so
annoying, that you need to do something about them. Usually at that
point it's a bit problematic ;-)

So, do you know some good methods to prevent myself from just starting
coding (which I like very much) and do some thinking about the problem
(which I like a little less ;-))?

-- 
Filip Gruszczyński
--
http://mail.python.org/mailman/listinfo/python-list


Re: Condition.wait(0.5) doesn't respect it's timeout

2009-04-18 Thread stephane . bisinger
On Apr 18, 10:24 am, Piet van Oostrum p...@cs.uu.nl wrote:

 I haven't run it (too much hassle to setup) but I noticed one strange
 thing in your code:

 ,
 | def groupUpdated(self, gView):
 |         # Acquire the lock to do modifications
 |         self._mod_lock.acquire()
 |  
 |         if not self._groups.has_key(gView.uid):
 |             return
 `

 In case the return is taken, the lock will not be released thereby
 blocking the rest. It could be that the timeout is taken, but before the
 wait can continue it has to acquire the lock again.

That is absolutely correct, but I guess with an RLock there shouldn't
be a deadlock... Anyway I'm fixing that!


 It is best to put all your code after the acquire in a try: finally:
 like

 ,
 | self._mod_lock.acquire()
 | try:
 |         do something
 | finally:
 |         self._mod_lock.release()
 `

 or even better use the with statement:

 ,
 | with self._mod_lock:
 |      do something
 `
 It will do the releasing automatically

Thanks for the advice!

 And then something else:
 ,
 | def __thread_run(self):
 |        while True:
 |            import sys
 |            print  sys.stderr, at loop start
 |            self._mod_lock.acquire()
 |            t = time.time()
 |            # We don't want to work before at least half a second has passed
 |            while time.time() - t  0.5 or not self._modified:
 |                print  sys.stderr, Going to sleep\n
 |                self._mod_lock.wait(timeout=1)
 |                print  sys.stderr, Ok time to see if we must repaint
 |            self.__repaint()
 |            t = time.time()
 |            self._mod_lock.release()
 |            print  sys.stderr, at loop end
 |            self._mod_lock.acquire()
 `

 Your loop ends with self._mod_lock.acquire() but in the next round there
 is another self._mod_lock.acquire() at the beginning of the loop. So the
 acquire at the end isn't necessary.

I have no idea how that came to be, probably pasted one line where I
shouldn't have, it's gone ;)

Anyway I cleaned up that mess and here is the resulting code, with the
same issues:
http://github.com/Kjir/amsn2/commit/bda6829d0c7d50a1cbf1188cdfa3789c4b7967c5
http://github.com/Kjir/amsn2/blob/bda6829d0c7d50a1cbf1188cdfa3789c4b7967c5/amsn2/gui/front_ends/curses/contact_list.py

I'll also file a bug report because I am more and more convinced this
is a bug, if anything else at least in the documentation...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Too early implementation

2009-04-18 Thread Tim Chase

Filip Gruszczyński wrote:

I am not a very disciplined person. Usually I rush to my next
assignment and code furiously, hoping that my initial understanding of
the stated problem will be just fine. And Python does very little to
stop me ;-) If I had to do something in C++, I know I would have to
write all those header files, fill stubs, etc., which is a lot of
work, which I don't want to do twice. So I take a while and start to
think, because it's better to be safe, than sorry.

So, do you know some good methods to prevent myself from just starting
coding (which I like very much) and do some thinking about the problem
(which I like a little less ;-))?


Well, you can force yourself to write tests first...

-tkc


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


any complete and actual pysqlite example?

2009-04-18 Thread oyster
I mean not a code to do seperated functions, but a real project

I have read the doc of pysqlite, but since I know little about
database, I found it is still very hard for me to cook a real database
app from the scratch with the help of codelet in pysqlite doc. here is
the simplified details:
[TABLE 1]
bookName text
price num
author -- this is actually linked with the [TABLE 2], for one author
maybe write many books, I think it is better to do an external link
[/TABLE 1]

[TABLE 2]
authorName text
[/TABLE 2]

Then
[record  for TABLE 1]
id  bookName  price authoridx
1   The Definitive Guide to SQLite  30  1
2   Core Python 40  2
3   Dive Into Python35  3
[/record  for TABLE 1]

[record  for TABLE 2]
id  authorName
1   Michael Owens
2   Wesley J. Chun
3   Mark Pilgrim
[/record  for TABLE 2]

what I need
1. of cause, create the TABLE, and add real data into it. I don't know
how to deal with the author item in [TABLE 1]

2. list the data. A question is, when I list the record in [TABLE 1],
can I get something like following?
The Definitive Guide to SQLite, 30.0, Michael Owens
I mean, the authorName is returned automatically, but not only the authoridx

3. what if I del the 1st record in [TABLE 2] since a record in [TABLE 1] use it?

4.I want to do some group, for example, group the record in [TABLE 1]
according to their price, so that
[30]
   Book1Name
   Book2Name
[40]
   Book3Name
[50]
   Book4Name
   Book4Name
does sqlite support this? or I have to do this in python?

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


Re: can't install new modules after updating python

2009-04-18 Thread Aahz
In article f2a25d72-5e21-498a-95a4-59045f158...@r37g2000yqn.googlegroups.com,
lie  liewai...@gmail.com wrote:

I've updated from python 2.5 to 2.6 on my Slackware 12.2, by compiling
the 2.6 source. When I try to use slapt-get to install a new module
for python, it installs in the old version, and I can't use it. How
can I fix this? Should I go back to 2.5?

Generally speaking, you should never directly update the system Python;
most Linux systems these days rely on Python for their operation.
Instead, you install an additional copy of Python, and you cannot use
your OS package management to install modules; just install the modules
manually.
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur.  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: send() to a generator in a for loop with continue(val)??

2009-04-18 Thread Aahz
In article gsc7e1$rj6$0...@news.t-online.com,
Peter Otten  __pete...@web.de wrote:

If it were up to me I'd rip out send() immediatly. At first I thought I
would see a compelling use case and be enlightened, but it never happened.

Too late -- it's likely to get an upgrade for 3.1 and 2.7.  Basically,
send() is useful for coroutines, and if you haven't yet read
http://dabeaz.com/coroutines/
you really should (assuming you want to continue arguing).
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur.  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: Condition.wait(0.5) doesn't respect it's timeout

2009-04-18 Thread Aahz
In article 1eb44e98-3f32-42b3-92f8-1e635428c...@q9g2000yqc.googlegroups.com,
 stephane.bisin...@gmail.com wrote:

I have a problem with Condition.wait(), it doesn't return after the
given timeout. The thing is that if I try to create a simple program,
it works as expected, but in the actual code, the timeout is not
respected (albeit the notify()s work as expected).

Whether or not there's a bug, you likely will simplify your code if you
switch to using a Queue().
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur.  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: Condition.wait(0.5) doesn't respect it's timeout

2009-04-18 Thread stephane . bisinger
On Apr 18, 2:05 pm, a...@pythoncraft.com (Aahz) wrote:
 Whether or not there's a bug, you likely will simplify your code if you
 switch to using a Queue().

I'm sorry, but I can't see how the queue would help me on this, since
I only have 2 threads and the documentation esplicitly states that it
helps with multiple threads. I have no items to put in the queue, my
only concern is not to update the screen while I am changing the state
of the contact list... Maybe there's something I didn't think of, but
I'd need more details on your part if that is the case, because I
really can't see the advantage of Queue in this situation...

Thanks,
Stéphane
--
http://mail.python.org/mailman/listinfo/python-list


Re: question about xrange performance

2009-04-18 Thread ~flow
 [soapbox]
 Speaking about idiomacy, ...
 [end soapbox]

soapbox]
I ALREADY STEPPED DOWN FROM SOAPBOX (on this topic)
[end soapbox]

thanks for the comment anyhow.

that an efficient `x in y` implementation used to be there and is gone
now is gross. guess i'll just have to live with my own makeshift
implementation. gross.

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


Re: send() to a generator in a for loop with continue(val)??

2009-04-18 Thread Michele Simionato
On Apr 18, 3:03 pm, a...@pythoncraft.com (Aahz) wrote:
 In article gsc7e1$rj6$0...@news.t-online.com,
 Peter Otten  __pete...@web.de wrote:



 If it were up to me I'd rip out send() immediatly. At first I thought I
 would see a compelling use case and be enlightened, but it never happened.

 Too late -- it's likely to get an upgrade for 3.1 and 2.7.  Basically,
 send() is useful for coroutines, and if you haven't yet 
 readhttp://dabeaz.com/coroutines/
 you really should (assuming you want to continue arguing).
 --

I suspect Peter knows everything about coroutines and still he is not
convinced about
.send. FWIW, I am sympathic with him.

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


Re: Too early implementation

2009-04-18 Thread alex23
On Apr 18, 9:48 pm, Filip Gruszczyński grusz...@gmail.com wrote:
 With Python you rarely are sorry, because you can do everything so
 quickly. And yet, at some point you see, that flaws in design get so
 annoying, that you need to do something about them. Usually at that
 point it's a bit problematic ;-)

 So, do you know some good methods to prevent myself from just starting
 coding (which I like very much) and do some thinking about the problem
 (which I like a little less ;-))?

Try test-driven development: 
http://en.wikipedia.org/wiki/Test-driven_development
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a programming language that is combination of Python and Basic?

2009-04-18 Thread Stef Mientki

BJörn Lindqvist wrote:

I first started programming basic and i don't think it has hurt me much.


I can somewhat sympathise with the op, neither python nor any other
mainstream language can still do this:

SCREEN 13
PSET 160,100,255
  
Maybe, who is able to understand such nosense without a lot of apriori 
knowledge ?

cheers,
Stef
--
http://mail.python.org/mailman/listinfo/python-list


Re: Too early implementation

2009-04-18 Thread stephane . bisinger
On Apr 18, 12:48 pm, Filip Gruszczyński grusz...@gmail.com wrote:
 So, do you know some good methods to prevent myself from just starting
 coding (which I like very much) and do some thinking about the problem
 (which I like a little less ;-))?

Well you know, the thing is that according to Pike  Kernighan in The
Practice of Programming, your first implementation of a program
should be scrapped and rewritten from scratch, so your approach might
not be that wrong after all.
The trouble is that if you overthink your code, you'll end up losing
interest in the project and write bloated code that may be too generic
for what you need. So either way there can be trouble, although it is
right to try to balance yourself in between these two extremes...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Your confirmation is required to join the Python-list mailing list

2009-04-18 Thread Mads Nielsen
Hello.

i was wondering if there would be someone on the list that know of or have
ideas for a beginner python project ?
i have made a simple calculator Program with a if else loop. and such. but
i need a new project.

i know xml. html. css. and a bit JavaScript. so it can incorporate any or
all of those languages.

Any help / ideas are very much appreciated.

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


Re: can't install new modules after updating python

2009-04-18 Thread John
On Apr 18, 9:00 am, a...@pythoncraft.com (Aahz) wrote:
 In article 
 f2a25d72-5e21-498a-95a4-59045f158...@r37g2000yqn.googlegroups.com,

 Generally speaking, you should never directly update the system Python;
 most Linux systems these days rely on Python for their operation.
 Instead, you install an additional copy of Python, and you cannot use
 your OS package management to install modules; just install the modules
 manually.

Agreed. I tend to keep my own Python installation in ~/opt, and then
use the usual `python setup.py install` to install modules. You just
need to make sure you have $HOME/opt/py/bin in your $PATH before the
system python (or else explicitly specify `~/opt/py/bin/python
setup.py install` when you install modules).

If your *system* Python needs modules, you install those with your OS
package management utility.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a programming language that is combination of Python and Basic?

2009-04-18 Thread MRAB

Steven D'Aprano wrote:

On Fri, 17 Apr 2009 14:00:18 -0700, Mensanator wrote:


On Apr 17, 3:37 pm, baykus baykusde...@gmail.com wrote:

Hi

I am looking for one of those experimental languages that might be
combination of python+basic. Now thta sounds weird and awkward I know.

That's a clue you won't find anyone seriously contemplating such idiocy.


The reason I am asking is that I always liked how I could reference-
call certain line number back in the days.

A bad idea. If you really want to write bad code, learn C.


It would be interesting to get similar functionality in Python.

Yeah, it would interesting just as a train wreck is interesting, as
long as you're not the one who has to live through it.


Nevertheless, somebody *has* implemented such functionality in Python. 
Not just GOTO, but also COMEFROM.


http://entrian.com/goto/

 
I once translated a BASIC program to Pascal (hint: no goto allowed). 


Pascal has GOTOs. People rarely used them, because even in the 1970s and 
80s they knew that unstructured gotos to arbitrary places was a terrible 
idea.


GOTO in Pascal required that you defined a label in your code, then you 
could jump to that label. You can't jump to arbitrary parts of the 
program, only within the current procedure.



What I found strange was that labels could be only unsigned integers,
but they still had to be declared:

label 1, 2, 3;

Fortunately the version(s) I used (TurboPascal/Dephi) permitted
identifiers.
--
http://mail.python.org/mailman/listinfo/python-list


Re: class variables and class methods

2009-04-18 Thread Aahz
In article 9c848013-2245-455e-bb30-48e430d56...@j9g2000prh.googlegroups.com,
 krishnaposti...@gmail.com wrote:

I have a class whose job is to serve several other objects,  [...]

Sorry, I'm finding it difficult to understand what you want.  It looks
to me that you're confusing object and instance, and I think you're
also confusing variable and attribute.  You might find it helpful to
read the following URLs and then re-post with new phrasing:

http://docs.python.org/tutorial/classes.html
http://starship.python.net/crew/mwh/hacks/objectthink.html
http://effbot.org/zone/python-objects.htm
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur.  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: send() to a generator in a for loop with continue(val)??

2009-04-18 Thread Aahz
In article 07ad771b-a6d1-4f08-b16c-07caf7462...@e18g2000yqo.googlegroups.com,
Michele Simionato  michele.simion...@gmail.com wrote:
On Apr 18, 3:03=A0pm, a...@pythoncraft.com (Aahz) wrote:
 In article gsc7e1$rj6$0...@news.t-online.com,
 Peter Otten =A0__pete...@web.de wrote:

If it were up to me I'd rip out send() immediatly. At first I thought I
would see a compelling use case and be enlightened, but it never happened.

 Too late -- it's likely to get an upgrade for 3.1 and 2.7. Basically,
 send() is useful for coroutines, and if you haven't yet read
http://dabeaz.com/coroutines/
 you really should (assuming you want to continue arguing).

I suspect Peter knows everything about coroutines and still he is not
convinced about .send. FWIW, I am sympathic with him.

Okay, I'm curious, is the argument that you shouldn't use generators for
coroutines or something else?
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur.  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: Condition.wait(0.5) doesn't respect it's timeout

2009-04-18 Thread Aahz
In article 8373c927-5ef2-4511-a439-25caa3fd6...@v15g2000yqn.googlegroups.com,
 stephane.bisin...@gmail.com wrote:
On Apr 18, 2:05=A0pm, a...@pythoncraft.com (Aahz) wrote:

 Whether or not there's a bug, you likely will simplify your code if you
 switch to using a Queue().

I'm sorry, but I can't see how the queue would help me on this, since
I only have 2 threads and the documentation esplicitly states that it
helps with multiple threads. I have no items to put in the queue, my
only concern is not to update the screen while I am changing the state
of the contact list... Maybe there's something I didn't think of, but
I'd need more details on your part if that is the case, because I
really can't see the advantage of Queue in this situation...

Essentially, you use the Queue instead of the Condition.  When you want
to explicitly give up control in a thread, you get() on the Queue until
you get an object (with the optional timeout).  When the other thread is
done processing, it puts an object on the Queue (optionally doing a
get_nowait() at some point if it wants to make sure the Queue is cleaned
up).

The critical advantage of using Queue is that you don't have to do the
acquire()/release() dance.

It's not so much that there's an advantage to using Queue in this one
specific case as the fact that you can use Queue for almost everything
you'd use other kinds of locking mechanisms, so you can reduce your
mental model for dealing with threading.
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur.  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: Condition.wait(0.5) doesn't respect it's timeout

2009-04-18 Thread stephane . bisinger
On Apr 18, 4:28 pm, a...@pythoncraft.com (Aahz) wrote:
 Essentially, you use the Queue instead of the Condition.  When you want
 to explicitly give up control in a thread, you get() on the Queue until
 you get an object (with the optional timeout).  When the other thread is
 done processing, it puts an object on the Queue (optionally doing a
 get_nowait() at some point if it wants to make sure the Queue is cleaned
 up).

Yep but as I said I have nothing to pass around

 The critical advantage of using Queue is that you don't have to do the
 acquire()/release() dance.

And neither do I have to using the with statement ;)

 It's not so much that there's an advantage to using Queue in this one
 specific case as the fact that you can use Queue for almost everything
 you'd use other kinds of locking mechanisms, so you can reduce your
 mental model for dealing with threading.

That surely helps not making synchronization errors, but I like fully
understanding the concept even if it means being bitten by it! But
thanks for your tips, they will surely be helpful in some other
situation...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Too early implementation

2009-04-18 Thread Aahz
In article f317e00e-042c-4894-83dc-bdd83fbbe...@y7g2000yqa.googlegroups.com,
 stephane.bisin...@gmail.com wrote:

Well you know, the thing is that according to Pike  Kernighan in The
Practice of Programming, your first implementation of a program
should be scrapped and rewritten from scratch, so your approach might
not be that wrong after all.

This observation was originally made in _The Mythical Man-Month_ by Fred
Brooks, which ought to be required reading for all programmers.
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur.  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: Too early implementation

2009-04-18 Thread stephane . bisinger
On Apr 18, 4:44 pm, a...@pythoncraft.com (Aahz) wrote:
 This observation was originally made in _The Mythical Man-Month_ by Fred
 Brooks, which ought to be required reading for all programmers.

I miss that one, yet :( Nice to know, though
--
http://mail.python.org/mailman/listinfo/python-list


Re: Condition.wait(0.5) doesn't respect it's timeout

2009-04-18 Thread Aahz
In article 19475d1c-ee83-4466-ba55-b352ea760...@x5g2000yqk.googlegroups.com,
 stephane.bisin...@gmail.com wrote:
On Apr 18, 4:28=A0pm, a...@pythoncraft.com (Aahz) wrote:

 Essentially, you use the Queue instead of the Condition. =A0When you want
 to explicitly give up control in a thread, you get() on the Queue until
 you get an object (with the optional timeout). =A0When the other thread i=
s
 done processing, it puts an object on the Queue (optionally doing a
 get_nowait() at some point if it wants to make sure the Queue is cleaned
 up).

Yep but as I said I have nothing to pass around

You create it -- it's essentially a plain sentinel in this case.

 The critical advantage of using Queue is that you don't have to do the
 acquire()/release() dance.

And neither do I have to using the with statement ;)

Fair enough -- I was stuck on Python 2.3 in my last job and I still
haven't caught up.
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur.  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] large db question about no joins

2009-04-18 Thread Martin P. Hellwig

Daniel Fetchinson wrote:
cut

Thanks, this wikipedia entry was actually very useful as well as your
other comments.

Thanks again,
Daniel



Your welcome, I usually take quite a lot of effort into designing before 
I start coding. One tool I found very helpful was DIA, especially the 
UML section. Have a look at it you might find it useful.

http://projects.gnome.org/dia/

--
MPH
http://blog.dcuktec.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: need to start a new project , can python do all that ?

2009-04-18 Thread Tim Rowe
2009/4/17 Hyuga hyugaricd...@gmail.com:

 I'm not too assured... What are the actual requirements for this
 software?  Is this intended for real world use in health care?  I'm
 not too comfortable with a single individual with apparently limited
 experience in Python developing something like that.

And limited experience in safety-related systems, if he thinks safety
can be tested in, after the event.

But of course it might be that the proposed system has gone through a
proper safety analysis, and it /might/ have been determined that there
are no safety or security risks with it, in which case there would be
no reason for him not to cut his Python teeth (fangs?) on it.

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


Re: Is there a programming language that is combination of Python and Basic?

2009-04-18 Thread Steven D'Aprano
On Sat, 18 Apr 2009 13:39:23 +0200, BJörn Lindqvist wrote:

 I first started programming basic and i don't think it has hurt me much.
 
 I can somewhat sympathise with the op, neither python nor any other
 mainstream language can still do this:
 
 SCREEN 13
 PSET 160,100,255

Maybe, maybe not. What on earth does it do?



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


Re: Is there a programming language that is combination of Python and Basic?

2009-04-18 Thread D'Arcy J.M. Cain
On 18 Apr 2009 16:29:30 GMT
Steven D'Aprano st...@remove-this-cybersource.com.au wrote:
 On Sat, 18 Apr 2009 13:39:23 +0200, BJörn Lindqvist wrote:
  SCREEN 13
  PSET 160,100,255
 
 Maybe, maybe not. What on earth does it do?

It makes people scratch their heads and wonder what the hell it does.

-- 
D'Arcy J.M. Cain da...@druid.net |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a programming language that is combination of Python and Basic?

2009-04-18 Thread Tim Rowe
2009/4/18 norseman norse...@hughes.net:

 ...only within the current procedure.   That was one of the why Pascal
 didn't hang on as long as it might have.

Really? I thought it was because of the lack of support for packaging,
which was solved in different ways by Object Pascal/Delphi and by
Modula 2, the latter of which in turn became Ada, which is still doing
pretty well in mission-critical contexts.

  Another was it's COBAL structure
 in defining things. Just like today - the more typing the more errors, the
 longer to 'in service'.

Got any evidence for that? There's a lot of typing in Ada (it shows
its Pascal roots) but in all the studies I've seen Ada production code
has consistently shown fewer errors than the more concise C/C++ family
of languages.

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


Re: question about xrange performance

2009-04-18 Thread Steven D'Aprano
On Sat, 18 Apr 2009 13:05:34 +0200, mmanns wrote:

 On Fri, 17 Apr 2009 23:40:32 -0700 (PDT) bearophileh...@lycos.com wrote:
 
 Paul McGuire:
 
 xrange is not really intended for in testing,
 
 Let's add the semantic of a good and fast in to xrange (and to the
 range of Python3). It hurts no one, allows for a natural idiom
 (especially when you have a stride you don't want to re-invent the
 logic of skipping absent numbers), and it's readable.
 
 A fast in to xrange would be great. Why was it taken away?


http://docs.python.org/whatsnew/2.2.html#other-changes-and-fixes

Some features of the object returned by the xrange() function are now 
deprecated, and trigger warnings when they’re accessed; they’ll disappear 
in Python 2.3. xrange objects tried to pretend they were full sequence 
types by supporting slicing, sequence multiplication, and the in 
operator, but these features were rarely used and therefore buggy. The 
tolist() method and the start, stop, and step attributes are also being 
deprecated. At the C level, the fourth argument to the PyRange_New 
function, repeat, has also been deprecated.



You may also want to read these:

http://mail.python.org/pipermail/python-3000/2007-August/009061.html
http://mail.python.org/pipermail/patches/2004-August/015501.html



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


Re: Is there a programming language that is combination of Python and Basic?

2009-04-18 Thread Aahz
In article mailman.4112.1240072722.11746.python-l...@python.org,
Tim Rowe  digi...@gmail.com wrote:

Really? I thought it was because of the lack of support for packaging,
which was solved in different ways by Object Pascal/Delphi and by
Modula 2, the latter of which in turn became Ada, which is still doing
pretty well in mission-critical contexts.

blink  I had never previously heard that Modula-2 significantly
influenced Ada, and the Wikipedia entry says nothing about it.  Do you
have a cite?
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur.  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: Too early implementation

2009-04-18 Thread Filip Gruszczyński
Yep, I have heard a lot about test driven development. I am now
programming a lot using DJango and I would like to use its test
framework to try it. However, I have little experience with this (as
most people I know). I also have no idea, how to apply this, when I
write code heavily focused on user interface.

I thought, that prototyping is cool, especially with python, where you
can create something functional pretty quickly. But recently I was met
with a situation, when after writing 1k lines of prototype and then
writing main program  3k lines I noticed, that there is something
really wrong with the design. It was then, that I started wondering:
maybe I should first prepare some good design documents, I don't know
some SAD or something.

-- 
Filip Gruszczyński
--
http://mail.python.org/mailman/listinfo/python-list


[no subject]

2009-04-18 Thread karlos barlos
i have the following code :

   elif choice == 3:
    print all users list :
    print\n
    import active_directory
    for user in active_directory.search (objectCategory='Person', 
objectClass='User'):
 print user
    
i want to write  the output of the code (

LDAP://CN=bessy,OU=sales,DC=shay,DC=com
LDAP://CN=ron,OU=legal,DC=shay,DC=com

to a text \  csv file ... 

can any one help ??


 








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


Re: Is there a programming language that is combination of Python and Basic?

2009-04-18 Thread Tim Chase

SCREEN 13
PSET 160,100,255


Maybe, maybe not. What on earth does it do?


I believe this attempts to set screen-mode 13 (I'm surprised this 
isn't a hex constant, though that may be a (Q)Basic quirk), which 
for older VGA cards was 320x200 with 256-colors.  It then looks 
like it sets a point at (160,100 = the middle of the screen) in 
color #255.


Ah, back in the days where each application had to maintain the 
screen itself, and you had to use hacks to get square pixels (the 
320x200 in this mode had a non-square aspect-ratio) in Mode-X. 
Can't say I miss it much beyond nostalgia.


-tkc



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


Re:

2009-04-18 Thread Joe Riopel
On Sat, Apr 18, 2009 at 12:56 PM, karlos barlos karlosbar...@yahoo.com wrote:
 LDAP://CN=bessy,OU=sales,DC=shay,DC=com
 LDAP://CN=ron,OU=legal,DC=shay,DC=com

 to a text \  csv file ...

 can any one help ??

Have a look at this:
http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files

and this:
http://docs.python.org/library/csv.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Too early implementation

2009-04-18 Thread stephane . bisinger
On Apr 18, 5:54 pm, Filip Gruszczyński grusz...@gmail.com wrote:
 Yep, I have heard a lot about test driven development. I am now
 programming a lot using DJango and I would like to use its test
 framework to try it. However, I have little experience with this (as
 most people I know). I also have no idea, how to apply this, when I
 write code heavily focused on user interface.

One of the most complete testing suites I know of is jUnit, even
though you don't know Java, it may still be useful to you understand
how the thing works. There is also a pyunit framework, but I fear that
jUnit has a better overall documentation - anyway the concepts are
similar.

 I thought, that prototyping is cool, especially with python, where you
 can create something functional pretty quickly. But recently I was met
 with a situation, when after writing 1k lines of prototype and then
 writing main program  3k lines I noticed, that there is something
 really wrong with the design. It was then, that I started wondering:
 maybe I should first prepare some good design documents, I don't know
 some SAD or something.

My experience with design documents and all is that you end up not
following them anyway because when you start to code you also start to
realize you forgot something. Software Engineering would have you fall
back to redesign to include the new stuff in, but I've hardly ever
seen that happen. Of course you can try, because what works for me
could not be working for you... The thing with software engineering is
that nobody has found a good answer to these problems yet, no matter
what they claim. Every approach has its advantages and its drawbacks,
it is up to you to find your own way to deal with this kind of problems
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lambda alternative?

2009-04-18 Thread Hrvoje Niksic
Duncan Booth duncan.bo...@invalid.invalid writes:

 import cPickle as p
 p.dumps([])
 '(l.'
 p.dumps([].append)
 Traceback (most recent call last):
   File stdin, line 1, in module
 TypeError: expected string or Unicode object, NoneType found

 Not the best of examples: [].append is a built-in method rather than a 
 bound method.

Sorry about the confusion.  By bound method I meant the callable
obtained by binding a method (built-in or written in python) to a
concrete instance, as opposed to an unbound method, such as
list.append.  The reprs are different for built-in methods and for
python methods, but I consider that difference an artifact of the
CPython implementation, not a distinction mandated by the language.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Too early implementation

2009-04-18 Thread Patrick Mullen
2009/4/18 Filip Gruszczyński grusz...@gmail.com:
 Yep, I have heard a lot about test driven development. I am now
 programming a lot using DJango and I would like to use its test
 framework to try it. However, I have little experience with this (as
 most people I know). I also have no idea, how to apply this, when I
 write code heavily focused on user interface.

There are many testing frameworks to choose from with regards to
interface, but at least starting with unit tests (which don't need to
interact with the interface) will still gain you something, and help
guide the design probably a little better than interface tests at
that.  My style of TDD is to alternate somewhat between the code and
the tests. When that idea pops into my head about how to do something,
I will either write a test OR write the code to make it work,
depending on what my inspiration is. If the inspiration is API
related, then the test gets written first, because what is in my head
are really interface stuff and not implementation. On the other hand,
if my inspiration is code/implementation related, I will write the
code. Afterward, I will switch and write the other piece, which sort
of backs up whatever my decision was (or doesn't).

I don't follow this exactly, it's just my general coding style when I
am using tests.

Sometimes I don't use tests at all (they aren't quite as helpful in
game programming as in other domains), and in those cases I generally
try to refactor or clean up my code before a script gets too long,
where too long means I am getting frustrated at not being able to find
where to fix problems or add features fast enough. In practice, this
usually means writing about 800-1000 lines of code in one script, and
then exploding one script into several.

 I thought, that prototyping is cool, especially with python, where you
 can create something functional pretty quickly. But recently I was met
 with a situation, when after writing 1k lines of prototype and then
 writing main program  3k lines I noticed, that there is something
 really wrong with the design. It was then, that I started wondering:
 maybe I should first prepare some good design documents, I don't know
 some SAD or something.


It's pretty hard to design very much up front, because when you get
into the code things change. Maybe if you do some coding and then
start designing as you go to keep yourself on the right track.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Too early implementation

2009-04-18 Thread Kay Schluehr
Start to like blogging about your ideas, results and findings. Writing
is a process of clarification of the mind. It doesn't matter much
whether you design upfront, or mix coding and writing in an
incremental process. If I could I'd just write specs, draft my ideas
in Python in order to verify that I really know what I'm talking about
and let others work out the details. Of course I'm not in the splendid
position of a university professor or an intellectual capitalist.
--
http://mail.python.org/mailman/listinfo/python-list


__getattribute__ for operators

2009-04-18 Thread Michael
While thinking about Steven D'Aprano's thread about automatically
generating arithmetic operations for a subclass, I stumbled upon
something confusing.  Having defined the following class to do funky
addition,

class MyInt(int):
def __getattribute__(self, key):
if key == __add__:
print(In __getattribute__('__add__'))
return lambda other: MyInt(int.__add__(self, other+100))
else:
return object.__getattribute__(self, key)

def __getattr__(self, key):
if key == __add__:
print(In __getattr__('__add__'))
return lambda other: MyInt(int.__add__(self, other+100))
else:
return object.__getattr__(self, key)

I then do this:

 a = MyInt(4)
 a.__add__(2)
In __getattribute__('__add__')
106
 a + 2
6


Why doesn't a + 2 look up the __add__ attribute and use my lambda?
If I manually define __add__(self, other) then a + 2 will of course
use that method.

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


Re: after_cancel?

2009-04-18 Thread Saul Spatz

W. eWatson wrote:
I'm looking a program that I'm not real familiar with that uses an 
after_cancel method and after_id variable.  Are they related to some 
particular widget and what is there function? Perhaps they are related 
to a Cancel button on a widget?


http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm
--
http://mail.python.org/mailman/listinfo/python-list


Re:

2009-04-18 Thread karlos barlos


--- On Sat, 4/18/09, Joe Riopel goo...@gmail.com wrote:

From: Joe Riopel goo...@gmail.com
Subject: Re:
To: karlos barlos karlosbar...@yahoo.com
Cc: python-list@python.org
Date: Saturday, April 18, 2009, 12:01 PM

On Sat, Apr 18, 2009 at 12:56 PM, karlos barlos karlosbar...@yahoo.com wrote:
 LDAP://CN=bessy,OU=sales,DC=shay,DC=com
 LDAP://CN=ron,OU=legal,DC=shay,DC=com

 to a text \  csv file ...

 can any one help ??

can some one give my an exmple on how to pipe the output into a csv. file ??



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


Re: Condition.wait(0.5) doesn't respect it's timeout

2009-04-18 Thread Piet van Oostrum
 Gabriel Genellina gagsl-...@yahoo.com.ar (GG) wrote:

GG If another thread has acquired the lock, cond.wait() doesn't return. Add
GG these lines at the end of your test and see:

GG sleep(2)
GG print Main thread - cond.acquire()
GG cond.acquire()
GG sleep(2)
GG print Main thread - cond.release()
GG cond.release()
GG sleep(2)
GG sys.exit()

GG The timeout is detected, but the wait method doesn't return, it's stuck at
GG the last line (trying to restore a saved RLock state).
GG I don't understand the logic behind that.

That is the semantics of a Condition. The cond.wait() must be done in a
critical section, i.e. when the thread has acquired the lock. The wait()
temporarily releases the lock so that another thread can try to make the
way free for the waiting thread and give a notify(). When the wait()
continues it must first re-acquire the lock to make sure it has
exclusive access to the critical section. If another thread still has
the lock it has to wait for the lock being released. This is also the
case when the wait continues because the timeout has expired.

GG Please file a bug report at http://bugs.python.org/

It is not a bug. I see the Hello World temporarily suspended and then
continuing. That's how it should be.
-- 
Piet van Oostrum p...@cs.uu.nl
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyqt4 qTableWidget add items help

2009-04-18 Thread ookrin
On Apr 18, 3:46 am, Sebastian Wiesner basti.wies...@gmx.net wrote:
 -BEGIN PGP SIGNED MESSAGE-
 Hash: SHA1

 ookrin – Samstag, 18. April 2009 11:58

 [...] I've been trying

          while(len(orders) i):
              ui.tb1_tblOrders.setCurrentCell(i,0,orders[i][1])
              i+=1

  which to me, says go add in the first column row with the first order,
  and it makes sense to me

 Read the documentation [1] to learn, what .setCurrentCell() actually does
 and what its arguments are!  And please stop this wild guessing ...

 The method you're searching for is .setItem() [2], which adds a new
 QTableWidgetItem [3] to a QTableWidget.

 [1]http://doc.trolltech.com/4.5/qtablewidget.html#setCurrentCell
 [2]http://doc.trolltech.com/4.5/qtablewidget.html#setItem
 [3]http://doc.trolltech.com/4.5/qtablewidgetitem.html

 - --
 Freedom is always the freedom of dissenters.
                                       (Rosa Luxemburg)
 -BEGIN PGP SIGNATURE-
 Version: GnuPG v2.0.11 (GNU/Linux)

 iEYEARECAAYFAknpr4sACgkQGV4vxEMMOxdnawCfTXO55EffBJMQ7h91RGtMIpZ/
 hcYAoLQ9yF5u/hBgNRvqxGRlIy5lPDgb
 =Q6ef
 -END PGP SIGNATURE-

I forgot to include what I tried first.
setCurrentItem was just the last thing I was on at the time.

First I filled out a row in Designer to see how it loads the items. It
loads like this:
self.tb1_tblOrders.item(0, 0).setText(QtGui.QApplication.translate
(MainWin, Date, None, QtGui.QApplication.UnicodeUTF8))

Ok following that example:

ui.tb1_tblOrders.item(0,0).setText(QtGui.QApplication.translate
(MainWindow,order[0][1], None,QtGui.QApplication.UnicodeUTF8))

AttributeError: 'NoneType' object has no attribute 'setText'

So reading through the QTableWidget Doc I see the setItem

setItem(int,int, QTableWidgetItem * item)
QTableWidgetItem*item ???

The only example on the entire page:

 QTableWidgetItem *newItem = new QTableWidgetItem(tr(%1).arg(
 pow(row, column+1)));

is that setup as c++ ? Ok, it's a class.

twi = QTableWidgetItem()
 newItem = twi(order[i][0])
ui.tb1_tb1Orders.setItem(i,0,newItem)

NameError: global name 'QTableWidgetItem' is not defined

At the top of the page
include QTableWidgetItem
from PyQt4 import  ?? QtGui? QtCore? Those are already loaded   other
options are pyqtconfig and uic and those don't sound correct...

And that's what I did first. Then I started guessing in the next
logical order, not wildly. editItem, setCurrentItem, setCurrentCell.
Then I came here. So I guess I actually stuck at the QTableWidgetItem
thing, I should have made that a little more clearer first post.

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


Re: any complete and actual pysqlite example?

2009-04-18 Thread Philip Semanchuk


On Apr 18, 2009, at 8:59 AM, oyster wrote:


I mean not a code to do seperated functions, but a real project

I have read the doc of pysqlite, but since I know little about
database, I found it is still very hard for me to cook a real database
app from the scratch with the help of codelet in pysqlite doc. here is
the simplified details:
[TABLE 1]
bookName text
price num
author -- this is actually linked with the [TABLE 2], for one author
maybe write many books, I think it is better to do an external link
[/TABLE 1]

[TABLE 2]
authorName text
[/TABLE 2]

Then
[record  for TABLE 1]
id  bookName  price authoridx
1   The Definitive Guide to SQLite  30  1
2   Core Python 40  2
3   Dive Into Python35  3
[/record  for TABLE 1]

[record  for TABLE 2]
id  authorName
1   Michael Owens
2   Wesley J. Chun
3   Mark Pilgrim
[/record  for TABLE 2]

what I need
1. of cause, create the TABLE, and add real data into it. I don't know
how to deal with the author item in [TABLE 1]

2. list the data. A question is, when I list the record in [TABLE 1],
can I get something like following?
The Definitive Guide to SQLite, 30.0, Michael Owens
I mean, the authorName is returned automatically, but not only the  
authoridx


3. what if I del the 1st record in [TABLE 2] since a record in  
[TABLE 1] use it?


4.I want to do some group, for example, group the record in [TABLE 1]
according to their price, so that
[30]
  Book1Name
  Book2Name
[40]
  Book3Name
[50]
  Book4Name
  Book4Name
does sqlite support this? or I have to do this in python?


Hi Oyster,
It sounds like you're trying to learn several things at once. You  
might find it easier to separate them so you can learn one thing at a  
time.


Your questions are mostly about SQL and relational databases, not  
Python or Python's interface to SQLite. Once you have a better  
understanding of SQL and SQLite, the Python interface will make more  
sense to you.


In order to learn SQLite, I suggest that you install it and play with  
it on its own. There are probably precompiled binaries for your  
platform:

http://www.sqlite.org/download.html

SQLite comes with a command line client similar to Python's  
interactive shell, so you can enter database commands interactively  
and see their output, like so:


$ sqlite3
SQLite version 3.4.0
Enter .help for instructions
sqlite CREATE TABLE books
   ... (
   ... id  INTEGER NOT NULL PRIMARY KEY  
AUTOINCREMENT,

   ... nameTEXT,
   ... price   REAL,
   ... author_id   INTEGER
   ... )
   ... ;
sqlite CREATE TABLE authors
   ... (
   ... id  INTEGER NOT NULL PRIMARY KEY  
AUTOINCREMENT,

   ... nameTEXT
   ... )
   ... ;
sqlite
sqlite INSERT INTO
   ... authors (name)
   ... VALUES
   ... ('Mrs. Premise');
sqlite
sqlite INSERT INTO
   ... authors (name)
   ... VALUES
   ... ('Mrs. Conclusion');
sqlite
sqlite SELECT
   ... *
   ... FROM
   ... authors;
id  name
--  
1   Mrs. Premise
2   Mrs. Conclus
sqlite

To answer your specific questions:

what I need
1. of cause, create the TABLE, and add real data into it. I don't know
how to deal with the author item in [TABLE 1]


There's sample create table statements above. The author_id in the  
books table in my example is called a foreign key. You should read  
more about them.




2. list the data. A question is, when I list the record in [TABLE 1],
can I get something like following?
The Definitive Guide to SQLite, 30.0, Michael Owens
I mean, the authorName is returned automatically, but not only the  
authoridx


Yes, using something called a JOIN:

sqlite INSERT INTO
   ... books (name, price, author_id)
   ... VALUES
   ... ('The Big Book of Nonsense', 30.00, 1);
sqlite INSERT INTO
   ... books (name, price, author_id)
   ... VALUES
   ... ('Jean Paul Satre Goes to the Chemist', 25.00, 2);
sqlite
sqlite SELECT
   ... books.name, books.price, authors.name
   ... FROM
   ... books, authors
   ... WHERE
   ... books.author_id = authors.id;
name  price   name
  --  
The Big Book of Nonsense  30.0Mrs. Premise
Jean Paul Satre Goes to   25.0Mrs. Conclus
sqlite

3. what if I del the 1st record in [TABLE 2] since a record in  
[TABLE 1] use it?


That's a problem! =) In a relational database you want to preserve  
something called referential integrity. That means that if one table  
refers to records in another table, you want to make sure that the  
thing being referred to doesn't disappear. The SQL standard helps you  
to defend against this problem with something called a foreign key  
constraint. When you applied correctly, the database won't let you  
delete a record if something is referring to it.



Re: Is there a programming language that is combination of Python andBasic?

2009-04-18 Thread Brian Blais

On Apr 18, 2009, at 5:44 , Hendrik van Rooyen wrote:


baykus b..@gmail.com wrote:



I guess I did not articulate myself well enough. I was just looking
for a toy to play around. I never suggested that Python+Basic  
would be

better than Python and everyone should use it. Python is Python and
Basic is Basic. I am not comparing them at all. I understand the
merits of Python but that does not mean I can play with ideas?


Apparently this is not allowed by the CS thought police.





to untangle some spaghetti code.  He did not mention if
the spaghetti was actually doing it's job, bug free, which
IMO is the only rational test for the quality of a piece
of code, because it is the reason for its existence.
The aesthetics are, like all aesthetics, a matter of opinion.


Actually, I strongly disagree with this statement.  In my experience,  
there has been very very few pieces of code that I've written that I  
hadn't wanted to *modify* at some point: extend it to a new set of  
circumstances, cover a different case, change the output, etc...  The  
quality of a piece of code is not just if it works right now, but if  
you can reasonably extend it for the future.  I toyed with Perl for a  
year or so, but couldn't give it my full attention.  As a result,  
every few weeks when I wanted to modify what I wrote, I had to re- 
learn the code all over again because the syntax was so terse.  The  
same is true for the typical use of a goto: you have to relearn the  
program, because the flow jumps around.  It's not just about  
aesthetics, but about being able to work with a piece of code.



bb


--
Brian Blais
bbl...@bryant.edu
http://web.bryant.edu/~bblais



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


Re: Is there a programming language that is combination of Python andBasic?

2009-04-18 Thread Mensanator
On Apr 18, 4:44 am, Hendrik van Rooyen m...@microcorp.co.za wrote:
 baykus b..@gmail.com wrote:
  I guess I did not articulate myself well enough. I was just looking
  for a toy to play around. I never suggested that Python+Basic would be
  better than Python and everyone should use it. Python is Python and
  Basic is Basic. I am not comparing them at all. I understand the
  merits of Python but that does not mean I can play with ideas?

 Apparently this is not allowed by the CS thought police.

 The reasoning is based on an Argument from Authority,
 namely the Dijkstra link.

 Now it looks to me when I read that article, that the jump
 is deprecated because it leads to code that is difficult to
 understand, which was based on the difficulty that Dijkstra
 had to construct a co-ordinate system for storing the state
 of a program at any given line of code.  This was done
 without giving any reason as to why this should be important,
 or even desirable, except towards the end where he wanted to
 define instances in time when a count could conceivably be
 off by one, and he asserted without proof that having jumps
 in the code makes this more difficult.  Even if this assertion
 were to be provably true, it does not really follow that jumps
 should be banned, but merely that one runs such a risk if one
 were to use them.  Now to some minds, this difficulty may
 not be a difficulty at all:

 Processors and interrupt service routines are storing the state
 of multiple programmes at arbitrary points in the code, even
 as I type - and every one of those programmes include jumps.
 It is a non - issue.

 Mensanator had the same complaint based on difficulty
 earlier in this thread, when he described how he struggled
 to untangle some spaghetti code.  He did not mention if
 the spaghetti was actually doing it's job, bug free, which
 IMO is the only rational test for the quality of a piece
 of code, because it is the reason for its existence.  

Oh, the bugs were there, alright. But they tended to be very
subtle, so much so the original author must not have noticed them.
For instance, a players AGILITY attribute affected the player's
probability of hitting the monster he was attacking. This AGILITY
attribute was altered by the quality of the player's armor, heavier
plate armor being more adverse than light leather armor.

In most situations, the adjustment is made once at the start of
the game. Rarely is armor donned or removed during the course
of the game. But it does happen in some games. I wrote one
in which the player is captured and whatever armor he started
the game with is taken away and part of his quest, in aggition to
finding his way out of the dungeon, is to recover all the
artifacts he entered the game with (which are hidden throughout
to encourage wandering all over the layout).

One of the symptoms of the spaghetti code's jumping around instead
of doing subroutine returns was failure of the armor algorithm to
properly adjust the AGILITY when armor is removed. The result was
that AGILITY was only ever adjusted downwards, and never restored
if it was taken off. If the player then subsequently donned it again,
AGILITY would be further reduced.

The same type of subtlty occured with monster COURAGE. Any monster
(including the friendly ones who fought on your side) that didn't
have a COURAGE rating of 100 was supposed to flee the room if a
certain level of damage was taken. Again, because of goto screwups,
such behaviour was rarely seen. Once corrected, it happened quite
frequently, so much so that it affected the overall game itself.

With the entire dynamic of the game beig very different, desingers
estimates on how many monsters to place in a given scenario were
all incorrect.

 The aesthetics are, like all aesthetics, a matter of opinion.

Game design isn't just a matter of aesthetics.


 I do not agree with the reasoning that effectively says:
 If it is difficult to comprehend, it must be wrong

A programmer once said to me Why should I run it, I know
how it works, I wrote it.

My reply: You only THINK you know how it works. _I_, on
the other hand, ACTUALLY know how it works because I've
run it.


 If this were to be a tenet, then using the pickle module
 should be forbidden too, as it is a complex piece of
 code that (to me at least) is not easily understood on a
 first read-through.

 So does that mean I must stop using pickles?

 All Strength to Arnaud for his goto code!
 I am looking forward to the gosub and return.
 :-)

 - Hendrik

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


I'm sort of mystified by the print hex to char conversion

2009-04-18 Thread grocery_stocker
I'm just really not seeing how something like x63 and/or x61 gets
converted by 'print' to the corresponding chars in the following
output...

[cdal...@localhost oakland]$ python
Python 2.4.3 (#1, Oct  1 2006, 18:00:19)
[GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
Type help, copyright, credits or license for more information.
 print '\x63had'
chad
 print '\x63h\x61d'
chad
 print \x63had
chad
 print \x63h\x61d
chad


Does print just do this magically?
--
http://mail.python.org/mailman/listinfo/python-list


Please help with problem creating class

2009-04-18 Thread auzarski2008
Hi I have been working on a homework assignment that I am having a lot
of trouble with.  I am so frustrated because every time I think I am
getting close to figuring it out there is another problem.   If you
could look at this and tell me what I am doing wrong I would very much
appreciate it

import string

from datetime import date



class Leaderapplicant:



def __init__(self, line):

#convert the lines of data into fields and removes
\n

line = line.rstrip(\n)

appname, leadername, start, end = line.split(\t)



self.appname = appname

self.leadername = leadername





, mm, dd = start.split(,)  #splits the string
into dates

b = int()

c = int(mm)

d = int(dd)

self.start = date(b,c,d)





, mm, dd = end.split(,)

b = int()

c = int(mm)

d = int(dd)

self.end = date(b, c, d)





def getAppname(self):

return self.appname



def getLeadername(self):

return self.leadername



def getStart(self):

return self.start



def getEnd(self):

return self.end



def getSomething(self):

# infoStr is a tab separated line: name leadername startdate
enddate



return self.appname + \t + self.leadername + \t +
self.start + \t + self.end



#import Leader Applicant



def get_files():
infile = raw_input(What file is the data in? )
outfile = raw_input(What file would you like the data to go
in? )
return infile, outfile




def main():


#recall get_files function
files = get_files()

#open files
infile = open(files[0], 'r')
outfile = open(files[1], 'w')


reportstart = raw_input(Please enter the date (, mm, dd)
the reporting period started: )

, mm, dd = string.split(reportstart, ,)

 = int()

mm  = int(mm)

dd  = int(dd)

reportstartdate= date(, mm, dd)



reportend = raw_input(Please enter the date (, mm, dd)
the reporting period ended: )

, mm, dd = string.split(reportend, ,)

 = int()

mm = int(mm)

dd = int(dd)

reportenddate = date(, mm, dd)





for line in infile:



a = Leaderapplicant(line) #from data file



if a.getEnd() = reportstartdate and a.getEnd() =
reportenddate:



outfile.write(a.getAppname())

outfile.write
(\n)





#close files



infile.close()

outfile.close()



#print The list has been written to, files[1]





if __name__ == '__main__':

main()






I am using tab separated data in another file that looks like this...


appname1   leadername12005, 02, 022006, 02, 02
appname2   leadername22006, 03, 212007, 06, 28

etc...

The error message looks like this

 back (most recent call last):
  File /home/amy/Documents/LIS452/assignment 3/testworks.py, line
97, in module
main()
  File /home/amy/Documents/LIS452/assignment 3/testworks.py, line
80, in main
a = Leaderapplicant(line) #from data file
  File /home/amy/Documents/LIS452/assignment 3/testworks.py, line 9,
in __init__
appname, leadername, start, end = line.split(\t)
ValueError: need more than 3 values to unpack

Any help would be greatly appreciated.  I have spent so much time on
this that I am behind not only in this class but in other classes as
well.
--
http://mail.python.org/mailman/listinfo/python-list


Re: question about xrange performance

2009-04-18 Thread Arnaud Delobelle
Steven D'Aprano st...@remove-this-cybersource.com.au writes:
[...]
 Speaking about idiomacy, it is grammatically incorrect to start sentences 
 in English with lower-case letters [...]
[...]

 x.0 floats working with xrange is an accident, not a deliberate design 
 decision, and has been deprecated in Python 2.6, which means it will 
 probably be gone in a few years:

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


python alternatives to C structs??

2009-04-18 Thread KoolD
Hey all,
I need to convert a C code to python please help me figure out how to
do
it.
Suppose the C program's like:


typedef struct _str
{
int a;
char *b;
int c;
}str;
int main()
{
str mbr;
fd=open(/dev/sda,O_RDONLY);
read(fd,mbr,sizeof(str));
}


Is there a way to code it in python.

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


Re: Condition.wait(0.5) doesn't respect it's timeout

2009-04-18 Thread Piet van Oostrum
 stephane.bisin...@gmail.com (SB) wrote:

SB On Apr 18, 10:24 am, Piet van Oostrum p...@cs.uu.nl wrote:
 
 I haven't run it (too much hassle to setup) but I noticed one strange
 thing in your code:
 
 ,
 | def groupUpdated(self, gView):
 |         # Acquire the lock to do modifications
 |         self._mod_lock.acquire()
 |  
 |         if not self._groups.has_key(gView.uid):
 |             return
 `
 
 In case the return is taken, the lock will not be released thereby
 blocking the rest. It could be that the timeout is taken, but before the
 wait can continue it has to acquire the lock again.

SB That is absolutely correct, but I guess with an RLock there shouldn't
SB be a deadlock... Anyway I'm fixing that!

I suppose the groupUpdated() method is called from a different thread
than the self._mod_lock.wait(timeout=1) because it contains a notify().
Otherwise your code would have been flawed. From the code you can see
that this is the case as the thread with wait in it is created here (in
aMSNContactListWidget.__init__) and it contains no calls to
groupUpdated. Therefore the RLock thing isn't applicable. It was,
however, applicable in the superfluous acquire in the loop, so it saved
you there.

Maybe you can put print statements at the beginning and end of each
with block to see if there is an unreleased lock that blocks the wait.

Some more remarks:

1. __repaint acquires the lock, but it is called from __thread_run which
has already acquired it. Because the lock is recursive it doesn't harm
but it is not necessary.

2. Importing in a thread is discouraged. I think it is cleaner to put
   the import sys in the top of the module.
3. I think I have found a bug in the Condition implementation, but I
   can't imagine you being hit by it. It would not be a reproducible one.
-- 
Piet van Oostrum p...@cs.uu.nl
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please help with problem creating class

2009-04-18 Thread MRAB

auzarski2...@gmail.com wrote:

Hi I have been working on a homework assignment that I am having a lot
of trouble with.  I am so frustrated because every time I think I am
getting close to figuring it out there is another problem.   If you
could look at this and tell me what I am doing wrong I would very much
appreciate it

import string

from datetime import date



class Leaderapplicant:



def __init__(self, line):

#convert the lines of data into fields and removes
\n

line = line.rstrip(\n)

appname, leadername, start, end = line.split(\t)



self.appname = appname

self.leadername = leadername





, mm, dd = start.split(,)  #splits the string
into dates

b = int()

c = int(mm)

d = int(dd)

self.start = date(b,c,d)





, mm, dd = end.split(,)

b = int()

c = int(mm)

d = int(dd)

self.end = date(b, c, d)





def getAppname(self):

return self.appname



def getLeadername(self):

return self.leadername



def getStart(self):

return self.start



def getEnd(self):

return self.end



def getSomething(self):

# infoStr is a tab separated line: name leadername startdate
enddate



return self.appname + \t + self.leadername + \t +
self.start + \t + self.end



#import Leader Applicant



def get_files():
infile = raw_input(What file is the data in? )
outfile = raw_input(What file would you like the data to go
in? )
return infile, outfile




def main():


#recall get_files function
files = get_files()

#open files
infile = open(files[0], 'r')
outfile = open(files[1], 'w')


reportstart = raw_input(Please enter the date (, mm, dd)
the reporting period started: )

, mm, dd = string.split(reportstart, ,)

 = int()

mm  = int(mm)

dd  = int(dd)

reportstartdate= date(, mm, dd)



reportend = raw_input(Please enter the date (, mm, dd)
the reporting period ended: )

, mm, dd = string.split(reportend, ,)

 = int()

mm = int(mm)

dd = int(dd)

reportenddate = date(, mm, dd)





for line in infile:



a = Leaderapplicant(line) #from data file



if a.getEnd() = reportstartdate and a.getEnd() =
reportenddate:



outfile.write(a.getAppname())

outfile.write
(\n)





#close files



infile.close()

outfile.close()



#print The list has been written to, files[1]





if __name__ == '__main__':

main()






I am using tab separated data in another file that looks like this...


appname1   leadername12005, 02, 022006, 02, 02
appname2   leadername22006, 03, 212007, 06, 28

etc...

The error message looks like this

 back (most recent call last):
  File /home/amy/Documents/LIS452/assignment 3/testworks.py, line
97, in module
main()
  File /home/amy/Documents/LIS452/assignment 3/testworks.py, line
80, in main
a = Leaderapplicant(line) #from data file
  File /home/amy/Documents/LIS452/assignment 3/testworks.py, line 9,
in __init__
appname, leadername, start, end = line.split(\t)
ValueError: need more than 3 values to unpack

Any help would be greatly appreciated.  I have spent so much time on
this that I am behind not only in this class but in other classes as
well.


Print out the value of 'line' using repr(). Is it what you expected?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please help with problem creating class

2009-04-18 Thread member thudfoo
On 4/18/09, auzarski2...@gmail.com auzarski2...@gmail.com wrote:
 Hi I have been working on a homework assignment that I am having a lot
  of trouble with.  I am so frustrated because every time I think I am
  getting close to figuring it out there is another problem.   If you
  could look at this and tell me what I am doing wrong I would very much
  appreciate it

  import string

  from datetime import date



  class Leaderapplicant:



 def __init__(self, line):

 #convert the lines of data into fields and removes
  \n

 line = line.rstrip(\n)

 appname, leadername, start, end = line.split(\t)

[...]


  I am using tab separated data in another file that looks like this...


  appname1   leadername12005, 02, 022006, 02, 02
  appname2   leadername22006, 03, 212007, 06, 28

  etc...

  The error message looks like this

   back (most recent call last):
   File /home/amy/Documents/LIS452/assignment 3/testworks.py, line
  97, in module
 main()
   File /home/amy/Documents/LIS452/assignment 3/testworks.py, line
  80, in main
 a = Leaderapplicant(line) #from data file
   File /home/amy/Documents/LIS452/assignment 3/testworks.py, line 9,
  in __init__
 appname, leadername, start, end = line.split(\t)
  ValueError: need more than 3 values to unpack

  Any help would be greatly appreciated.  I have spent so much time on
  this that I am behind not only in this class but in other classes as
  well.


Immediately before line 9 put the following line:

print line.split(\t)

Now run it again and see how many values are in  the list that is
printed. Your code expects that there will be exactly three.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please help with problem creating class

2009-04-18 Thread member thudfoo
Correction:

On 4/18/09, member thudfoo thud...@opensuse.us wrote:
 On 4/18/09, auzarski2...@gmail.com auzarski2...@gmail.com wrote:
   Hi I have been working on a homework assignment that I am having a lot
of trouble with.  I am so frustrated because every time I think I am
getting close to figuring it out there is another problem.   If you
could look at this and tell me what I am doing wrong I would very much
appreciate it
  
import string
  
from datetime import date
  
  
  
class Leaderapplicant:
  
  
  
   def __init__(self, line):
  
   #convert the lines of data into fields and removes
\n
  
   line = line.rstrip(\n)
  
   appname, leadername, start, end = line.split(\t)
  

 [...]


  
I am using tab separated data in another file that looks like this...
  
  
appname1   leadername12005, 02, 022006, 02, 02
appname2   leadername22006, 03, 212007, 06, 28
  
etc...
  
The error message looks like this
  
 back (most recent call last):
 File /home/amy/Documents/LIS452/assignment 3/testworks.py, line
97, in module
   main()
 File /home/amy/Documents/LIS452/assignment 3/testworks.py, line
80, in main
   a = Leaderapplicant(line) #from data file
 File /home/amy/Documents/LIS452/assignment 3/testworks.py, line 9,
in __init__
   appname, leadername, start, end = line.split(\t)
ValueError: need more than 3 values to unpack
  
Any help would be greatly appreciated.  I have spent so much time on
this that I am behind not only in this class but in other classes as
well.
  


 Immediately before line 9 put the following line:

 print line.split(\t)

  Now run it again and see how many values are in  the list that is
  printed. Your code expects that there will be exactly four.

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


Re: I'm sort of mystified by the print hex to char conversion

2009-04-18 Thread Wojtek Walczak
On Sat, 18 Apr 2009 11:45:09 -0700 (PDT), grocery_stocker wrote:
 I'm just really not seeing how something like x63 and/or x61 gets
 converted by 'print' to the corresponding chars in the following
 output...
...
 print \x63h\x61d
 chad


 Does print just do this magically?

Not only print does that:

 a='\x63h\x61d'
 a
'chad'
 print a
chad
 import sys
 sys.stdout.write(a)
chad eval(a)
Traceback (most recent call last):
  File stdin, line 1, in module
  File string, line 1, in module
NameError: name 'chad' is not defined

The policy is described here:

http://www.python.org/doc/2.4.4/ref/strings.html

Unlike Standard C, all unrecognized escape sequences are left in the
string unchanged, i.e., the backslash is left in the string. (This
behavior is useful when debugging: if an escape sequence is mistyped,
the resulting output is more easily recognized as broken.)

So, as long as the escape sequence is recognized it is changed
accordingly.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: python alternatives to C structs??

2009-04-18 Thread Wojtek Walczak
On Sat, 18 Apr 2009 12:25:29 -0700 (PDT), KoolD wrote:

Hi,

 I need to convert a C code to python please help me figure out how to
 do
 it.
 Suppose the C program's like:
...
 Is there a way to code it in python.

You need struct module:
http://docs.python.org/library/struct.html
http://www.doughellmann.com/PyMOTW/struct/index.html
http://code.activestate.com/recipes/498149/

HTH,
-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please help with problem creating class

2009-04-18 Thread Günther Dietrich
auzarski2...@gmail.com wrote:

I am using tab separated data in another file that looks like this...


appname1   leadername12005, 02, 022006, 02, 02
appname2   leadername22006, 03, 212007, 06, 28

etc...

The error message looks like this

 back (most recent call last):
  File /home/amy/Documents/LIS452/assignment 3/testworks.py, line
97, in module
main()
  File /home/amy/Documents/LIS452/assignment 3/testworks.py, line
80, in main
a = Leaderapplicant(line) #from data file
  File /home/amy/Documents/LIS452/assignment 3/testworks.py, line 9,
in __init__
appname, leadername, start, end = line.split(\t)
ValueError: need more than 3 values to unpack

You assign the result of line.split() to four variables. So split needs 
at least four fields (that's more than three) in line to process.

Examine your input data (appname1   leadername1   2005...), if it 
_really_ contains alt least three tab characters to separate the data 
fields.
Maybe you created the input file by means of the same editor you use for 
coding your python code, so the probability is high, that the editor 
produces multiple space characters when you press the tab key.
You could load the input file into vi or vim and give vi/vim the command

:set list

In list mode, tabs are rendered as '^I' (without the quotes).

Or you use a hex editor or something like od to inspect the input file.



Best regards,

Günther
--
http://mail.python.org/mailman/listinfo/python-list


Re: Overriding methods per-object

2009-04-18 Thread Piet van Oostrum
 Pavel Panchekha pavpanche...@gmail.com (PP) wrote:

 The docs don't say you can do that:
PP Thanks, hadn't noticed that.

 Should you be able to?

PP I'd say so. In my case, I need a class that can encapsulate any
PP object, add a few methods to it, and spit something back that works
PP just like the object, but also has those extra methods. I can't just
PP add the methods, because it has to work on e.g. lists. So I'll have to
PP end up defining all the possible methods on that class (and that's
PP still not best because I can't use hasattr to test if, for example,
PP addition is allowed on that object).

PP On the other hand, I see how this severely restricts the possibly
PP optimizations that can be made in the interpreter.

But you can give each object its own class and then put the special
methods in that class:

 def create_special_object(bases, *args):
...   if not isinstance(bases, tuple):
...  bases = bases,
...   cls = type(SpecialClass, bases, {})
...   return cls(*args)
... 
 a = create_special_object(list, [1,2,3])
 a
[1, 2, 3]
 a.__class__
class '__main__.SpecialClass'
 a.__class__.__nonzero__ = lambda self: False
 bool(a)
False
 a.__nonzero__()
False
 a.append(4)
 a
[1, 2, 3, 4]
 

-- 
Piet van Oostrum p...@cs.uu.nl
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Any adv. in importing a module and some objects in the same module, into the same file?

2009-04-18 Thread Visco Shaun
http://docs.python.org/library/logging.html

While going thr' the above link i came across import statements 
import logging
import logging.handlers

What is the use of second import as the first import will be
enough(AFAIK) to access anything intended by the second import?
Is there any kind of advantage?
-- 
Thanks  Regards
visco

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


for blackberry?

2009-04-18 Thread Vistro
Is there any good way of getting python to run on a blackberry 8830
world edition?

-- 

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


Re: How to create an unclosed dialog in wxPython?

2009-04-18 Thread alejandro
Don't press alt+f4?

?? liangguan...@163.com wrote in message 
news:719e6773-bad0-46ff-9842-a7ade2ced...@f41g2000pra.googlegroups.com...
 In wxPython, after I create a wx.Frame, I want to create a modeless
 and unclosed dialog. Here is my step:

 app = wx.PySimpleApp()
 f = wx.Frame(None, -1, Test)
 d = wx.Dialog(f, -1, Test Dialog, style = wx.CAPTION)
 f.Show()
 d.Show()
 app.MainLoop()

 As you see, I create a dialog with wx.CAPTION style. And than, there
 is no close button in this dialog. It seems unclosed dialog, but in
 fact, if you enter Alt+F4 in this dialog, it will close. How could I
 do?
 


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


Re: polar plots, clockwise, north

2009-04-18 Thread enricong
Thanks, I had tried this earlier but by rotating the data in this
fashion, it has problems connecting the endpoints between 0 and 360
and tries to go counter clockwise around.  I am then left with an
extra circle in all my plots where it attempts to connect the points
between 360 and 0 (now 100 and 0).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing a parse tree

2009-04-18 Thread Clarendon
Dear John Machin

So sorry about the typo. It should be: the program should *see* that
the designated *words* are...

a long way has two parentheses to the left -- (VP (DT -- before it
hits a separate group -- VBD came). If there are three parenthesis,
for instance (NP, this will means that what follows a long way is a
modifier of a long way, as illustrated below:

(VP (VBD came)
   (NP
 (NP (DT a) (JJ long) (NN way))
 (PP (IN in)

So I am trying to capture the grammatical relations following the
designated words.




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


How to create an unclosed dialog in wxPython?

2009-04-18 Thread 书虫
In wxPython, after I create a wx.Frame, I want to create a modeless
and unclosed dialog. Here is my step:

app = wx.PySimpleApp()
f = wx.Frame(None, -1, Test)
d = wx.Dialog(f, -1, Test Dialog, style = wx.CAPTION)
f.Show()
d.Show()
app.MainLoop()

As you see, I create a dialog with wx.CAPTION style. And than, there
is no close button in this dialog. It seems unclosed dialog, but in
fact, if you enter Alt+F4 in this dialog, it will close. How could I
do?

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


Re: __getattribute__ for operators

2009-04-18 Thread Michael
Hmm... I meant to create a new thread, as does GMail when you edit the
subject.  Pardon my Google-Groups newbieness. - Michael
--
http://mail.python.org/mailman/listinfo/python-list


Re: Please help with problem creating class

2009-04-18 Thread Aahz
In article 3pmpb6-lq9@spamfence.net,
=?UTF-8?Q?G=C3=BCnther?= Dietrich guenther.dietr...@spamfence.net wrote:

You assign the result of line.split() to four variables. So split needs 
at least four fields (that's more than three) in line to process.

s/at least/exactly/

 w, x, y, z = '1\t2\t3\t4\t5'.split('\t')
Traceback (most recent call last):
  File stdin, line 1, in ?
ValueError: too many values to unpack
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur.  --Red Adair
--
http://mail.python.org/mailman/listinfo/python-list


Re: Variables vs attributes

2009-04-18 Thread Piet van Oostrum
 Steven D'Aprano st...@remove-this-cybersource.com.au (SD) wrote:

SD On Fri, 17 Apr 2009 17:48:55 +0200, Diez B. Roggisch wrote:
 No, because you are creating *classvariables* when declaring things like
 this:
SD ...
 OTOH, when assigning to an instance, this will create an
 *instance*-variable. Which is what


SD If an integer variable is an integer, and a string variable is a string, 
SD and float variable is a float, and a list variable is a list (there's a 
SD pattern here), shouldn't a class variable be a class and an instance 
SD variable be an instance?

If a wooden bench is made of wood, what is a garden bench made of?

SD I had never noticed the usage of variable to mean attribute until a few 
SD months ago. What's going on? Why did people decide that confusing 
SD variables and attributes of variables was a good thing? What's next, 
SD describing dictionary keys as dictionary variables?

If you google for 'instance variable python' you get quite a number of
hits, not only recent ones. Albeit two orders of magnitude fewer than
for 'attribute python'.
-- 
Piet van Oostrum p...@cs.uu.nl
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a programming language that is combination of Python and Basic?

2009-04-18 Thread Tim Rowe
2009/4/18 Aahz a...@pythoncraft.com:

 blink  I had never previously heard that Modula-2 significantly
 influenced Ada, and the Wikipedia entry says nothing about it.  Do you
 have a cite?

Not in writing. I got it from a SPARK user group meeting many years
ago. SPARK is, of course a subset of Ada with some mandatory
structured comments, and is a successor to SPADE which was much the
same thing for Pascal. When somebody asked one of the SPARK team -- I
think it was Denton Clutterbuck -- why they'd gone from Pascal to Ada
rather than Modula2, he observed If you look at the SPARK subset
you'll see that it pretty much *is* Modula2. So whether Modula2 was a
direct influence or not, it seems to have found its way in.

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


[no subject]

2009-04-18 Thread karlos barlos
hello to all !!

given the code :

elif choice == 3:
    print all users list :
    print\n
    import active_directory
    for user in active_directory.search (objectCategory='Person', 
objectClass='User'):
 print user



that lists all active directory personal ...

how can i pipe this into a csv file ??

or a text file ?

do need to first make it txt and then csv??



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


Re:

2009-04-18 Thread Benjamin Kaplan
On Sat, Apr 18, 2009 at 4:23 PM, karlos barlos karlosbar...@yahoo.comwrote:

 hello to all !!

 given the code :

 elif choice == 3:
 print all users list :
 print\n
 import active_directory
 for user in active_directory.search (objectCategory='Person',
 objectClass='User'):
  print user

 

 that lists all active directory personal ...

 how can i pipe this into a csv file ??

 or a text file ?

 do need to first make it txt and then csv??


http://www.lmgtfy.com/?q=python+csv

Also, look at

http://www.catb.org/~esr/faqs/smart-questions.html





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


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


Re: __getattribute__ for operators

2009-04-18 Thread Terry Reedy

Michael wrote:

While thinking about Steven D'Aprano's thread about automatically
generating arithmetic operations for a subclass, I stumbled upon
something confusing.  Having defined the following class to do funky
addition,

class MyInt(int):
def __getattribute__(self, key):
if key == __add__:
print(In __getattribute__('__add__'))
return lambda other: MyInt(int.__add__(self, other+100))
else:
return object.__getattribute__(self, key)

def __getattr__(self, key):
if key == __add__:
print(In __getattr__('__add__'))
return lambda other: MyInt(int.__add__(self, other+100))
else:
return object.__getattr__(self, key)

I then do this:


a = MyInt(4)
a.__add__(2)

In __getattribute__('__add__')
106

a + 2

6

Why doesn't a + 2 look up the __add__ attribute and use my lambda?


Answer 1: because it was not programmed that way ;-).

Answer 2: because __getattribute__/__getattr__ are for looking up 
attributes of instances of the class, whereas special methods are 
generally required to be attributes of the class.  So *their* lookup 
would use type(MyInt).__getxxx__.  When that fails, the add code looks 
for int.__radd__.  (I *think* this your answer.)


 If I manually define __add__(self, other) then a + 2 will of course

use that method.


because that is that type(MyInt).__getxxx__ will find.

tjr

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


Re: __getattribute__ for operators

2009-04-18 Thread Piet van Oostrum
 Michael gundl...@gmail.com (M) wrote:

M While thinking about Steven D'Aprano's thread about automatically
M generating arithmetic operations for a subclass, I stumbled upon
M something confusing.  Having defined the following class to do funky
M addition,

M class MyInt(int):
M def __getattribute__(self, key):
M if key == __add__:
M print(In __getattribute__('__add__'))
M return lambda other: MyInt(int.__add__(self, other+100))
M else:
M return object.__getattribute__(self, key)

M def __getattr__(self, key):
M if key == __add__:
M print(In __getattr__('__add__'))
M return lambda other: MyInt(int.__add__(self, other+100))
M else:
M return object.__getattr__(self, key)

M I then do this:

 a = MyInt(4)
 a.__add__(2)
M In __getattribute__('__add__')
M 106
 a + 2
M 6
 

M Why doesn't a + 2 look up the __add__ attribute and use my lambda?
M If I manually define __add__(self, other) then a + 2 will of course
M use that method.

This has just been discussed in the thread Overriding methods
per-object. In short: In newstyle classes these methods when invoked
implicitely, e.g by a+2, are only looked up in the class, and bypass
__getattribute__.

See 
http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes
-- 
Piet van Oostrum p...@cs.uu.nl
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: I'm sort of mystified by the print hex to char conversion

2009-04-18 Thread Peter Pearson
On Sat, 18 Apr 2009 11:45:09 -0700 (PDT), grocery_stocker wrote:
 I'm just really not seeing how something like x63 and/or x61 gets
 converted by 'print' to the corresponding chars in the following
 output...

 [cdal...@localhost oakland]$ python
 Python 2.4.3 (#1, Oct  1 2006, 18:00:19)
 [GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
 Type help, copyright, credits or license for more information.
 print '\x63had'
 chad
 print '\x63h\x61d'
 chad
 print \x63had
 chad
 print \x63h\x61d
 chad


 Does print just do this magically?

I'm not sure what magic you see in there, but does the
following help?

 a = \x63had
 len(a)
4
 b = \x63h\x61d
 len(b)
4

Personally, when I'm puzzled by something involving a string
with backslashes, I use len to help figure out what's really
in the string and what's inserted on the way to my screen.

-- 
To email me, substitute nowhere-spamcop, invalid-net.
--
http://mail.python.org/mailman/listinfo/python-list


not homework... something i find an interesting problem

2009-04-18 Thread Trip Technician
although it's not homework (how can i prove that...?) i am still happy
with just hints

+++

we want to express integers as sums of squares. (repeated squares are
allowed)

most numbers have one minimal representation e.g. 24=16+4+4, some have
two or more e.g. 125 = 121+4 = 100+25

so far I have created a simple recursive function that expresses a
given number as a sum of squares in the obvious and naive way. it
returns a nested tuple , which is then flattened for simplicity...then
to cover the possibility that there might be one other minimal
representation i call another similar function which will find one
other representation, not necessarily shorter or of equal length,
finally these are sorted and the results displayed, with the minimal
result or the 2 equal-length minimal results.

as the numbers get bigger (i believe) there will be some which have 3
or more minimal representations which this code will miss.

what I want to do is come up with a recursion that will find all
possible minimal representations in one function (if possible ) in an
optimally elegant and scalable way. There's no application in mind, i
just love playing with math.

code so far below:

# express numbers as sum of squares

a=[x**2 for x in range(50,0,-1)]

# finds obvious candidate

def squ(z):
if z==0:
return 0
for x in a:
if z=x:
return x,squ(z-x)

# finds another candidate with largest square as next square down from
above function

def squ2(z):
if z==0:
return 0
for x in a:
if z=x:
return a[a.index(x)+1],squ(z-a[a.index(x)+1])

def flatten(lst):
for elem in lst:
if type(elem) in (tuple, list):
for i in flatten(elem):
yield i
else:
yield elem
q=[]
r=[]

for aa in range(100):
r.append([])

for xx in range(10,100):
q=[]
for ss in flatten(squ(xx)):
if ss!=0:
q.append(ss)
r[xx].append(q)

for xx in range(10,100):
q=[]
for ss in flatten(squ2(xx)):
if ss!=0:
q.append(ss)
r[xx].append(q)


for eee in r:
if eee:
if len(eee[0])==len(eee[1]):
print r.index(eee),eee[0],eee[1]
else:
print r.index(eee),eee[0]

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


Re: Any adv. in importing a module and some objects in the same module, into the same file?

2009-04-18 Thread Piet van Oostrum
 Visco Shaun visc...@gmail.com (VS) wrote:

VS http://docs.python.org/library/logging.html
VS While going thr' the above link i came across import statements 
VS import logging
VS import logging.handlers

VS What is the use of second import as the first import will be
VS enough(AFAIK) to access anything intended by the second import?
VS Is there any kind of advantage?

Have you tried?

 import logging
 logging.handlers
Traceback (most recent call last):
  File stdin, line 1, in module
AttributeError: 'module' object has no attribute 'handlers'
 import logging.handlers
 logging.handlers
module 'logging.handlers' from 
'/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/logging/handlers.pyc'
 

'logging' is a package. The 'logging' module does not contain a
definition of 'handlers' but there is a module 'handlers' in the 'logging'
directory.
-- 
Piet van Oostrum p...@cs.uu.nl
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Overriding methods per-object

2009-04-18 Thread Pavel Panchekha
On Apr 18, 4:01 pm, Piet van Oostrum p...@cs.uu.nl wrote:
 But you can give each object its own class and then put the special
 methods in that class:

  def create_special_object(bases, *args):

 ...   if not isinstance(bases, tuple):
 ...      bases = bases,
 ...   cls = type(SpecialClass, bases, {})
 ...   return cls(*args)
 ... a = create_special_object(list, [1,2,3])
  a
 [1, 2, 3]
  a.__class__

 class '__main__.SpecialClass'

  a.__class__.__nonzero__ = lambda self: False
  bool(a)
 False
  a.__nonzero__()
 False
  a.append(4)
  a
 [1, 2, 3, 4]

 --
 Piet van Oostrum p...@cs.uu.nl
 URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
 Private email: p...@vanoostrum.org

I think this is the solution I like best.

 FYI this works as you expect if GeneralTypeOfObject is an old-style
 class (i.e. does not inherit from object). If this feature is so more
 important than all those that come with new-style classes, you have
 control over the involved classes and don't care about Python 3.x
 (where old-style classes are gone), you may choose to downgrade
 GeneralTypeOfObject to old-style.

It is important, but new-style classes are important too. And I care
quite a bit about Python 3.x, thus the fact that I prefer the above
solution.
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >