Imports again...

2010-04-09 Thread Alex Hall
Hello all, once again:
http://www.gateway2somewhere.com/sw/sw.zip

The above link is to a project. I am new to using multiple files in
Python, and I have a lot of tangled imports where many files in the
same folder are importing each other. When I tried to follow the
manual to make some files into packages, it did not work. Can anyone
explain why I am getting an import error in the above project, and/or
how I can clean up the file structure and imports to avoid problems
like this in the future? Thanks in advance for any help, and I
apologize for the broken link the other day.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: lambda with floats

2010-04-09 Thread Bas
On Apr 7, 6:15 am, Patrick Maupin  wrote:
> I should stop making a habit of responding to myself, BUT.  This isn't
> quite an acre in square feet.  I just saw the 43xxx and assumed it
> was, and then realized it couldn't be, because it wasn't divisible by
> 10.  (I used to measure land with my grandfather with a 66 foot long
> chain, and learned at an early age that an acre was 1 chain by 10
> chains, or 66 * 66 * 10 = 43560 sqft.)
> That's an exact number, and 208 is a poor approximation of its square
> root.

There is no need to remember those numbers for the imperially
challenged people:

In [1]: import scipy.constants as c

In [2]: def acre2sqft(a):
   ...: return a * c.acre / (c.foot * c.foot)
   ...:

In [3]: acre2sqft(1)
Out[3]: 43560.0


Cheers,
Bas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pass object or use self.object?

2010-04-09 Thread Bruno Desthuilliers

Tim Arnold a écrit :

On Apr 8, 4:20 am, Bruno Desthuilliers 
(snip)

There are two points here : the first is that we (that is, at least, you
and me) just don't know enough about the OP's project to tell whether
something should belong to the document or not. period. The second point
is that objects don't live in a splendid isolation, and it's perfectly
ok to have code outside an object's method working on the object.

wrt/ these two points, your "document should encapsulate its own logic"
note seems a bit dogmatic (and not necessarily right) to me - hence my
answer.


The 'document' in this case is an lxml Elementtree, so I think it
makes sense to have code outside the object.


Indeed. It's the only sensible thing to do here.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Imports again...

2010-04-09 Thread Tim Golden

On 08/04/2010 14:16, Alex Hall wrote:

The above link is to a project. I am new to using multiple files in
Python, and I have a lot of tangled imports where many files in the
same folder are importing each other. When I tried to follow the
manual to make some files into packages, it did not work. Can anyone
explain why I am getting an import error in the above project, and/or
how I can clean up the file structure and imports to avoid problems
like this in the future? Thanks in advance for any help, and I
apologize for the broken link the other day.


I don't have the energy at the moment to install all the dependencies
to make the thing run, but just glancing at the layout... you appear
to have a slightly confused idea of how packages are used. The main
"arm" directory has an __init__.py as does a "modes" subdirectory and
a "weather" subdirectory of that. But neither of these has any code
in them to be imported. And the "arm" directory appears to be the main
application directory so making that into a package doesn't seem to
serve any purpose.

I'm sure there are better explanations around, but in short: packages
are directories with Python modules in them and, specifically, one Python
module __init__.py which is typically empty (but needn't be). They can
be considered in different ways, but essentially are ways of grouping
Python modules according to some idea of cohesion. They don't magically
make tangled code untangled but they might offer a certain clarity where
you'd otherwise have one big directory full of undifferentiated modules.

A typical example of packages would be a system which wanted to output
to csv, html and pdf using some standardised API. The various
output modules might live inside an "outputs" subpackage so the main
program could do "from outputs import csv" or whatever. As it happens,
this example also shows that the "outputs.csv" module won't shadow the
stdlib csv module -- also purists might argue that it's bad practice to
name any module over a stdlib module.

Creating a package in your case might help you -- I haven't really looked
at your code enough to say for sure -- to break one big module into several
more structured modules within a package.

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


Re: SIP

2010-04-09 Thread CHEN Guang
PythoidC ( http://pythoidc.sf.net ) provides some examples and templates for 
writing and importing C modules (.c or .exe) into Python environment, may be of 
some help. 
- Original Message - 
From: "omnia neo" 
To: 
Sent: Friday, April 09, 2010 1:51 PM
Subject: Re: SIP


On Apr 9, 10:42 am, omnia neo  wrote:
> On Apr 9, 10:30 am, Stefan Behnel  wrote:
>
> > omnia neo, 09.04.2010 07:01:
>
> > > import siptest
>
> > > I get following error :
> > > import error : no module named siptest
>
> > Is the directory where your siptest.dll lies in your PYTHONPATH (sys.path)?
>
> > Otherwise, Python can't find it.
>
> > Stefan
>
> thanks for reply Stefan..
> well I added PYTHONPATH =  in my environment variables
> (windows XP).

well I just tried this too.
I added the path using sys.path on the fly in my python script as
follows:

###
import sys
sys.path.append("")
print sys.path
import siptest
###

again same error:
ImportError: No module named siptest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The Regex Story

2010-04-09 Thread Steven D'Aprano
On Fri, 09 Apr 2010 14:48:22 +1000, Lie Ryan wrote:

> On 04/09/10 12:32, Dotan Cohen wrote:
>>> Regexes do have their uses. It's a case of knowing when they are the
>>> best approach and when they aren't.
>> 
>> Agreed. The problems begin when the "when they aren't" is not
>> recognised.
> 
> But problems also arises when people are suggesting overly complex
> series of built-in functions for what is better handled by regex.

What defines "overly complex"?

For some reason, people seem to have the idea that pattern matching of 
strings must be a single expression, no matter how complicated the 
pattern they're trying to match. If we have a complicated task to do in 
almost any other field, we don't hesitate to write a function to do it, 
or even multiple functions: we break our code up into small, 
understandable, testable pieces. We recognise that a five-line function 
may very well be less complex than a one-line expression that does the 
same thing. But if it's a string pattern matching task, we somehow become 
resistant to the idea of writing a function and treat one-line 
expressions as "simpler", no matter how convoluted they become.

It's as if we decided that every maths problem had to be solved by a 
single expression, no matter how complex, and invented a painfully terse 
language unrelated to normal maths syntax for doing so:

# Calculate the roots of sin**2(3*x-y):
result = me.compile("{^g.?+*y:h}|\Y^r&(?P:2+)|\w+(x&y)|[?#\s]").solve()

That's not to say that regexes aren't useful, or that they don't have 
advantages. They are well-studied from a theoretical basis. You don't 
have to re-invent the wheel: the re module provides useful pattern 
matching functionality with quite good performance.

One disadvantage is that you have to learn an entire new language, a 
language which is painfully terse and obfuscated, with virtually no 
support for debugging. Larry Wall has criticised the Perl regex syntax on 
a number of grounds:

* things which look similar often are very different;
* things which are commonly needed are long and verbose, while things 
which are rarely needed are short;
* too much reliance on too few metacharacters;
* the default is to treat whitespace around tokens as significant, 
instead of defaulting to verbose-mode for readability;
* overuse of parentheses;
* difficulty working with non-ASCII data;
* insufficient abstraction;
* even though regexes are source code in a regular expression language, 
they're treated as mere strings, even in Perl;

and many others.

http://dev.perl.org/perl6/doc/design/apo/A05.html

As programming languages go, regular expressions -- even Perl's regular 
expressions on steroids -- are particularly low-level. It's the assembly 
language of pattern matching, compared to languages like Prolog, SNOBOL 
and Icon. These languages use patterns equivalent in power to Backus-Naur 
Form grammars, or context-free grammars, much more powerful and readable 
than regular expressions.

But in any case, not all text processing problems are pattern-matching 
problems, and even those that are don't necessarily require the 30lb 
sledgehammer of regular expressions.

I find it interesting to note that there is such a thing as "regex 
culture", as Larry Wall describes it. There seems to be a sort of 
programmers' machismo about solving problems via regexes, even when 
they're not the right tool for the job, and in the fewest number of 
characters possible. I think regexes have a bad reputation because of 
regex culture, and not just within Python circles either:

http://echochamber.me/viewtopic.php?f=11&t=57405


For the record, I'm not talking about "Because It's There" regexes like 
this this 6343-character monster:

http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html

or these:

http://mail.pm.org/pipermail/athens-pm/2003-January/33.html
http://blog.sigfpe.com/2007/02/modular-arithmetic-with-regular.html

The fact that these exist at all is amazing and wonderful. And yes, I 
admire the Obfuscated C and Underhanded C contests too :)



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


Re: The Regex Story

2010-04-09 Thread Alf P. Steinbach

* Steven D'Aprano:


For some reason, people seem to have the idea that pattern matching of 
strings must be a single expression, no matter how complicated the 
pattern they're trying to match. If we have a complicated task to do in 
almost any other field, we don't hesitate to write a function to do it, 
or even multiple functions: we break our code up into small, 
understandable, testable pieces. We recognise that a five-line function 
may very well be less complex than a one-line expression that does the 
same thing. But if it's a string pattern matching task, we somehow become 
resistant to the idea of writing a function and treat one-line 
expressions as "simpler", no matter how convoluted they become.


It's as if we decided that every maths problem had to be solved by a 
single expression, no matter how complex, and invented a painfully terse 
language unrelated to normal maths syntax for doing so:


# Calculate the roots of sin**2(3*x-y):
result = me.compile("{^g.?+*y:h}|\Y^r&(?P:2+)|\w+(x&y)|[?#\s]").solve()


http://www.youtube.com/watch?v=a9xAKttWgP4


Cheers,

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


Re: python as pen and paper substitute

2010-04-09 Thread Giacomo Boffi
Manuel Graune  writes:

> Giacomo Boffi  writes:
>
>> Manuel Graune  writes:
>>
>>> Hello everyone,
>>>
>>> I am looking for ways to use a python file as a substitute for simple
>>> pen and paper calculations.
>>
>> search("embedded calc mode") if manuel in emacs_fellows_set or sys.exit(1)
>
> Well, the subject does say python

and so i answered in python...

seriously, embedded calc mode is not mathematica's notebooks but is
usable for doing "live maths" in a text buffer

> I'm a vim-user anyways.

sorry... otoh, vim is scriptable in python.  i know less than nothing
on this subject but i'd be surprised if something akin to your request
were not available

> *duckandrun*

tanto ti ripiglio
g
-- 
non ho capito un apascio   -- pp, tra se e se 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The Regex Story

2010-04-09 Thread Paul Rubin
Steven D'Aprano  writes:
> One disadvantage is that you have to learn an entire new language, a 
> language which is painfully terse and obfuscated, with virtually no 
> support for debugging. Larry Wall has criticised the Perl regex syntax on 
> a number of grounds: ...

There is a parser combinator library for Python called Pyparsing but it
is apparently dog slow.  Maybe someone can do a faster one sometime.  
See: http://pyparsing.wikispaces.com/ for info.  I haven't used it,
but it is apparently similar in style to Parsec (a Haskell library):

  http://research.microsoft.com/users/daan/download/papers/parsec-paper.pdf 

I use Parsec sometimes, and it's much nicer than complicated regexps.
There is a version called Attoparsec now that is slightly less powerful
but very fast.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The Regex Story

2010-04-09 Thread Lie Ryan
On 04/09/10 18:59, Steven D'Aprano wrote:
> On Fri, 09 Apr 2010 14:48:22 +1000, Lie Ryan wrote:
> 
>> On 04/09/10 12:32, Dotan Cohen wrote:
 Regexes do have their uses. It's a case of knowing when they are the
 best approach and when they aren't.
>>>
>>> Agreed. The problems begin when the "when they aren't" is not
>>> recognised.
>>
>> But problems also arises when people are suggesting overly complex
>> series of built-in functions for what is better handled by regex.
> 
> What defines "overly complex"?

These discussions about readability and suitability of regex are
orthogonal issue with the sub-topic I started. We are all fully aware of
the limitations of each approaches. What I am complaining is the recent
development of people just saying no to regex when the problem is in
fact in regex's very sweetspot. We have all seen people abusing regex;
but nowadays I'm starting to see people abusing built-ins as well.

We don't like when regex gets convoluted, but that doesn't mean built-in
fare much better either.
-- 
http://mail.python.org/mailman/listinfo/python-list


[Python-list] The distutils.sysconfig.set_python_config() function

2010-04-09 Thread Ray Allen
I've been reading the python document "Distributing python modules", and
found this function document in sysconfig module:

This function is even more special-purpose, and should only be used from
Python’s own build procedures.

distutils.sysconfig.set_python_build()<#distutils.sysconfig.set_python_build>Inform
the distutils.sysconfig module that it is being used as part of the build
process for Python. This changes a lot of relative locations for files,
allowing them to be located in the build area rather than in an installed
Python.

Where is this function? I cannot find it in distutils/sysconfig.py.

Thanks.

-- 
Ray Allen
Best wishes!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The Regex Story

2010-04-09 Thread Stefan Behnel

Tim Chase, 08.04.2010 16:23:

Lie Ryan wrote:

Why am I seeing a lot of this pattern lately:

OP: Got problem with string
+- A: Suggested a regex-based solution
+- B: Quoted "Some people ... regex ... two problems."

or

OP: Writes some regex, found problem
+- A: Quoted "Some people ... regex ... two problems."
+- B: Supplied regex-based solution, clean one
+- A: Suggested PyParsing (or similar)


There are some problem-classes for which regexps are the *right*
solution, and I don't see as much of your example dialog in those cases.


Obviously. People rarely complain about problems that are easy to solve 
with the solution at hand.


Stefan

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


Re: The Regex Story

2010-04-09 Thread Stefan Behnel

Steven D'Aprano, 09.04.2010 10:59:

It's as if we decided that every maths problem had to be solved by a
single expression, no matter how complex, and invented a painfully terse
language unrelated to normal maths syntax for doing so:

# Calculate the roots of sin**2(3*x-y):
result = me.compile("{^g.?+*y:h}|\Y^r&(?P:2+)|\w+(x&y)|[?#\s]").solve()


Actually, I would expect that the result of any mathematical calculation 
can be found by applying a suitable regular expression to pi.


Stefan

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


Re: How to open and read an unknown extension file

2010-04-09 Thread varnikat t
Hey thanks a lot to all of youNow i understood the concept and can use
it the right way

I have another doubt regarding using radio buttons

I am using two radio buttons for user to select either of the two options:

Landscape
Portrait

When i run the program it shows both radio buttons are active
I don't know how to toggle between the two radio buttons.
Also I want to display the respective image with them Landscape and portrait
at the top of each optionCan anyone help me with this?

On Fri, Apr 9, 2010 at 6:05 AM, Tim Chase wrote:

> On 04/08/2010 12:22 PM, varnikat t wrote:
>
>> it gives me this error
>>
>> TypeError: coercing to Unicode: need string or buffer, list found
>>
>>> Thanks for the help.it detects now using glob.glob("*.*.txt")
>>>
>>> Can u suggest how to open and read file this way?
>>>
>>> *if glob.glob("*.*.txt"):
>>> file=open(glob.glob("*.*.txt"))
>>>
>>> self.text_view.get_buffer().set_text(file.read())
>>> else:
>>> file=open(glob.glob("*.*.html"))
>>>
>>> self.text_view.get_buffer().set_text(file.read())
>>>
>>
> glob() returns a list of matching files, not a string.  So you need to
> iterate over those files:
>
>  filenames = glob.glob('*.*.txt')
>  if filenames:
>for filename in filenames:
>  do_something_text(filename)
>  else:
>for filename in glob('*.*.html'):
>  do_something_html(filename)
>
> -tkc
>
>
>
>


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


Re: How to open and read an unknown extension file

2010-04-09 Thread varnikat t
And I am using python and GLADE for GUI

On Fri, Apr 9, 2010 at 6:30 PM, varnikat t  wrote:

> Hey thanks a lot to all of youNow i understood the concept and can use
> it the right way
>
> I have another doubt regarding using radio buttons
>
> I am using two radio buttons for user to select either of the two options:
>
> Landscape
> Portrait
>
> When i run the program it shows both radio buttons are active
> I don't know how to toggle between the two radio buttons.
> Also I want to display the respective image with them Landscape and
> portrait at the top of each optionCan anyone help me with this?
>
>
> On Fri, Apr 9, 2010 at 6:05 AM, Tim Chase 
> wrote:
>
>> On 04/08/2010 12:22 PM, varnikat t wrote:
>>
>>> it gives me this error
>>>
>>> TypeError: coercing to Unicode: need string or buffer, list found
>>>
 Thanks for the help.it detects now using glob.glob("*.*.txt")

 Can u suggest how to open and read file this way?

 *if glob.glob("*.*.txt"):
 file=open(glob.glob("*.*.txt"))

 self.text_view.get_buffer().set_text(file.read())
 else:
 file=open(glob.glob("*.*.html"))

 self.text_view.get_buffer().set_text(file.read())

>>>
>> glob() returns a list of matching files, not a string.  So you need to
>> iterate over those files:
>>
>>  filenames = glob.glob('*.*.txt')
>>  if filenames:
>>for filename in filenames:
>>  do_something_text(filename)
>>  else:
>>for filename in glob('*.*.html'):
>>  do_something_html(filename)
>>
>> -tkc
>>
>>
>>
>>
>
>
> --
> Varnika Tewari
>



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


Re: Pythonic list reordering

2010-04-09 Thread Joaquin Abian
On Apr 9, 1:58 am, Chris Rebert  wrote:
> On Thu, Apr 8, 2010 at 4:01 PM, Joaquin Abian  wrote:
> > On Apr 9, 12:52 am, Ben Racine  wrote:
> >> I have a list...
>
> >> ['dir_0_error.dat', 'dir_120_error.dat', 'dir_30_error.dat', 
> >> 'dir_330_error.dat']
>
> >> I want to sort it based upon the numerical value only.
>
> >> Does someone have an elegant solution to this?
>
> > not sure about elegance, but my two cents:
>
> >>> mylist = ['dir_0_error.dat', 'dir_120_error.dat', 'dir_30_error.dat', 
> >>> 'dir_330_error.dat']
> >>> mylist = [(int(item.split('_')[1]), item) for item in mylist]
> >>> mylist.sort()
> >>> mylist = [item for idx, item in mylist]
> >>> mylist
>
> > ['dir_0_error.dat', 'dir_30_error.dat', 'dir_120_error.dat',
> > 'dir_330_error.dat']
>
> At least conceptually, that's how list.sort() with a key= argument
> works internally (i.e. via Schwartzian transform).
>
> Cheers,
> Chris
> --http://blog.rebertia.com

Chris, thanks for the comment. I did not know that name (Schwartzian
transform)
I knew it as the decorate-sort-undecorate strategy.
Now after learning that it was a Perl idiom I feel somewhat
embarrassed ;-)

BTW, I actually prefer the l.sort(key=f) method.
Just my lazy neurons were back to Python 2.3 when I wrote the
response.

Joaquin

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


Re: Preserving logging streams through a daemon.DaemonContext switch (was: daemon.DaemonContext)

2010-04-09 Thread Vinay Sajip
On Apr 9, 12:46 am, Ben Finney  wrote:
> > I think you just have to pass the file object used by the handler
> > (fh.stream) in the files_preserve array.
>
> Not quite. As the docs specify, you need to pass the *file descriptors*
> for the files you want preserved.

Okay, but the docstring you quoted:

"Elements of the list are file descriptors (as returned by a file
object's `fileno()` method) or Python `file` objects."

implies that fh.stream would work as well as fh.stream.fileno(), and I
presume you internally do a hasattr(thingy, 'fileno') to get the
descriptor.

Regards,

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


Re: Imports again...

2010-04-09 Thread Thomas Guettler
Hi,

please post your traceback. I guess you have a recursive import. This
can lead to strange exceptions (for example AttributeError)

 Thomas

Alex Hall wrote:
> Hello all, once again:
> http://www.gateway2somewhere.com/sw/sw.zip
> 
> The above link is to a project. I am new to using multiple files in
> Python, and I have a lot of tangled imports where many files in the
> same folder are importing each other. When I tried to follow the
> manual to make some files into packages, it did not work. Can anyone
> explain why I am getting an import error in the above project, and/or
> how I can clean up the file structure and imports to avoid problems
> like this in the future? Thanks in advance for any help, and I
> apologize for the broken link the other day.
> 


-- 
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de
-- 
http://mail.python.org/mailman/listinfo/python-list


Excellent SAS Developer avaliable immediately for your client requriments

2010-04-09 Thread Haritha b
Dear Partners

I have Keerthi, SAS Developer available immediately for your client
requirements. Has worked for AccessPharmaceuticalsInc, ICON Clinical
Research, Amarillo Biosciences. She is in NC right now and is willing
to relocate in NC.  Please let me know if you have any direct client
positions for him.
Location: NC
Relocation: NC
Availability: ASAP


Please do send the requirements to hari...@lightningminds.com and
reach me at 703-349-5933



Please add my ID in your list and send your direct client requirements


SUMMARY:

·Over 8 years of strong experience in SAS and SAS tools
emphasizing on analysis, developing, design, testing and
implementation of various projects for Pharmaceutical Industries.

·Experience in requirement gathering, analysis, planning,
designing, coding and unit testing in Windows and Mainframe
environments.

·Extensive experience in Phase I, II, and III clinical data
analysis: analyzing clinical data, creating tables, listing and
generating reports and graphs.

·Experience in using SAS to read, write, import and export to
another data file formats, including delimited files, Microsoft Excel,
PDF and access tables.

·Experience with SAS Programming and familiar with all phases of
Clinical trials.

·Experience with clinical trial such as demographics data, adverse
event (AE), laboratory data (lab data) and vitals signs.

·Experience in analyzing medical claims data and interfacing SAS
with MS Office applications such as Access/Excel.

·Experience in SAS/BASE, SAS/STAT, SAS/GRAPH, SAS/MACRO, and SAS/
SQL.

·Proficient in the following reporting, statistical procedures:
REPORT, TABULATE, FREQ, MEANS, UNIVARIATE, TRANSPOSE, COMPARE, EXPORT,
COPY, CONTENTS.

·Experienced in producing HTML, RTF and PDF formatted files using
SAS/ODS.

·Knowledge of statistical procedures: PROC MIXED PROC MEANS, PROC
UNIVARIATE, PROC ANOVA.

·Experience in data accessing from relational databases, data
analysis and Predictive modeling.

·Thorough knowledge in preparing Clinical Study Reports by
conducting, documenting

  and reporting computer validation inspections in compliance with
21CFR Part 11, FDA regulatory guidelines.

·Proven ability to quick learn and apply new technologies.
Exceptionally well organized, strong work ethics and willingness to
work hard to achieve employer objectives. Clear and concise
communication and presentation skills.

·Effective team player with an aptitude to learn and ability to
prioritize, organize and accomplish multiple tasks, both as part of a
team and independently



Professional Certification:

SAS Certified Base Programmer for SAS9



TECHNICAL SKILLS:

SAS Skills:  SAS/BASE, SAS/GRAPH, SAS/MACRO, SAS/SQL, SAS/
STAT,
SAS/ACCESS, SAS/ODS.

Operating Systems: Windows 9x/2000, XP, NT, Windows Vista,
UNIX

Database:  Oracle, MS SQL Server, MS-Access,
SQL.

Others:   MS Office, MS Project, Power Point, Excel, SPSS





Thanks and Regards

Haritha
LIGHTNING MINDS
Phone : 703-349-5933
Email: hari...@lightningminds.com
Web: www.lightningminds.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Imports again...

2010-04-09 Thread Gabriel Genellina
On 8 abr, 10:16, Alex Hall  wrote:

> Hello all, once again:http://www.gateway2somewhere.com/sw/sw.zip
> 
> The above link is to a project. I am new to using multiple files in
> Python, and I have a lot of tangled imports where many files in the
> same folder are importing each other. When I tried to follow the
> manual to make some files into packages, it did not work. Can anyone
> explain why I am getting an import error in the above project, and/or
> how I can clean up the file structure and imports to avoid problems
> like this in the future? Thanks in advance for any help, and I
> apologize for the broken link the other day.

In addition to what Tim Golden has said (which appears to be based on another 
version of this project - I don't see the file structure he describes), I 
noticed that weather.py spawns a new thread when imported; don't do that: 
http://docs.python.org/library/threading.html#importing-in-threaded-code

Also, you have some .pyw files with corresponding .pyc file. That's *very* 
strange. .pyw files are *not* modules, and Python won't import them. Don't use 
the .pyw extension except for your main application script (in cases when you 
don't want a console window to appear). Having foo.pyc and foo.pyw in the same 
directory, Python will always load the .pyc file, ignoring any changes in 
the .pyw source.

-- 
Gabriel Genellina

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


Re: Imports again...

2010-04-09 Thread Tim Golden

On 09/04/2010 15:19, Gabriel Genellina wrote:

In addition to what Tim Golden has said (which appears to be based on another
version of this project


Just downloaded again, and there's definitely an empty package structure
of the kind I described. (Altho' I certainly did have a few other versions
lying around from previous questions by the OP).


Also, you have some .pyw files with corresponding .pyc file. That's *very*
strange. .pyw files are *not* modules, and Python won't import them.


Ahem.


Python 2.6.4rc2 (r264rc2:75501, Oct 18 2009, 22:41:58) [MSC v.1500 32 bit (I
Type "help", "copyright", "credits" or "license" for more information.

open ("xxx.pyw", "w").write ("print ('hello')")
import xxx

hello







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


Re: SIP

2010-04-09 Thread Gabriel Genellina
omnia neo  gmail.com> writes:
> On Apr 9, 10:42 am, omnia neo  wrote:
> > On Apr 9, 10:30 am, Stefan Behnel  wrote:
> >
> > > omnia neo, 09.04.2010 07:01:
> >
> > > > import siptest
> >
> > > > I get following error :
> > > > import error : no module named siptest
> >
> > > Is the directory where your siptest.dll lies in your PYTHONPATH 
(sys.path)?
> > well I added PYTHONPATH =  in my environment variables
> > (windows XP).
> 
> well I just tried this too.
> I added the path using sys.path on the fly in my python script as
> follows:
> 
> ###
> import sys
> sys.path.append("")
> print sys.path
> import siptest
> ###
> 
> again same error:
> ImportError: No module named siptest.

Make sure the extension module must is called siptest.pyd, not siptest.dll
http://docs.python.org/extending/windows.html
(I'd expect SIP to take care of this)

-- 
Gabriel Genellina

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


Re: The Regex Story

2010-04-09 Thread Tim Chase

On 04/09/2010 06:18 AM, Stefan Behnel wrote:

Tim Chase, 08.04.2010 16:23:

Lie Ryan wrote:

OP: Got problem with string
+- A: Suggested a regex-based solution
+- B: Quoted "Some people ... regex ... two problems."

or

OP: Writes some regex, found problem
+- A: Quoted "Some people ... regex ... two problems."
+- B: Supplied regex-based solution, clean one
+- A: Suggested PyParsing (or similar)


There are some problem-classes for which regexps are the *right*
solution, and I don't see as much of your example dialog in those cases.


Obviously. People rarely complain about problems that are easy to solve
with the solution at hand.


Well, you still see the "Got a problem with a string" and the 
"having a problem with this regex" questions, but you don't see 
the remainder of the "now you have two problems" dialog. 
Granted, some folks give that as a knee-jerk reaction so we just 
learn to ignore their input because sometimes a regexp is exactly 
the right solution ;-)


-tkc


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


Python Line Intersection

2010-04-09 Thread Peyman Askari
Hello

This is partly Python related, although it might end up being more math related.

I am using PyGTK (GUI builder for Python) and I need to find the intersection 
point for two lines. It is easy to do, even if you only have the four points 
describing line segments 
(http://www.maths.abdn.ac.uk/~igc/tch/eg1006/notes/node23.html). However, it 
requires that you solve for two equations. How can I do this in Python, either 
solve equations, or calculating intersection points some other way?

Cheers


Peyman Askari




  __
Connect with friends from any web browser - no download required. Try the new 
Yahoo! Canada Messenger for the Web BETA at 
http://ca.messenger.yahoo.com/webmessengerpromo.php-- 
http://mail.python.org/mailman/listinfo/python-list


Tough sorting problem: or, I'm confusing myself

2010-04-09 Thread david jensen
Hi all,

I'm trying to find a good way of doing the following:

Each n-tuple in combinations( range( 2 ** m ), n ) has a corresponding
value n-tuple (call them "scores" for clarity later). I'm currently
storing them in a dictionary, by doing:


res={}
for i in itertools.combinations( range( 2**m ) , n):
res[ i ] = getValues( i )# getValues() is computationally
expensive


For each (n-1)-tuple, I need to find the two numbers that have the
highest scores versus them. I know this isn't crystal clear, but
hopefully an example will help: with m=n=3:

Looking at only the (1, 3) case, assuming:
getValues( (1, 2, 3) ) == ( -200, 125, 75 )# this contains the
highest "other" score, where 2 scores 125
getValues( (1, 3, 4) ) == ( 50, -50, 0 )
getValues( (1, 3, 5) ) == ( 25, 300, -325 )
getValues( (1, 3, 6) ) == ( -100, 0, 100 )# this contains the
second-highest, where 6 scores 100
getValues( (1, 3, 7) ) == ( 80, -90, 10  )
getValues( (1, 3, 8) ) == ( 10, -5, -5 )

I'd like to return ( (2, 125), (6, 100) ).

The most obvious (to me) way to do this would be not to generate the
res dictionary at the beginning, but just to go through each
combinations( range( 2**m), n-1) and try every possibility... this
will test each combination n times, however, and generating those
values is expensive. [e.g. (1,2,3)'s scores will be generated when
finding the best possibilities for (1,2), (1,3) and (2,3)]

What I'm doing now is ugly, and i think is where i'm confusing myself:


best2={}
for i in itertools.combinations( range( 2**m), n-1):
scorelist=[]
for j in range( 2**m ):
if j not in i:
k=list(i)
k.append(j)
k=tuple(sorted(k))#gets the key for looking up the
scores in res
scorelist.append((j,res[k][k.index(j)]))
best2[i]=sorted(scorelist,key=lambda x: -x[1])[:2]


Am I missing an obviously better way?

Many thanks!

David


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


Re: Replacing Periods with Backspaces

2010-04-09 Thread Aahz
In article <8404fac9-06c7-4555-93af-c78f5e01d...@j21g2000yqh.googlegroups.com>,
Booter   wrote:
>
>I am trying to replace a series of periods in a sting with backspaces
>that way I can easily parse information from a Windows command.  the
>current statement I have for this is
>
>capture = re.sub('\.*', '\b', capture)

What's wrong with 

capture = capture.replace('.', '\b')

That will be much faster.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"...string iteration isn't about treating strings as sequences of strings, 
it's about treating strings as sequences of characters.  The fact that
characters are also strings is the reason we have problems, but characters 
are strings for other good reasons."  --Aahz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Line Intersection

2010-04-09 Thread Emile van Sebille

On 4/9/2010 8:04 AM Peyman Askari said...

Hello

This is partly Python related, although it might end up being more math related.

I am using PyGTK (GUI builder for Python) and I need to find the intersection 
point for two lines. It is easy to do, even if you only have the four points 
describing line segments 
(http://www.maths.abdn.ac.uk/~igc/tch/eg1006/notes/node23.html). However, it 
requires that you solve for two equations. How can I do this in Python, either 
solve equations, or calculating intersection points some other way?


I needed this a couple years back and used parts of pycad without much 
difficulty.


Emile

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


Re: Python Line Intersection

2010-04-09 Thread Gary Herron

Peyman Askari wrote:

Hello

This is partly Python related, although it might end up being more 
math related.


I am using PyGTK (GUI builder for Python) and I need to find the 
intersection point for two lines. It is easy to do, even if you only 
have the four points describing line segments 
(http://www.maths.abdn.ac.uk/~igc/tch/eg1006/notes/node23.html). 
However, it requires that you solve for two equations. How can I do 
this in Python, either solve equations, or calculating intersection 
points some other way?


Cheers


Peyman Askari



It is purely a math question, having nothing to do with Python.  But 
I'll answer it anyway:


Your problem is equivalent to solving a system of two equations in two 
unknowns.  If you can put those equations in the following form


 a*x + b*y = c
 d*x + e*y = f

then the solution is

 x = (c*e - b*f) / (a*e - b*d) 
 y = (a*f - c*d) / (a*e - b*d)


If the denominator is zero then the lines are parallel, and there is no 
(unique) solution.
(There are other was of solving the system, but they will all amount to 
the same arithmetic, and will, of course, produce the same result.)


Gary Herron






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


Re: Python Line Intersection

2010-04-09 Thread Chris Rebert
On Fri, Apr 9, 2010 at 8:04 AM, Peyman Askari  wrote:
>
> Hello
>
> This is partly Python related, although it might end up being more math 
> related.
>
> I am using PyGTK (GUI builder for Python) and I need to find the intersection 
> point for two lines. It is easy to do, even if you only have the four points 
> describing line segments 
> (http://www.maths.abdn.ac.uk/~igc/tch/eg1006/notes/node23.html). However, it 
> requires that you solve for two equations. How can I do this in Python, 
> either solve equations, or calculating intersection points some other way?


Just solve the equations ahead of time by using generic ones.

Given:
y = mx + b
y = nx + c

We set them equal and solve for x:
mx + b = nx + c
mx - nx = c - b
(m-n)x = c - b
x = (c - b) / (m-n)

So we now have a formula for x. y can then be calculated using the
numerical value of x and one of the original formulas for y.
If your equations are not in slope-intercept form, the same approach
works, just use different, appropriate initial equations.

Alternately, you could use a linear algebra library to solve the
system of equations; NumPy sounds like it has at least part of one.
But this is probably overkill for such a simple problem.

Cheers,
Chris
--
Zero is my hero! Squi FTW.
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating a rainbow?

2010-04-09 Thread Tobiah

>>You should use different variables for the two loops.
> 
>Actually it is closing the divs that makes it work in FireFox:
> 

Hah.  I new that the rainbow wasn't complete and that it
didn't work in Opera.  I just fizzled on the closing of the
divs.  

I also don't get why it worked at all when I was stomping
on my x variable in the inside loop.

It's better now.

http://tobiah.org/rainbow.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Imports again...

2010-04-09 Thread Alex Hall
Okay, what you all say makes sense, and I am going to try the package
thing again. The "modes" dir is from my last attempt, as is its
"weather" subdir. I think I see what I did wrong, at least I hope I
do. I will also remove the init file from the main dir. Yes, "arm" is
the main directory of the program. Also, I will try to update things
so that most imports happen from the dependencies folder, avoiding the
need to install/copy so much to your local install of Python. Here is
a traceback of the program as it is right now; this is from the exact
same version as the .zip file contains.

Microsoft Windows [Version 6.1.7600]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Alex>cd c:\python26

c:\Python26>python.exe i:\arm\main.pyw
Traceback (most recent call last):
  File "i:\arm\main.pyw", line 3, in 
import arm, network, weather, dict
  File "i:\arm\arm.py", line 4, in 
import config
  File "i:\arm\config.py", line 4, in 
from main import exitProgram
  File "i:\arm\main.pyw", line 3, in 
import arm, network, weather, dict
  File "i:\arm\network.py", line 4, in 
arm.ready()
AttributeError: 'module' object has no attribute 'ready'

c:\Python26>


I realize it may be odd to import from main.pyw, but I do not think
that could be causing the problem... could it? Perhaps I should erase
all the .pyc files and let it compile again, or would that not do
anything?

On 4/9/10, Tim Golden  wrote:
> On 09/04/2010 15:19, Gabriel Genellina wrote:
>> In addition to what Tim Golden has said (which appears to be based on
>> another
>> version of this project
>
> Just downloaded again, and there's definitely an empty package structure
> of the kind I described. (Altho' I certainly did have a few other versions
> lying around from previous questions by the OP).
>
>> Also, you have some .pyw files with corresponding .pyc file. That's *very*
>> strange. .pyw files are *not* modules, and Python won't import them.
>
> Ahem.
>
> 
> Python 2.6.4rc2 (r264rc2:75501, Oct 18 2009, 22:41:58) [MSC v.1500 32 bit (I
> Type "help", "copyright", "credits" or "license" for more information.
 open ("xxx.pyw", "w").write ("print ('hello')")
 import xxx
> hello


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


-- 
Have a great day,
Alex (msg sent from GMail website)
mehg...@gmail.com; http://www.facebook.com/mehgcap
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic list reordering

2010-04-09 Thread Tobiah

> How about a one liner?
> 
> L.sort(key=lambda s: int(s.split('_')[1]))
> 
> (Which is not necessarily elegant, but it is short.)

I grant it a measure of elegance as well.

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


Re: Imports again...

2010-04-09 Thread Ethan Furman

Tim Golden wrote:

On 09/04/2010 15:19, Gabriel Genellina wrote:
In addition to what Tim Golden has said (which appears to be based on 
another

version of this project


Just downloaded again, and there's definitely an empty package structure
of the kind I described. (Altho' I certainly did have a few other versions
lying around from previous questions by the OP).

Also, you have some .pyw files with corresponding .pyc file. That's 
*very*

strange. .pyw files are *not* modules, and Python won't import them.


Ahem.


Python 2.6.4rc2 (r264rc2:75501, Oct 18 2009, 22:41:58) [MSC v.1500 32 
bit (I

Type "help", "copyright", "credits" or "license" for more information.

open ("xxx.pyw", "w").write ("print ('hello')")
import xxx

hello







TJG


Good point.  Just to be clear, if there are *both* .py & .pyw...



Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit 
(Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.
--> open ("xxx.pyw", "w").write ("print ('hello')")
--> open ("xxx.py", "w").write ("print ('good-bye')")
--> import xxx
good-bye



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


Python question

2010-04-09 Thread Binary
How much space approximately is required to install the following packs on 
Windows XP?


pycairo-1.4.12-2.win32-py2.6.exe
python-2.6.1.msi
pygobject-2.14.2-2.win32-py2.6.exe
pygtk-2.12.1-3.win32-py2.6.exe
pywin32-213.win32-py2.6.exe
gtk-2.12.9-win32-2.exe

Does all this packs requires installation,  or it's possible just extract 
and place them in to C: drive, then to set environment variables properly?
Does this packs installs dynamic libraries and writes to registry? 


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


Re: How to call application in the background with subprocess.call

2010-04-09 Thread John Bokma
Kushal Kumaran  writes:

> On Thu, Apr 8, 2010 at 7:39 PM, jorma kala  wrote:
>> Hi,
>>
>> I'd like to call an external application (firefox) from a python program (a
>> PyQT GUI), but I want the external application to run in the background, I
>> mean I do not want my python calling program to wait till the external
>> subprocess terminates.
>> I've tried this:
>>
>> call(["firefox", "http://www.python.org";])
>>
>> but my PyQT interface freezes until I terminate Firefox.
>> Is there any parameter I need to use with call so that the python calling
>> program doesn't wait for the termination of the subprocess?
>>
>
> Use subprocess.Popen instead of directly using subprocess.call.


Or (maybe) better, use the webbrowser module.
http://docs.python.org/release/2.5.2/lib/module-webbrowser.html

-- 
John Bokma   j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Line Intersection

2010-04-09 Thread Josh English
On Apr 9, 8:36 am, Emile van Sebille  wrote:
> On 4/9/2010 8:04 AM Peyman Askari said...
>
> > Hello
>
> > This is partly Python related, although it might end up being more math 
> > related.
>
> > I am using PyGTK (GUI builder for Python) and I need to find the 
> > intersection point for two lines. It is easy to do, even if you only have 
> > the four points describing line segments 
> > (http://www.maths.abdn.ac.uk/~igc/tch/eg1006/notes/node23.html). However, 
> > it requires that you solve for two equations. How can I do this in Python, 
> > either solve equations, or calculating intersection points some other way?
>
> I needed this a couple years back and used parts of pycad without much
> difficulty.
>
> Emile

You can also do this by creating a Python representation of a line. I
did it by creating a vector class (using named tuple) and a line class
that stored a point and a direction vector. From there, you can find
the intersection of two lines (or a line with a circle, triangle, etc.
through some mathematical jiggery pokery using dot products.

If anyone want to see it I can post the code when I get home
-- 
http://mail.python.org/mailman/listinfo/python-list


Excellent Oracle Apps Technical Consutant avaliable immediately for your client requriments

2010-04-09 Thread Haritha b
Dear Partners

I have Raja Rao, Oracle Apps Technical consultant available
immediately for your client requirements. Has worked for Tekelec,
Hitachi Data Systems  etc. He is in NC right now and is willing to
relocate.  Pl. let me know if you have any direct client positions for
him.
Location: NC
Relocation: Open
Availability: ASAP

Please do send the requirements to a...@lightningminds.com and reach
me at 732-470-8387



Please add my ID in your list and send your direct client requirements


Summary:

 Over sixteen years in IT industry in design, development, testing and
implementation of business applications.   Over ten years of
experience in Oracle E-Business Financials/Supply Chain/Manufacturing
modules.  Developed custom forms to suit client requirements.
Developed custom oracle reports  in various modules of Oracle e-
Business Suite. Developed custom workflows to meet  user
requirements.  Customized Oracle seeded forms, reports and workflows
based on user requirements.

· Oracle RDBMS , PL/ SQL, SQL Plus

· Oracle Forms 6i/4.5/3.0, Reports 6i/2.5

· Oracle Financials/Supply Chain/Manufacturing modules
( Technical )

· Oracle Workflow Builder



Education:

· MS  from Indian Institute of Technology, Madras

· BS   from JNTU, Hyderabad

· Certificate in Oracle Financials/Supply Chain/Manufacturing
modules from Oracle Corporation, Madras



Technical Skills:



Software Tools: Oracle Financials/Supply Chain/Manufacturing
10.7  , 11i and  Release 12 (Accounts Receivables,  Accounts
Payables,  General Ledger,  Order Management,  Work  in Process,
Inventory, Bills of Material, Engineering,  Purchasing,  AOL, MRP,
iExpense, iProcurement, System Administration, Quoting, Trading
Community Architecture),  Oracle   Forms 6i/4.5/3.0 ,  Reports 6i/
2.5,  Oracle Workflow Builder, SQL navigator.

Databases:  Oracle 9i/10g, MS Access, DBASE IV

Languages:SQL Plus, PL/SQL, Basic,  Fortran IV, DBASE
IV

Operating System: Unix , Solaris 2.6, Windows 95/98/2000, NT 4.0,
DOS 6.0

Hardware: Sun Sparc, VAX –11/785, Intel based Pentium
I & II, IBM compatible 386/486



Thanks and Regards
Haritha

LIGHTNING MINDS
Phone : 703-349-5933
Email : hari...@lightningminds.com
Web: www.lightningminds.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance of list vs. set equality operations

2010-04-09 Thread Gabriel Genellina
En Thu, 08 Apr 2010 21:02:23 -0300, Patrick Maupin   
escribió:

On Apr 8, 6:35 pm, "Gabriel Genellina"  wrote:

The CPython source contains lots of shortcuts like that. Perhaps the  
checks should be stricter in some cases, but I imagine it's not so easy  
to fix: lots of code was written in the pre-2.2 era, assuming that  
internal types were not subclassable.


I don't know if it's a good "fix" anyway.  If you subclass an internal
type, you can certainly supply your own rich comparison methods, which
would (IMO) put the CPU computation burden where it belongs if you
decide to do something goofy like subclass a list and then override
__len__.


We're all consenting adults, that's the Python philosophy, isn't it?
If I decide to make stupid things, it's my fault. I don't see why Python  
should have to prevent that.


--
Gabriel Genellina

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


Re: Imports again...

2010-04-09 Thread Gabriel Genellina
En Fri, 09 Apr 2010 11:29:50 -0300, Tim Golden   
escribió:

On 09/04/2010 15:19, Gabriel Genellina wrote:


In addition to what Tim Golden has said (which appears to be based on  
another

version of this project


Just downloaded again, and there's definitely an empty package structure
of the kind I described. (Altho' I certainly did have a few other  
versions

lying around from previous questions by the OP).


Indeed! (Where did I look...?)

Also, you have some .pyw files with corresponding .pyc file. That's  
*very*

strange. .pyw files are *not* modules, and Python won't import them.



open ("xxx.pyw", "w").write ("print ('hello')")
import xxx

hello


Oops! Last time I checked, it didn't work... but it was a very long time  
ago, I presume. pyw files are importable since Python 2.2!

Thanks for the correction.

--
Gabriel Genellina

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


Re: Striving for PEP-8 compliance

2010-04-09 Thread John Nagle

Lawrence D'Oliveiro wrote:
In message , Gabriel 
Genellina wrote:



If you only reindent the code (without adding/removing lines) then you can
compare the compiled .pyc files (excluding the first 8 bytes that contain
a magic number and the source file timestamp). Remember that code objects
contain line number information.


Anybody who ever creates another indentation-controlled language should be 
beaten to death with a Guido van Rossum voodoo doll.


   No, the dumb thing was shipping a Python implementation which accepted both
tabs and spaces for indentation in the same file.  Tabs vs. spaces is
a religious issue, but mixing the two is unquestionably bad.

   Python 3.x, finally, detects inconsistent tab/space indentation. But that
should have been in Python 0.001, so that no inconsistent code ever escaped
into the wild.

   Check to see if your code will go through Python 3.x without indentation
complaints.  If it won't, you need to fix it before re-indenting.

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


Re: Python Line Intersection

2010-04-09 Thread John Nagle

Chris Rebert wrote:

On Fri, Apr 9, 2010 at 8:04 AM, Peyman Askari  wrote:

Hello

This is partly Python related, although it might end up being more math related.

I am using PyGTK (GUI builder for Python) and I need to find the intersection 
point for two lines. It is easy to do, even if you only have the four points 
describing line segments 
(http://www.maths.abdn.ac.uk/~igc/tch/eg1006/notes/node23.html). However, it 
requires that you solve for two equations. How can I do this in Python, either 
solve equations, or calculating intersection points some other way?



Just solve the equations ahead of time by using generic ones.

Given:
y = mx + b
y = nx + c

We set them equal and solve for x:
mx + b = nx + c
mx - nx = c - b
(m-n)x = c - b
x = (c - b) / (m-n)


   Actually, you don't want to do it that way, because it fails for vertical
lines, when m and n go to infinity.

See Wikipedia for the usual solution, given points on both lines:

http://en.wikipedia.org/wiki/Line-line_intersection

This is done all the time in computer graphics work.

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


Re: lambda with floats

2010-04-09 Thread monkeys paw

On 4/9/2010 3:43 AM, Bas wrote:

On Apr 7, 6:15 am, Patrick Maupin  wrote:

I should stop making a habit of responding to myself, BUT.  This isn't
quite an acre in square feet.  I just saw the 43xxx and assumed it
was, and then realized it couldn't be, because it wasn't divisible by
10.  (I used to measure land with my grandfather with a 66 foot long
chain, and learned at an early age that an acre was 1 chain by 10
chains, or 66 * 66 * 10 = 43560 sqft.)
That's an exact number, and 208 is a poor approximation of its square
root.


There is no need to remember those numbers for the imperially
challenged people:

In [1]: import scipy.constants as c


scipy.constants ??

doesn't work for me.



In [2]: def acre2sqft(a):
...: return a * c.acre / (c.foot * c.foot)
...:

In [3]: acre2sqft(1)
Out[3]: 43560.0


Cheers,
Bas


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


Re: Imports again...

2010-04-09 Thread Gabriel Genellina

En Fri, 09 Apr 2010 13:10:44 -0300, Alex Hall  escribió:


c:\Python26>python.exe i:\arm\main.pyw
Traceback (most recent call last):
  File "i:\arm\main.pyw", line 3, in 
import arm, network, weather, dict
  File "i:\arm\arm.py", line 4, in 
import config
  File "i:\arm\config.py", line 4, in 
from main import exitProgram
  File "i:\arm\main.pyw", line 3, in 
import arm, network, weather, dict
  File "i:\arm\network.py", line 4, in 
arm.ready()
AttributeError: 'module' object has no attribute 'ready'


I realize it may be odd to import from main.pyw, but I do not think
that could be causing the problem... could it?


Yes, it *is* a problem. Note the traceback sequence: main imports arm, arm  
imports config, config imports arm *again* (which is only partially  
initialized), arm imports network, and network tries to use arm.ready and  
fails.


Try to organize your modules hierarchically, so modules higher in the  
hierarchy may import (and use) other modules lower in the hierarchy, but  
not the other way around.
Doing it that way helps also to make clear the intent of each module (and  
class).
The 'main' script should be at the top of the hierarchy: 'main' may import  
anything, but no one may import 'main'. Put your high-level modules below  
it; they may use other low-level ones.


--
Gabriel Genellina

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


Re: Cleanup guarantees?

2010-04-09 Thread Gabriel Genellina
En Fri, 09 Apr 2010 01:13:37 -0300, Alf P. Steinbach   
escribió:


 > 
 > import urllib.request   # urlopen
 > import codecs   # getreader
 > import sys  # stderr
 >
 > def text_stream_from( url, encoding ):
 >  text_reader = codecs.getreader( encoding )
 >  connection = urllib.request.urlopen( url )
 >  return text_reader( connection )
 >
 > def list_text( url, encoding ):
 >  lines = text_stream_from( url, encoding )
 >  for line in lines:
 >  print( line, end = "" )
 >  lines.close()   # Undocumented?
 >
 > url = "http://www.rfc-editor.org/rfc/rfc1149.txt";
 > list_text( url, "ascii" )
 > 
 >
 > First, I'm unable to find documentation that there /is/ a close method  
in the
 > text_reader object, and I'm unable to find documentation that there is  
a close

 > method in the file like connection object; is there such documentation?

codecs.getreader returns a StreamReader instance (see [1])
StreamReader is documented here [2] and it says "In addition to the above  
methods, the StreamReader must also inherit all other methods and  
attributes from the underlying stream." -- the stream being 'connection',  
from urllib.request.urlopen.
The 3.x version of the documentation in [3] doesn't provide any details  
except being "a file-like object". The 2.x version [4] is much more clear:  
"a file-like object is returned. This supports the following methods:  
read(), readline(), readlines(), fileno(), close(), info(), getcode() and  
geturl(). It also has proper support for the iterator protocol."


[1] http://docs.python.org/py3k/library/codecs.html#codecs.getreader
[2] http://docs.python.org/py3k/library/codecs.html#codecs.StreamReader
[3]  
http://docs.python.org/py3k/library/urllib.request.html#urllib.request.urlopen

[4] http://docs.python.org/library/urllib.html#urllib.urlopen


 > Second, I'm unable to find documentation of when they're called and  
what they

 > do. It seems that (A) when the connection object's st
 method is called automatically, and (B) that when the
 > text_reader object's close method is called it calls the close method  
of the
 > wrapped stream (i.e. on the connection object). But where is this  
documented?


Nowhere, AFAIK.
I bet documentation patches are welcome.

--
Gabriel Genellina

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


Re: fcntl, serial ports and serial signals on RS232.

2010-04-09 Thread Max Kotasek
On Apr 8, 11:17 am, Grant Edwards  wrote:
> On 2010-04-07, Max Kotasek  wrote:
>
> > I'm trying to figure out how to parse the responses fromfcntl.ioctl()
> > calls that modify the serial lines in a way that asserts that the line
> > is now changed.
>
> Two comments:
>
>   1) None of the Linux serial drivers I've worked on return line states
>      except when you call TIOCMGET.
>
>   2) If the TIOCMBI[S|C] call returned a 'success' value, then the
>      line was set to what you requested.
>
> If you want to read back the state that you just wrote, you can call
> TIOCMGET, but for the "output" pins it's always going to return the
> last value that was written.
>
> > For example I may want to drop RTS explicitly, and
> > assert that the line has been dropped before returning.
>
> Call TIOCMSET.  If it doesn't return an error, then you're done.
>
> > Here is a brief snippet of code that I've been using to do that, but
> > not sure what to do with the returned response:
>
> What returned response?
>
> The only thing that is returned by TIOCMBIS/TIOCMBIC is a status value
> of 0 for success and <0 for failure. IIRC, that value is checked by
> Python'sfcntl.ioctl wrapper and it will raise an exception on
> failure.
>
> > Is someone familiar with manipulating serial signals like this in
> > python?
>
> Yes.
>
> > Am I even taking the right approach by using thefcntl.ioctl call?
>
> Yes.  When you set/clear RTS or DTR do they not go up/down?
>
> Even if you can't use pyserial, it's a good source for example code.
>
> --
> Grant Edwards               grant.b.edwards        Yow! TONY RANDALL!  Is YOUR
>                                   at               life a PATIO of FUN??
>                               gmail.com            


I appreciate the feedback.  I'm working in an environment with a lot
of changing factors, it's nice to have a piece not act unexpectedly.

Max

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


Re: python as pen and paper substitute

2010-04-09 Thread Michael Torrie
On 04/08/2010 02:54 PM, Manuel Graune wrote:
> 
> Well, the subject does say python and not elisp, but I'm a vim-user
> anyways. 

Did you look at the link to Owen Taylor's reinteract program?  I think
it's closer to what you want than any other thing mentioned here, with
the exception that it's a standalone GTK (graphical) app.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python question

2010-04-09 Thread Gabriel Genellina
En Fri, 09 Apr 2010 14:14:34 -0300, Binary  
 escribió:


How much space approximately is required to install the following packs  
on Windows XP?


pycairo-1.4.12-2.win32-py2.6.exe
python-2.6.1.msi
pygobject-2.14.2-2.win32-py2.6.exe
pygtk-2.12.1-3.win32-py2.6.exe
pywin32-213.win32-py2.6.exe
gtk-2.12.9-win32-2.exe


You might estimate it by the size of those files; use a factor of 2 or 3  
due to compression.



Does all this packs requires installation,


python and gtx must be installed as any other Windows program, and  
probably require administrator rights. I don't know all of the remaining  
files, but they look like Python packages; the installer typically drop  
some files into c:\python26\lib\site-packages and register something.


or it's possible just extract and place them in to C: drive, then to set  
environment variables properly?

Does this packs installs dynamic libraries and writes to registry?


Python and Gtk, yes. The other packages, maybe not.

--
Gabriel Genellina

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


Re: lambda with floats

2010-04-09 Thread Patrick Maupin
On Apr 9, 1:22 pm, monkeys paw  wrote:
> On 4/9/2010 3:43 AM, Bas wrote:
>
> > On Apr 7, 6:15 am, Patrick Maupin  wrote:
> >> I should stop making a habit of responding to myself, BUT.  This isn't
> >> quite an acre in square feet.  I just saw the 43xxx and assumed it
> >> was, and then realized it couldn't be, because it wasn't divisible by
> >> 10.  (I used to measure land with my grandfather with a 66 foot long
> >> chain, and learned at an early age that an acre was 1 chain by 10
> >> chains, or 66 * 66 * 10 = 43560 sqft.)
> >> That's an exact number, and 208 is a poor approximation of its square
> >> root.
>
> > There is no need to remember those numbers for the imperially
> > challenged people:
>
> > In [1]: import scipy.constants as c
>
> scipy.constants ??
>
> doesn't work for me.
>
>
>
> > In [2]: def acre2sqft(a):
> >     ...:     return a * c.acre / (c.foot * c.foot)
> >     ...:
>
> > In [3]: acre2sqft(1)
> > Out[3]: 43560.0
>
> > Cheers,
> > Bas
>
>

Basically, he's saying that, instead of remembering the very simple
"66" and "10" values, you can download and install a multi-megabyte
gzipped tar file for the scipy project. ;-)

(Of course, you get a few nice functions thrown in for free along with
your constants, but downloading scipy for its constants is like
choosing a sports car for its cupholders.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance of list vs. set equality operations

2010-04-09 Thread Patrick Maupin
On Apr 9, 1:07 pm, "Gabriel Genellina"  wrote:
> En Thu, 08 Apr 2010 21:02:23 -0300, Patrick Maupin   
> escribió:
>
> > On Apr 8, 6:35 pm, "Gabriel Genellina"  wrote:
>
> >> The CPython source contains lots of shortcuts like that. Perhaps the  
> >> checks should be stricter in some cases, but I imagine it's not so easy  
> >> to fix: lots of code was written in the pre-2.2 era, assuming that  
> >> internal types were not subclassable.
>
> > I don't know if it's a good "fix" anyway.  If you subclass an internal
> > type, you can certainly supply your own rich comparison methods, which
> > would (IMO) put the CPU computation burden where it belongs if you
> > decide to do something goofy like subclass a list and then override
> > __len__.
>
> We're all consenting adults, that's the Python philosophy, isn't it?
> If I decide to make stupid things, it's my fault. I don't see why Python  
> should have to prevent that.
>
> --
> Gabriel Genellina

Exactly.  I think we're in violent agreement on this issue ;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python grep

2010-04-09 Thread Peter Otten
Mag Gam wrote:

> I am in the process of reading a zipped file which is about 6gb.
> 
> I would like to know if there is a command similar to grep in python
> because I would like to emulate, -A -B option of GNU grep.
> 
> Lets say I have this,
> 
> 083828.441,AA
> 093828.441,AA
> 094028.441,AA
> 094058.441,CC
> 094828.441,AA
> 103828.441,AA
> 123828.441,AA
> 
> 
> if I do grep -A2 -B2 "CC"
> 
> I get 2 lines before and 2 lines after "C"
> 
> Is there an easy way to do this in python?


from itertools import islice, groupby
from collections import deque

def grep(instream, ismatch, before, after):
items_before = None
for key, group in groupby(instream, ismatch):
if key:
if items_before is not None:
for item in items_before:
yield "before", item
else:
items_before = not None # ;)
for item in group:
yield "match", item
else:
if items_before is not None:
for item in islice(group, after):
yield "after", item
items_before = deque(group, maxlen=before)


def demo1():
with open(__file__) as instream:
for state, (index, line) in grep(enumerate(instream, 1),
 ismatch=lambda (i, s): "item" in s, 
before=2, after=2):
print "%3d %-6s %s" % (index, state + ":", line),

def demo2():
from StringIO import StringIO
import csv
lines = StringIO("""\
083828.441,AA
093828.441,AA
094028.441,AA
094058.441,CC
094828.441,AA
103828.441,AA
123828.441,AA
""")

rows =  csv.reader(lines)
for state, row in grep(rows, lambda r: r[-1] == "CC", 1, 2):
print row

if __name__ == "__main__":
demo1()
demo2()

Probably too slow; badly needs testing.

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


Re: lambda with floats

2010-04-09 Thread monkeys paw

On 4/9/2010 2:40 PM, Patrick Maupin wrote:

On Apr 9, 1:22 pm, monkeys paw  wrote:

On 4/9/2010 3:43 AM, Bas wrote:


On Apr 7, 6:15 am, Patrick Maupinwrote:

I should stop making a habit of responding to myself, BUT.  This isn't
quite an acre in square feet.  I just saw the 43xxx and assumed it
was, and then realized it couldn't be, because it wasn't divisible by
10.  (I used to measure land with my grandfather with a 66 foot long
chain, and learned at an early age that an acre was 1 chain by 10
chains, or 66 * 66 * 10 = 43560 sqft.)
That's an exact number, and 208 is a poor approximation of its square
root.



There is no need to remember those numbers for the imperially
challenged people:



In [1]: import scipy.constants as c


scipy.constants ??

doesn't work for me.




In [2]: def acre2sqft(a):
 ...: return a * c.acre / (c.foot * c.foot)
 ...:



In [3]: acre2sqft(1)
Out[3]: 43560.0



Cheers,
Bas





Basically, he's saying that, instead of remembering the very simple
"66" and "10" values, you can download and install a multi-megabyte
gzipped tar file for the scipy project. ;-)

(Of course, you get a few nice functions thrown in for free along with
your constants, but downloading scipy for its constants is like
choosing a sports car for its cupholders.)


yea, the 66 foot chain story is a good one, i cant forget that. 
Appreciate the help, i just looked up the SciPY Project download,

it is 40 MB. I'm gonna check it out none the less...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python Line Intersection

2010-04-09 Thread lepy
> See Wikipedia for the usual solution, given points on both lines:
>
>        http://en.wikipedia.org/wiki/Line-line_intersection
# -*- coding: utf-8 -*-
import numpy as N

def intersect(line1, line2):
"""\begin{align} P(x,y)= \bigg(&\frac{(x_1 y_2-y_1 x_2)(x_3-x_4)-
(x_1-x_2)(x_3 y_4-y_3 x_4)}{(x_1-x_2)(y_3-y_4)-(y_1-y_2)(x_3-x_4)}, \\
&\frac{(x_1 y_2-y_1 x_2)(y_3-y_4)-(y_1-y_2)(x_3 y_4-y_3 x_4)}{(x_1-x_2)
(y_3-y_4)-(y_1-y_2)(x_3-x_4)}\bigg) \end{align}"""

x_1 = line1.x0[0]
y_1 = line1.x0[1]
x_2 = line1.x1[0]
y_2 = line1.x1[1]

x_3 = line2.x0[0]
y_3 = line2.x0[1]
x_4 = line2.x1[0]
y_4 = line2.x1[1]

try:
denom = float((x_1 - x_2) * (y_3 - y_4) - (y_1 - y_2) * (x_3 -
x_4))
x = ((x_1 * y_2 - y_1 * x_2) * (x_3 - x_4) - (x_1 - x_2) *
(x_3 * y_4 - y_3 * x_4)) / denom
y = ((x_1 * y_2 - y_1 * x_2) * (y_3 - y_4) - (y_1 - y_2) *
(x_3 * y_4 - y_3 * x_4)) / denom
except ZeroDivisionError:
return
return x, y

class Line(object):
def __init__(self, pkts=None):
self.x0 = N.array(pkts[0])
self.x1 = N.array(pkts[1])

if __name__ == "__main__":
line1 = Line(((0., 0.), (1., 1.)))
line2 = Line(((0., 1.), (1., 0.)))
print intersect(line1, line2)

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


Re: Pydev 1.5.6 Released (Django Integration)

2010-04-09 Thread Дамјан Георгиевски
> Hi All,
> 
> Pydev 1.5.6 has been released
> 
> Details on Pydev: http://pydev.org
> Details on its development: http://pydev.blogspot.com

Question,
Does it have a feature to evaluate the current edit buffer and continue 
with an interactive prompt?



-- 
дамјан ((( http://damjan.softver.org.mk/ )))

Hi! I'm a .signature virus! copy me into your .signature file to help me 
spread!

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


Re: Python Line Intersection

2010-04-09 Thread Chris Rebert
On Fri, Apr 9, 2010 at 11:43 AM, John Nagle  wrote:
> Chris Rebert wrote:
>> On Fri, Apr 9, 2010 at 8:04 AM, Peyman Askari 
>> wrote:
>>>
>>> Hello
>>>
>>> This is partly Python related, although it might end up being more math
>>> related.
>>>
>>> I am using PyGTK (GUI builder for Python) and I need to find the
>>> intersection point for two lines. It is easy to do, even if you only have
>>> the four points describing line segments
>>> (http://www.maths.abdn.ac.uk/~igc/tch/eg1006/notes/node23.html). However, it
>>> requires that you solve for two equations. How can I do this in Python,
>>> either solve equations, or calculating intersection points some other way?
>>
>> Just solve the equations ahead of time by using generic ones.

>> x = (c - b) / (m-n)
>
>   Actually, you don't want to do it that way, because it fails for vertical
> lines, when m and n go to infinity.

As the programmer said upon seeing a stripe-less zebra:
"Oh no, a special case!"

Excellent catch my good sir; although I will point out that strictly
speaking, you can't put vertical lines into slope-intercept form (but
I should not have forgotten that precondition).

Cheers,
Chris
--
Vertical line test, etc.
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


off by 1 error?

2010-04-09 Thread david jensen
Hi all,

I'm trying to assign a color to various values between some arbitrary
maximum and minimum, and i'd like to go from red to blue to green .
Currently, I have the following, where i'm passing the minimum and
maximum as a 2-tuple:

def getcolor( minmax, curr ):
rangesize = (minmax[1] - minmax[0]) - 1
currsize = float( curr - minmax[0] )
currpos = currsize / rangesize
colornum = int( currpos*511 + 0.5 )
r = max( 255 - colornum, 0 )
g = max( -256 + colornum, 0 )
b = 255 - ( r+g )
return r,g,b

1) is there a better way to do this?
2) at the extreme points, this doesn't work: the number of (255, 0,
0)s and (0, 255, 0)s are 1/2 what they should be, and (0, 0, 255) is
double what it should be.

the above algorithm at least doesn't give me things like (0, -1, 256),
which i struggled with for a while, but where is/are my off-by-one(s)?

many thanks

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


How to read file during module import?

2010-04-09 Thread Jeremy
I have a module that, when loaded, reads and parses a supporting
file.  The supporting file contains all the data for the module and
the function that reads/parses the file sets up the data structure for
the module.

How can I locate the file during the import statement.  The supporting
file is located in the same directory as the module, but when I import
I get a No such file or directory error.  I could hard code the path
to the filename, but that would make it only work on my machine.

A related question: Can I parse the data once and keep it somewhere
instead of reading the supporting file every time?  I tried pickling
but that wouldn't work because I have custom classes.  (Either that or
I just don't know how to pickle—this is a highly probable event.)

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


Dvalve! we called the heart of outsourcing world.

2010-04-09 Thread Dvalve.com

Dvalve.com is an online talent workplace that helps companies hire and
manage professionals online to get work done and grow their
businesses. Dvalve matches employers with a ready and qualified
workforce and rated, tested professionals with technical, marketing
and business skills. Dvalve also provides the online workplace and
tools to manage and pay remote professionals and teams online.
Contractors and service providers around the world use Dvalve to meet
employers and get paid for delivering great results.VISIT WWW.DVALVE.COM
FOR YOUR OUTSOURCE & BUSINESS NEEDS, SEE HOW FAST YOUR JOBS DONE WITH
QUALITY AND SECURITY.Dvalve a real virtual outsourcing ThinkTank.
Waiting for your valued participation.DVALVE TEAM Welcomes
freelancers, web designers. programmers, developers, designers,
business guys and all corporate and IT peoples TO WORK WITH US Please
Register as per your skills and wait for our Interview call. You can
register as a Service Provider or as a Buyer Account. Buyer will get
tie up Offers and providers will catch Jobs!.
One dice for all.
Regards
Dvalve Team
www.dvalve.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Dvalve! we called the heart of outsourcing world.

2010-04-09 Thread Dvalve.com

Dvalve.com is an online talent workplace that helps companies hire and
manage professionals online to get work done and grow their
businesses. Dvalve matches employers with a ready and qualified
workforce and rated, tested professionals with technical, marketing
and business skills. Dvalve also provides the online workplace and
tools to manage and pay remote professionals and teams online.
Contractors and service providers around the world use Dvalve to meet
employers and get paid for delivering great results.VISIT WWW.DVALVE.COM
FOR YOUR OUTSOURCE & BUSINESS NEEDS, SEE HOW FAST YOUR JOBS DONE WITH
QUALITY AND SECURITY.Dvalve a real virtual outsourcing ThinkTank.
Waiting for your valued participation.DVALVE TEAM Welcomes
freelancers, web designers. programmers, developers, designers,
business guys and all corporate and IT peoples TO WORK WITH US Please
Register as per your skills and wait for our Interview call. You can
register as a Service Provider or as a Buyer Account. Buyer will get
tie up Offers and providers will catch Jobs!.
One dice for all.
Regards
Dvalve Team
www.dvalve.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Dvalve! we called the heart of outsourcing world.

2010-04-09 Thread Dvalve.com

Dvalve.com is an online talent workplace that helps companies hire and
manage professionals online to get work done and grow their
businesses. Dvalve matches employers with a ready and qualified
workforce and rated, tested professionals with technical, marketing
and business skills. Dvalve also provides the online workplace and
tools to manage and pay remote professionals and teams online.
Contractors and service providers around the world use Dvalve to meet
employers and get paid for delivering great results.VISIT WWW.DVALVE.COM
FOR YOUR OUTSOURCE & BUSINESS NEEDS, SEE HOW FAST YOUR JOBS DONE WITH
QUALITY AND SECURITY.Dvalve a real virtual outsourcing ThinkTank.
Waiting for your valued participation.DVALVE TEAM Welcomes
freelancers, web designers. programmers, developers, designers,
business guys and all corporate and IT peoples TO WORK WITH US Please
Register as per your skills and wait for our Interview call. You can
register as a Service Provider or as a Buyer Account. Buyer will get
tie up Offers and providers will catch Jobs!.
One dice for all.
Regards
Dvalve Team
www.dvalve.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Dvalve! we called the heart of outsourcing world.

2010-04-09 Thread Dvalve.com

Dvalve.com is an online talent workplace that helps companies hire and
manage professionals online to get work done and grow their
businesses. Dvalve matches employers with a ready and qualified
workforce and rated, tested professionals with technical, marketing
and business skills. Dvalve also provides the online workplace and
tools to manage and pay remote professionals and teams online.
Contractors and service providers around the world use Dvalve to meet
employers and get paid for delivering great results.VISIT WWW.DVALVE.COM
FOR YOUR OUTSOURCE & BUSINESS NEEDS, SEE HOW FAST YOUR JOBS DONE WITH
QUALITY AND SECURITY.Dvalve a real virtual outsourcing ThinkTank.
Waiting for your valued participation.DVALVE TEAM Welcomes
freelancers, web designers. programmers, developers, designers,
business guys and all corporate and IT peoples TO WORK WITH US Please
Register as per your skills and wait for our Interview call. You can
register as a Service Provider or as a Buyer Account. Buyer will get
tie up Offers and providers will catch Jobs!.
One dice for all.
Regards
Dvalve Team
www.dvalve.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Dvalve! we called the heart of outsourcing world.

2010-04-09 Thread Dvalve.com
Dvalve.com is an online talent workplace that helps companies hire and
manage professionals online to get work done and grow their
businesses. Dvalve matches employers with a ready and qualified
workforce and rated, tested professionals with technical, marketing
and business skills. Dvalve also provides the online workplace and
tools to manage and pay remote professionals and teams online.
Contractors and service providers around the world use Dvalve to meet
employers and get paid for delivering great results.VISIT WWW.DVALVE.COM
FOR YOUR OUTSOURCE & BUSINESS NEEDS, SEE HOW FAST YOUR JOBS DONE WITH
QUALITY AND SECURITY.Dvalve a real virtual outsourcing ThinkTank.
Waiting for your valued participation.DVALVE TEAM Welcomes
freelancers, web designers. programmers, developers, designers,
business guys and all corporate and IT peoples TO WORK WITH US Please
Register as per your skills and wait for our Interview call. You can
register as a Service Provider or as a Buyer Account. Buyer will get
tie up Offers and providers will catch Jobs!.
One dice for all.
Regards
Dvalve Team
www.dvalve.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pickle problem while loading a class instance.

2010-04-09 Thread gerardob

I tried both things:

1- moved all the code to C:/Python26/lib/site-packages 
2- Modified the PYTHONPATH in the windows registry.

However, i stil have exactly the same error on the screen.

Any other suggestions?

Thanks.


Peter Otten wrote:
> 
> gerardob wrote:
> 
>> Hello, I am new to python and i have a problem using the pickle load
>> function.
>> I have an object m of the class MarkovModel and i want to copy it to a
>> file and load it onto another class:
>> 
>> l=[1,2,3]
>> m = markov_model.MarkovModel()
>> m.load_observations(l)
>> file = open("prueba.txt", 'w')
> 
> Remember to open the file in binary mode.
> 
>> pickle.dump(m,file,2)
>> file.close()
>> 
>> #m2 = markov_model.MarkovModel()
>> 
>> file = open("prueba.txt", 'rb')
>> m2 = pickle.load(file) (THIS IS LINE 36)
>> 
>> The error below appears. In the case i remove the comment to initialize
>> m2, the same thing happens. Any ideas on how to fix this?
> 
> Add the directory containing the markov_model module to your PYTHONPATH 
> environment variable or move the module into a directory where Python is 
> already looking (C:/Python26/lib/site-packages or the per-user
> equivalent).
> 
> See also http://docs.python.org/using/windows.html#finding-modules
> 
>> Traceback (most recent call last):
>> File "C:\Users\gberbeglia\Documents\python\scripting\mycodes\main.py",
>> line 36, in 
>> m2 = pickle.load(file)
>> File "C:\Python26\lib\pickle.py", line 1370, in load
>> return Unpickler(file).load()
>> File "C:\Python26\lib\pickle.py", line 858, in load
>> dispatch[key](self)
>> File "C:\Python26\lib\pickle.py", line 1090, in load_global
>> klass = self.find_class(module, name)
>> File "C:\Python26\lib\pickle.py", line 1124, in find_class
>> __import__(module)
>> ImportError: No module named markov_model
> 
> Peter
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

-- 
View this message in context: 
http://old.nabble.com/Pickle-problem-while-loading-a-class-instance.-tp28154964p28197881.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: How to read file during module import?

2010-04-09 Thread Gabriel Genellina

En Fri, 09 Apr 2010 18:04:59 -0300, Jeremy  escribió:


How can I locate the file during the import statement.  The supporting
file is located in the same directory as the module, but when I import
I get a No such file or directory error.  I could hard code the path
to the filename, but that would make it only work on my machine.


The directory containing the current module is:

module_dir = os.path.dirname(os.path.abspath(__file__))

so you could open your supporting file using:

fn = os.path.join(module_dir, "supporting_file_name.ext")
open(fn) ...


A related question: Can I parse the data once and keep it somewhere
instead of reading the supporting file every time?  I tried pickling
but that wouldn't work because I have custom classes.  (Either that or
I just don't know how to pickle—this is a highly probable event.)


What kind of "custom classes"?
An open file, or a socket, are examples of non pickleable objects; most  
other basic built-in objects are pickleable. Instances of user-defined  
classes are pickleable if they contain pickleable attributes. Micro recipe:


# pickle some_object
with open(filename, "wb") as f:
  pickle.dump(some_object, f, -1)

# unpickle it
with open(filename, "rb") as f:
  some_object = pickle.load(f)

Try again and report any problem you encounter...

--
Gabriel Genellina

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


Re: Pickle problem while loading a class instance.

2010-04-09 Thread Gabriel Genellina
En Fri, 09 Apr 2010 18:42:23 -0300, gerardob   
escribió:



I tried both things:

1- moved all the code to C:/Python26/lib/site-packages
2- Modified the PYTHONPATH in the windows registry.

However, i stil have exactly the same error on the screen.

Any other suggestions?


Did you follow the advice below?


Peter Otten wrote:



file = open("prueba.txt", 'w')


Remember to open the file in binary mode.


You have to re-create your pickle file, open it in binary mode 'wb'  
("prueba.txt" is not a good name - it's not a text file).

Any old pickle file created in text mode won't be readable.

--
Gabriel Genellina

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


Re: How to read file during module import?

2010-04-09 Thread Jeremy
On Apr 9, 4:02 pm, "Gabriel Genellina"  wrote:
> En Fri, 09 Apr 2010 18:04:59 -0300, Jeremy  escribió:
>
> > How can I locate the file during the import statement.  The supporting
> > file is located in the same directory as the module, but when I import
> > I get a No such file or directory error.  I could hard code the path
> > to the filename, but that would make it only work on my machine.
>
> The directory containing the current module is:
>
> module_dir = os.path.dirname(os.path.abspath(__file__))

I didn't know about  __file__ this works!  Thanks.
>
> so you could open your supporting file using:
>
> fn = os.path.join(module_dir, "supporting_file_name.ext")
> open(fn) ...
>
> > A related question: Can I parse the data once and keep it somewhere
> > instead of reading the supporting file every time?  I tried pickling
> > but that wouldn't work because I have custom classes.  (Either that or
> > I just don't know how to pickle—this is a highly probable event.)
>
> What kind of "custom classes"?

My custom classes are not very fancy.  They basically are dictionaries
and lists organizing the data in the supporting file.  I was actually
surprised they didn't pickle because the classes were so simple.

> An open file, or a socket, are examples of non pickleable objects; most  
> other basic built-in objects are pickleable. Instances of user-defined  
> classes are pickleable if they contain pickleable attributes. Micro recipe:
>
> # pickle some_object
> with open(filename, "wb") as f:
>    pickle.dump(some_object, f, -1)

When I did this I got the following error:

PicklingError: Can't pickle : it's not found
as __main__.element

Am I just being dumb?

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


Re: Pickle problem while loading a class instance.

2010-04-09 Thread Peter Otten
gerardob wrote:

> 
> I tried both things:
> 
> 1- moved all the code to C:/Python26/lib/site-packages
> 2- Modified the PYTHONPATH in the windows registry.
> 
> However, i stil have exactly the same error on the screen.
> 
> Any other suggestions?

Did you heed my advice and make sure that your script reads and writes the 
pickle file in binary mode?

> file = open("prueba.txt", 'w')

The above line can trigger the same error; change "w" to "wb":

>>> import pickle
>>> class A: pass
...
>>> s = pickle.dumps(A())
>>> pickle.loads(s)
<__main__.A instance at 0x7f31d088ed88>

Seems to work. Now let's simulate the effect of writing in text and reading 
in binary mode:

>>> pickle.loads(s.replace("\n", "\r\n"))
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib/python2.6/pickle.py", line 1374, in loads
return Unpickler(file).load()
  File "/usr/lib/python2.6/pickle.py", line 858, in load
dispatch[key](self)
  File "/usr/lib/python2.6/pickle.py", line 1069, in load_inst
klass = self.find_class(module, name)
  File "/usr/lib/python2.6/pickle.py", line 1124, in find_class
__import__(module)
ImportError: No module named __main__

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


Re: Striving for PEP-8 compliance

2010-04-09 Thread Lawrence D'Oliveiro
In message <4bbf6eb8$0$1670$742ec...@news.sonic.net>, John Nagle wrote:

> Lawrence D'Oliveiro wrote:
>
>> In message ,
>> Gabriel Genellina wrote:
>> 
>>> If you only reindent the code (without adding/removing lines) then you
>>> can compare the compiled .pyc files (excluding the first 8 bytes that
>>> contain a magic number and the source file timestamp). Remember that
>>> code objects contain line number information.
>> 
>> Anybody who ever creates another indentation-controlled language should
>> be beaten to death with a Guido van Rossum voodoo doll.
> 
> No ...

Yes, because otherwise you wouldn’t have stupid problems like the one which 
is preoccupying this thread: how to make sure indentation is consistent 
without introducing logic errors into the code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Event: First meeting of Karlsruhe User Group (tentatively named "KaPy"), 2010-04-16, 19:00:00 CEST

2010-04-09 Thread Jürgen Erhard
A new user group is being set up by some interested pythoneers from
(around) Karlsruhe.

The first meeting will be on Friday, 2010-04-16 (April 16th, 2010) at
19:00 (7pm) in the rooms of Entropia eV (the local affiliate of the
CCC).  See http://entropia.de/wiki/Anfahrt on how to get there.  Or
reply to me if you need instructions in English; there's a map on that
page, but the devil's in the details, as always.

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


urllib2: post request to textarea

2010-04-09 Thread bfrederi
I'm getting a 500 error when attempting to make a post request with
urllib2 to a form with a  tag. When I create the post
request with all the other post data, I don't get a 500. Just the part
of the form that is a . Is this just a coincidence, and my
real problem is something else?

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


getopt question

2010-04-09 Thread Raphael Mayoraz

Hello,

I have some trouble to make getopt.getopt work and the way I want (and 
is described in the documentation).


Attached is very small script to reproduce my problem.

If running:
> python testGetOpt.py -a junk1 -b junk2
everything is ok

> python testGetOpt.py -c junk1
ok too: I get the 'Invalid option' error message

now:
> python testGetOpt.py -a junk1 -c junk2
I'm expecting this to also print the error message, as 'c' is not in the 
argument given in getopt.getopt, but it doesn't.


What am I doing wrong ?

Using python 2.6.4 on WindowXP.

Thanks.

Raphael


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


Re: nested threading

2010-04-09 Thread Aahz
In article <4566e767-768f-4399-8a6b-5530ec90b...@a37g2000prd.googlegroups.com>,
Omer Ihsan   wrote:
>
>is there anything as "nested threading"that is, call a thread from
>within a thread.
>in this case how will thread locking take place.
>
>for example initially there were two functions that were called using
>threading.Thread. these wont get unlocked unless both of them are done
>with whatever they need to do. if say function 2 calls another thread.
>then what??

You need to do the locking explicitly.  There's really no such thing as
a nested thread in Python -- it's all a "flat namespace".  However,
trying to nest threads conceptually is likely to get you into deadlock
issues.  You are more likely to make things work if you just start all
threads in parallel.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"...string iteration isn't about treating strings as sequences of strings, 
it's about treating strings as sequences of characters.  The fact that
characters are also strings is the reason we have problems, but characters 
are strings for other good reasons."  --Aahz
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: off by 1 error?

2010-04-09 Thread Terry Reedy

On 4/9/2010 4:10 PM, david jensen wrote:

Hi all,

I'm trying to assign a color to various values between some arbitrary
maximum and minimum, and i'd like to go from red to blue to green .
Currently, I have the following, where i'm passing the minimum and
maximum as a 2-tuple:

def getcolor( minmax, curr ):


One would need more info re minmax and curr and their relationship to 
definitively answer your question.



rangesize = (minmax[1] - minmax[0]) - 1


I would expect that either +0 or +1 woult be correct


currsize = float( curr - minmax[0] )
currpos = currsize / rangesize
colornum = int( currpos*511 + 0.5 )


The .5 may be the reason for the '1/2' question.


r = max( 255 - colornum, 0 )
g = max( -256 + colornum, 0 )


r,g are both 0 for both 255 and 256. I suspect this is reason for the 
'double' question.



b = 255 - ( r+g )
return r,g,b

1) is there a better way to do this?
2) at the extreme points, this doesn't work: the number of (255, 0,
0)s and (0, 255, 0)s are 1/2 what they should be, and (0, 0, 255) is
double what it should be.

the above algorithm at least doesn't give me things like (0, -1, 256),
which i struggled with for a while, but where is/are my off-by-one(s)?


Again, start with a complete definition of the params.

Terry Jan Reedy

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


getopt question

2010-04-09 Thread Raphael Mayoraz

Ooops, forgot to attach the file in my first e-mail. Now, here it is.


Hello,

I have some trouble to make getopt.getopt work and the way I want (and 
is described in the documentation).


Attached is very small script to reproduce my problem.

If running:
> python testGetOpt.py -a junk1 -b junk2
everything is ok

> python testGetOpt.py -c junk1
ok too: I get the 'Invalid option' error message

now:
> python testGetOpt.py -a junk1 -c junk2
I'm expecting this to also print the error message, as 'c' is not in the 
argument given in getopt.getopt, but it doesn't.


What am I doing wrong ?

Using python 2.6.4 on WindowXP.

Thanks.

Raphael
-

#!/usr/bin/env python
import sys
import getopt

try:
opts, args = getopt.getopt(sys.argv[1:], 'ab')
except getopt.error:
print 'Invalid option'
sys.exit(0)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getopt question

2010-04-09 Thread Sean DiZazzo
On Apr 9, 4:37 pm, Raphael Mayoraz  wrote:
> Ooops, forgot to attach the file in my first e-mail. Now, here it is.
>
> 
> Hello,
>
> I have some trouble to make getopt.getopt work and the way I want (and
> is described in the documentation).
>
> Attached is very small script to reproduce my problem.
>
> If running:
>  > python testGetOpt.py -a junk1 -b junk2
> everything is ok
>
>  > python testGetOpt.py -c junk1
> ok too: I get the 'Invalid option' error message
>
> now:
>  > python testGetOpt.py -a junk1 -c junk2
> I'm expecting this to also print the error message, as 'c' is not in the
> argument given in getopt.getopt, but it doesn't.
>
> What am I doing wrong ?
>
> Using python 2.6.4 on WindowXP.
>
> Thanks.
>
> Raphael
> -
>
> [testGetOpt.py< 1K ]#!/usr/bin/env python
> import sys
> import getopt
>
> try:
>     opts, args = getopt.getopt(sys.argv[1:], 'ab')
> except getopt.error:
>     print 'Invalid option'
>     sys.exit(0)

If your argument is expecting a value, you need to add a colon after
it in the argument string.  ie.  'a:b:'

Guessing if you print 'args' from your example, both the -c and junk1
will be in there.

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


Re: Striving for PEP-8 compliance

2010-04-09 Thread Grant Edwards
On 2010-04-09, Lawrence D'Oliveiro  wrote:
> In message <4bbf6eb8$0$1670$742ec...@news.sonic.net>, John Nagle wrote:
>
>> Lawrence D'Oliveiro wrote:
>>
>>> In message ,
>>> Gabriel Genellina wrote:
>>> 
 If you only reindent the code (without adding/removing lines) then you
 can compare the compiled .pyc files (excluding the first 8 bytes that
 contain a magic number and the source file timestamp). Remember that
 code objects contain line number information.
>>> 
>>> Anybody who ever creates another indentation-controlled language should
>>> be beaten to death with a Guido van Rossum voodoo doll.
>> 
>> No ...
>
> Yes, because otherwise you wouldn?t have stupid problems like the one
> which is preoccupying this thread: how to make sure indentation is
> consistent without introducing logic errors into the code.

Anybody who invents another brace-delimited language should be beaten.
You always end up with a big problem trying to make sure the braces
are consistent with the program logic.

-- 
Grant

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


Re: Striving for PEP-8 compliance

2010-04-09 Thread Lawrence D'Oliveiro
In message , Grant Edwards wrote:

> Anybody who invents another brace-delimited language should be beaten.
> You always end up with a big problem trying to make sure the braces
> are consistent with the program logic.

Would you prefer “begin” and “end” word symbols, then?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Preserving logging streams through a daemon.DaemonContext switch

2010-04-09 Thread Ben Finney
Vinay Sajip  writes:

> On Apr 9, 12:46 am, Ben Finney  wrote:
> > Not quite. As the docs specify, you need to pass the *file
> > descriptors* for the files you want preserved.
>
> Okay, but the docstring you quoted:
>
> "Elements of the list are file descriptors (as returned by a file
> object's `fileno()` method) or Python `file` objects."
>
> implies that fh.stream would work as well as fh.stream.fileno()

You're quite right, I made a mistake in what I wrote above.

Rebelo  writes:

> Ben Finney wrote:
> > So how do we get the file object for a logging handler? The
> > ‘logging’ module documentation doesn't mention any way to get at the
> > stream object for the handlers.
> >
> > But looking at the source code for ‘StreamHandler’ on my system,
> > ‘/usr/lib/python2.5/logging/__init__.py’, shows a ‘stream’ attribute
> > that is bound to the stream object. It's not marked private (i.e.
> > it's not named with a leading underscore), so one presumes it is
> > part of the public API.

[…]

> >
> > lh = logging.handlers.TimedRotatingFileHandler(
> > LOG_FILENAME,
> > # …
> > )
> > log_stream_descriptor = lh.stream.fileno()
> >
> > daemon_context.files_preserve = [log_stream_descriptor]
> >

The above can then be simplified as:

lh = logging.handlers.TimedRotatingFileHandler(
LOG_FILENAME,
# …
)

daemon_context.files_preserve = [lh.stream]

> thank you both for a detailed explanation.

I hope this helps you to make better use of ‘python-daemon’, and thank
you for raising questions here.

This is a good addition for the Frequently Asked Questions document; I
will do this and it will be available in the next version of the
library.

-- 
 \   “I prayed for twenty years but received no answer until I |
  `\  prayed with my legs.” —Frederick Douglass, escaped slave |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Striving for PEP-8 compliance

2010-04-09 Thread Grant Edwards
On 2010-04-10, Lawrence D'Oliveiro  wrote:
> In message , Grant Edwards wrote:
>
>> Anybody who invents another brace-delimited language should be beaten.
>> You always end up with a big problem trying to make sure the braces
>> are consistent with the program logic.

> Would you prefer ???begin??? and ???end??? word symbols, then?

Nope, I categorize those as nothing more than verbose "braces".

-- 
Grant

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


Re: Striving for PEP-8 compliance

2010-04-09 Thread Patrick Maupin
On Apr 9, 5:31 pm, Lawrence D'Oliveiro  wrote:
> >> Anybody who ever creates another indentation-controlled language should
> >> be beaten to death with a Guido van Rossum voodoo doll.
>
> >     No ...
>
> Yes, because otherwise you wouldn’t have stupid problems like the one which
> is preoccupying this thread: how to make sure indentation is consistent
> without introducing logic errors into the code.

You go through life and you choose your stupid problems.  Well, not
really, but you make your choices, and you wind up with stupid
problems.  I use Linux, and have a different set of stupid problems
than I did when I used Windows.

But as Ian Bicking said:

I think there is a meme that Python people are close-minded to
suggestions for changes in the language. I think there is significant
truth to that. But sometimes everyone else is just completely wrong. I
want nothing to do with any programmer who would mis-indent their
code. If you want to mis-indent your code you are an idiot. If you
want idiotic code to be an option you are being absurd.

And as paraphrased by Markos Gaivo ( http://markos.gaivo.net/blog/?p=126
):

A: I don’t like Python because of significant whitespace.
B: Do you indent your code?
A: Yes, of course.
B: And the problem is?

Regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: raise exception with fake filename and linenumber

2010-04-09 Thread kwatch
On 4月8日, 午後12:52, "Gabriel Genellina"  wrote:
>
> The built-in SyntaxError exception does what you want. Constructor  
> parameters are undocumented, but they're as follows:
>
>     raise SyntaxError("A descriptive error message", (filename, linenum,  
> colnum, source_line))
>
> colnum is used to place the ^ symbol (10 in this fake example). Output:
>
> Traceback (most recent call last):
>    File "1.py", line 9, in 
>      foo()
>    File "1.py", line 7, in foo
>      raise SyntaxError("A descriptive error message", (filename, linenum,  
> colnum, "this is line 123 in example.file"))
>    File "example.file", line 123
>      this is line 123 in example.file
>               ^
> SyntaxError: A descriptive error message
>
> --
> Gabriel Genellina

Thank you Gabriel,
this is great help for me.

By the way, is it hard to specify any other exception class instead of
SyntaxError?
The SyntaxError class is a good solution in my case, but if possible,
I want to know
more general solution to specify filename and linenum for exception.

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


Re: Striving for PEP-8 compliance

2010-04-09 Thread Steven D'Aprano
On Sat, 10 Apr 2010 10:31:58 +1200, Lawrence D'Oliveiro wrote:

> In message <4bbf6eb8$0$1670$742ec...@news.sonic.net>, John Nagle wrote:
> 
>> Lawrence D'Oliveiro wrote:
>>
>>> In message ,
>>> Gabriel Genellina wrote:
>>> 
 If you only reindent the code (without adding/removing lines) then
 you can compare the compiled .pyc files (excluding the first 8 bytes
 that contain a magic number and the source file timestamp). Remember
 that code objects contain line number information.
>>> 
>>> Anybody who ever creates another indentation-controlled language
>>> should be beaten to death with a Guido van Rossum voodoo doll.
>> 
>> No ...
> 
> Yes, because otherwise you wouldn’t have stupid problems like the one
> which is preoccupying this thread: how to make sure indentation is
> consistent without introducing logic errors into the code.


I don't see the problem here.

The OP has code which is already correctly indented. He wants to re-
indent it, from two spaces to four. As I see it, even a simple-minded 
string replacement from 2 to 4 spaces should Just Work, provided you 
don't care about extra spacing potentially being introduced into strings, 
comments, etc.

E.g. if you have this (already ugly) code:


def f(a):
  x =  42
  if a < 0:
return a  # Return a untouched.
  else:
for i   in range(  x  )  :  # Do pointless work
  pass
this_is_a_very_long_line  = (   2, 4,  5, 
   7, 9)
return   a+1


and just do a simple string replacement, you get this:

def f(a):
x =42
if a < 0:
return a# Return a untouched.
else:
for i in range(x):# Do pointless work
pass
this_is_a_very_long_line= ( 2, 4,5,
 7, 9)
return a+1


which is still ugly, but continues to work correctly. The only way to 
break working code by re-indenting in such a simple-minded fashion is if 
the layout of string literals is significant.

But of course no professional-quality re-indenter program would just do a 
simple-minded replace('  ', '') on the source code, any more than a 
professional-quality code beautifier for a brace language would just add 
newlines and spaces around every brace it saw.

A less simple-minded re-indenter would only replace *indentation*, not 
random whitespace. In that case, how could it break anything? Since the 
indents are correct, you are mapping indents of 2, 4, 6, 8, ... spaces to 
4, 8, 12, 16,  What do you think will break?


If you start with broken indentation, it is difficult to fix, but that's 
not the OP's problem. In a brace language (whether you spell them { } or 
BEGIN END or START-BLOCK-HERE and END-BLOCK-HERE) if you start with 
inconsistent braces, it is equally difficult to fix. Invalid code is 
invalid code no matter what language you are using, and in general can't 
be mechanically fixed. If the nature of the breakage is such that the 
code is inconsistent or ambiguous, you need to *read* and *understand* it 
to fix it, no matter whether you have braces or indents.



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


Re: urllib2: post request to textarea

2010-04-09 Thread Tim Roberts
bfrederi  wrote:
>
>I'm getting a 500 error when attempting to make a post request with
>urllib2 to a form with a  tag. When I create the post
>request with all the other post data, I don't get a 500. Just the part
>of the form that is a . Is this just a coincidence, and my
>real problem is something else?

It's just a coincidence.  The contents of a  are transmitted
exactly like the contents of an .  My guess is that you
did the encoding improperly.
-- 
Tim Roberts, t...@probo.com
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance of list vs. set equality operations

2010-04-09 Thread Raymond Hettinger
> > I don't know if it's a good "fix" anyway.  If you subclass an internal
> > type, you can certainly supply your own rich comparison methods, which
> > would (IMO) put the CPU computation burden where it belongs if you
> > decide to do something goofy like subclass a list and then override
> > __len__.
>
> We're all consenting adults, that's the Python philosophy, isn't it?
> If I decide to make stupid things, it's my fault. I don't see why Python  
> should have to prevent that.

Perhaps so for pure python classes, but the C builtins are another
story.

The C containers directly reference underlying structure and methods
for several reasons.  The foremost reason is that if their internal
invariants are violated, they can segfault.  A list's __getitem__
method needs to know the real length (not what you report in __len__)
if it is to avoid writing objects outside of its allocated memory
range.  Another reason is efficiency -- the cost of attribute lookups
is high and would spoil the performance of the builtins if they could
not access their underlying structure and friend methods directly.
It is important to have those perform well because they are used
heavily
in everyday programming.

There are also couple of OOP design considerations.  The
http://en.wikipedia.org/wiki/Open/closed_principle is one example.

Encapsulation is another example.  If you override __len__
in order to influence the behavior of __eq__, then you're
relying on an implementation detail, not the published interface.
Eventhough the length check is an obvious optimization
for list equality and set equality, there is no guarantee
that other implementations of Python use that same pattern.

my-two-cents-ly yours,

Raymond


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


Re: Python Line Intersection

2010-04-09 Thread Mark Tolonen


"Chris Rebert"  wrote in message 
news:y2o50697b2c1004091304u627d99bfj44ad56fa76a3c...@mail.gmail.com...

On Fri, Apr 9, 2010 at 11:43 AM, John Nagle  wrote:

Chris Rebert wrote:
On Fri, Apr 9, 2010 at 8:04 AM, Peyman Askari 


wrote:


Hello

This is partly Python related, although it might end up being more math
related.

I am using PyGTK (GUI builder for Python) and I need to find the
intersection point for two lines. It is easy to do, even if you only 
have

the four points describing line segments
(http://www.maths.abdn.ac.uk/~igc/tch/eg1006/notes/node23.html). 
However, it

requires that you solve for two equations. How can I do this in Python,
either solve equations, or calculating intersection points some other 
way?


Just solve the equations ahead of time by using generic ones.



x = (c - b) / (m-n)


Actually, you don't want to do it that way, because it fails for vertical
lines, when m and n go to infinity.


As the programmer said upon seeing a stripe-less zebra:
"Oh no, a special case!"

Excellent catch my good sir; although I will point out that strictly
speaking, you can't put vertical lines into slope-intercept form (but
I should not have forgotten that precondition).


And parallel lines, where m and n are equal (divide-by-zero)...

-Mark


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


Re: Python Line Intersection

2010-04-09 Thread Lie Ryan
On 04/10/10 16:24, Mark Tolonen wrote:
> 
> "Chris Rebert"  wrote in message
> news:y2o50697b2c1004091304u627d99bfj44ad56fa76a3c...@mail.gmail.com...
>> On Fri, Apr 9, 2010 at 11:43 AM, John Nagle  wrote:
>>> Chris Rebert wrote:
 On Fri, Apr 9, 2010 at 8:04 AM, Peyman Askari
 
 wrote:
>
> Hello
>
> This is partly Python related, although it might end up being more
> math
> related.
>
> I am using PyGTK (GUI builder for Python) and I need to find the
> intersection point for two lines. It is easy to do, even if you
> only have
> the four points describing line segments
> (http://www.maths.abdn.ac.uk/~igc/tch/eg1006/notes/node23.html).
> However, it
> requires that you solve for two equations. How can I do this in
> Python,
> either solve equations, or calculating intersection points some
> other way?

 Just solve the equations ahead of time by using generic ones.
>> 
 x = (c - b) / (m-n)
>>>
>>> Actually, you don't want to do it that way, because it fails for
>>> vertical
>>> lines, when m and n go to infinity.
>>
>> As the programmer said upon seeing a stripe-less zebra:
>> "Oh no, a special case!"
>>
>> Excellent catch my good sir; although I will point out that strictly
>> speaking, you can't put vertical lines into slope-intercept form (but
>> I should not have forgotten that precondition).
> 
> And parallel lines, where m and n are equal (divide-by-zero)...

This is actually one place where non-stop arithmetic can be a good thing.

With non-stop arithmetic, when you divide by zero, you get infinity and
everything turns out quite well.
-- 
http://mail.python.org/mailman/listinfo/python-list