Re: Why date do not construct from date?

2009-06-02 Thread Gabriel Genellina
En Tue, 02 Jun 2009 03:14:22 -0300, Chris Rebert   
escribió:


On Mon, Jun 1, 2009 at 10:25 PM, Alexandr N Zamaraev   
wrote:



import datetime as dt
d = dt.date(2009, 10, 15)
dt.date(d)

Traceback (most recent call last):
 File "", line 1, in 
TypeError: function takes exactly 3 arguments (1 given)


Why int form int, str from str, Decumal from Decumal can construct bat  
date from date not?


Probably because the function signatures would be so different. str(),
int(), etc *always* take *exactly one* argument -- the object to
convert. In contrast, date() takes several integers corresponding to
the year, month, and day. Adding a second signature to it that took
exactly one argument (of type `date`) and copied it would be
significantly different from its other signature; in idiomatic Python,
one would typically make a separate, new function for this drastically
different signature.


That doesn't convince me. It's not very consistent along the various  
types: int("3ab0",16) is rather different than int(3.2) but they're the  
same function...



However, the `date` type is immutable, so there's no reason at all to
try and copy a new instance from an existing one anyway, thus a
single-argument copy-constructor is completely unnecessary, hence why
there isn't one.


Isn't the same for all other examples (int, float, str, Decimal...)?  
They're all immutable types, and some have several and rather different  
constructor signatures:


py> Decimal((0, (1, 5, 0, 0), -3))
Decimal('1.500')
py> Decimal(Decimal('1.500'))
Decimal('1.500')

If one can say float(3.0), str("hello"), etc -- what's so wrong with  
date(another_date)?


--
Gabriel Genellina

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


Re: Why date do not construct from date?

2009-06-02 Thread Peter Otten
Gabriel Genellina wrote:

> If one can say float(3.0), str("hello"), etc -- what's so wrong with
> date(another_date)?

You can do

x = float(x)

when you don't know whether x is a float, int, or str. Not terribly useful, 
but sometimes convenient because making the float() call idempotent allows 
you to skip the type check.

def subtract(a, b):
if isinstance(a, str): a = float(b)
if isinstance(b, str): b = float(b)
return a - b

becomes

def subtract(a, b):
return float(a) - float(b)

For date you'd have to make the type check anyway, e. g.

if isinstance(x, tuple): 
   x = date(*x)
else:
   x = date(x) # useless will only succeed if x already is a date

as there would be no other way to create a date from a single value.

So the date() call in the else branch is completely redundant unless you 
change date() to accept multiple types via the same signature:

for x in "2000-01-01", datetime.now(), (2000, 1, 1):
print date(x)

Peter


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


python 2.6 packages in python 3.0

2009-06-02 Thread ssd
Hi,

I usually works with packages like pyserial, numpy, mathplotlib,pyUSB, etc..

When is planned that these packages are supported in Python 3.0?

Seen this i would say that is not recommendable to use Python 3.0 at the 
moment? most of 2.6 packages are not available, not working in python 3.0.

Thanks,
Bye, 


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


Re: python 2.6 packages in python 3.0

2009-06-02 Thread Chris Rebert
On Tue, Jun 2, 2009 at 12:51 AM, ssd  wrote:
> Hi,
>
> I usually works with packages like pyserial, numpy, mathplotlib,pyUSB, etc..
>
> When is planned that these packages are supported in Python 3.0?

That would depend on the individual packages and their maintainers.
Check their respective websites. There is not, as of yet, any
concerted/coordinated effort to port third-party libraries to 3.0.

> Seen this i would say that is not recommendable to use Python 3.0 at the
> moment? most of 2.6 packages are not available, not working in python 3.0.

Yes, that's basically the state of things at the moment. We're in a
transitional phase while people port everything to Python 3.0 and/or
wait for the libraries they require to be ported to 3.0.

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


[no subject]

2009-06-02 Thread Kiran Siddiqui

hi have to parse a very complex dumps(whatever it is), i have done the parsing 
thruogh python.since the parsed data is very huge in amount, i have to feed it 
in the database (SQL), I have also done this... now the thing is i have to 
compare the data now present in the sql.
 
in actual i have to compare the data of 1st dump with the data of the 2nd 
dump. the both dump have the same fields(attributes) but the values of 
their field may be change... so i have to detect this change.. for this i have 
to do the comparison...
 
i.e, let i have a tableA ,its 1st row carry the data of dump1 and then on the 
2nd day the data comes from dump2 go into the next row of tableA. and i have to 
compare both rows. 
 
 but i dont have the idea how to do this all using python as my front end.
 
plz pl anyone help me:(
 
_
Show them the way! Add maps and directions to your party invites. 
http://www.microsoft.com/windows/windowslive/products/events.aspx-- 
http://mail.python.org/mailman/listinfo/python-list


what is the biggest number that i can send to Wave_write.writeframes(data)

2009-06-02 Thread '2+
would like to take advantage of the wave module
found a good example here:
http://www.python-forum.org/pythonforum/viewtopic.php?f=2&t=10644

hmm .. i don't get how to write a stereo .. i mean i can set nchannels
.. but how do i actually take control of each ch individually?
and what's the range(in float) of the data i can set in
wav_file.writeframes(struct.pack('h', data))?

tia

-- 
SaRiGaMa's Oil Vending Orchestra
is podcasting:
http://sarigama.namaste.jp/podcast/rss.xml
and supplying oil.py for free:
http://oilpy.blogspot.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "TypeError: 'int' object is not callable"

2009-06-02 Thread Richard Brodie

"Visco Shaun"  wrote in message 
news:mailman.966.1243852864.8015.python-l...@python.org...
> when I was executing the below code I got "TypeError: 'int' object is
> not callable" exception. Why is it so?
>
> if type(c) == type(ERROR):

You've probably assigned to type somewhere in your code. What does
print repr(type) give? 


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


Re: Ah, ctypes

2009-06-02 Thread Lawrence D'Oliveiro
In message , Nick Craig-
Wood wrote:

> As a ctypes user I found this an interesting story - thanks for
> posting it!

By the way, I hate wildcard imports. In the ctypes docs, they recommend you 
do this

from ctypes import *

but I prefer this:

import ctypes as ct

which explains the "ct." prefixes in my sample code, in case you were 
wondering.

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


Re:

2009-06-02 Thread Teguh Iskanto
how about this :
- dump those data with sort enabled
- use diff to those two dumps  , eg: diff dump_a dump_b

if you don't know what diff is , try : man diff

HTH


On Tue, Jun 2, 2009 at 2:50 AM, Kiran Siddiqui
wrote:

>  hi have to parse a very complex dumps(whatever it is), i have done the
> parsing thruogh python.since the parsed data is very huge in amount, i have
> to feed it in the database (SQL), I have also done this... now the thing is
> i have to compare the data now present in the sql.
>
>
>
> in actual i have to compare the data of 1st dump with the data of the 2nd
> dump. the both dump have the same fields(attributes) but the values of
> their field may be change... so i have to detect this change.. for this i
> have to do the comparison...
>
>
>
> i.e, let i have a tableA ,its 1st row carry the data of dump1 and then on
> the 2nd day the data comes from dump2 go into the next row of tableA. and i
> have to compare both rows.
>
>
>
>  but i dont have the idea how to do this all using python as my front end.
>
>
>
> plz pl anyone help me:(
>
>
>
> --
> See all the ways you can stay connected to friends and 
> family
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to get the path of a module (myself) ?

2009-06-02 Thread Vlastimil Brom
2009/6/2 Stef Mientki :
...
> and the files generated by Py2Exe, don't work at all.
>
> Through this discussion, I discovered another problem,
> because __file__ isn't the current file,
> I can't run 1 module(file) from another module (file) .
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

There are already  answers regarding other more topical issues with
the initial problem; but just in case the main problem would be the
use of __file__ ...
It seems, that the exe files generated from py2exe don't recognise
this variable;
sometimes I used code like

try:
__file__
except NameError: # py2exe
__file__ = sys.path[0]

cf. e.g. http://mail.python.org/pipermail/python-list/2001-May/085384.html


I'm not sure, whether there are any drawbacks, but it works in the
respective context (accessing text and image files in parallel
directories).

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


Seach for encrypted socket wrapper

2009-06-02 Thread Hans Müller

Hello experts,

I'm looking for secure way to pass messages from a python program to a 
c-library in both ways.

This scenario is given:

display client  Calculation module in 
COBOL (yes, big, old but it works well)
(python, wxpython)  <- Network connection ->  C-Lib beeing called from 
COBOL to communicaty with
display client

The network connection should be encrypted. And fail save.
Has someone an idea what to use ?

I have had a short look on xml rpc which can run over a https server but this 
seems quite fat.
Better ideas ?!
Importand is also that the C-Lib on the cobol side should be coded as simple as 
possible.
Platforms: Windows, *ix

Thanks a lot.

Hans


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


Re: python 2.6 packages in python 3.0

2009-06-02 Thread Terry Reedy

Chris Rebert wrote:

On Tue, Jun 2, 2009 at 12:51 AM, ssd  wrote:

Hi,

I usually works with packages like pyserial, numpy, mathplotlib,pyUSB, etc..

When is planned that these packages are supported in Python 3.0?


That would depend on the individual packages and their maintainers.
Check their respective websites. There is not, as of yet, any
concerted/coordinated effort to port third-party libraries to 3.0.


That is more likely to happen after 3.1 final is released in a month or 
less.



Seen this i would say that is not recommendable to use Python 3.0 at the
moment? most of 2.6 packages are not available, not working in python 3.0.


If you need the packages, then 3.0 is not for you.


Yes, that's basically the state of things at the moment. We're in a
transitional phase while people port everything to Python 3.0 and/or
wait for the libraries they require to be ported to 3.0.


I expect people to port directly to 3.1 and not worry about whether 
there are minor incompatibilities with 3.0.


tjr

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


Re: Challenge supporting custom deepcopy with inheritance

2009-06-02 Thread Lie Ryan
Gabriel Genellina wrote:
> En Mon, 01 Jun 2009 14:19:19 -0300, Michael H. Goldwasser
>  escribió:
> 
>>   I can examine the inherited slots to see which special methods are
>>   there, and to implement my own __deepcopy__ accordingly. But to do
>>   so well seems to essentially require reimplementing the complicated
>>   logic of the copy.deepcopy function.  That is, if my new class is
>>   the first to be implementing an explicit __deepcopy__ function, I
>>   seem to have no easy way to invoke the inherited version of
>>   "deepcopy(self)".
> 
> Yes, that's a problem. But there is a workaround: since __deepcopy__ is
> searched *in the instance* (unlike many other __special__ methods, that
> are usually searched in the class itself) you can fool the copy logic
> into thinking there is no __deepcopy__ method defined, just by
> (temporarily) setting an instance attribute __deepcopy__ to None. (It's
> a hack, anyway)

I've never really used pickle before but maybe you could try pickling
then unpickling? It is a hack, but for some objects that does not have
__deepcopy__ it might be sufficient.

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


Re: Is there any module for sea tides?

2009-06-02 Thread Roy Smith
In article 
,
 alex23  wrote:

> "alejandro"  wrote:
> > I found some in C but could not find in Python
> 
> The best I could find was a reference to some in-house code used by
> the US National Oceanoic & Atmospheric Association:
> 
>   http://tinyurl.com/mct9zz
> 
> You might be able to contact the email address at the bottom and
> inquire about the code.
> 
> Another alternative is to look into using the ctypes module to create
> bindings for the C libs you found...

This is really off-topic for a Python group, but...

http://www.flaterco.com/xtide/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why date do not construct from date?

2009-06-02 Thread Lie Ryan
Gabriel Genellina wrote:
> En Tue, 02 Jun 2009 03:14:22 -0300, Chris Rebert 
> escribió:
> 
>> On Mon, Jun 1, 2009 at 10:25 PM, Alexandr N Zamaraev
>>  wrote:
> 
>> import datetime as dt
>> d = dt.date(2009, 10, 15)
>> dt.date(d)
>>> Traceback (most recent call last):
>>>  File "", line 1, in 
>>> TypeError: function takes exactly 3 arguments (1 given)
> 
>>> Why int form int, str from str, Decumal from Decumal can construct
>>> bat date from date not?
>>
>> Probably because the function signatures would be so different. str(),
>> int(), etc *always* take *exactly one* argument -- the object to
>> convert. In contrast, date() takes several integers corresponding to
>> the year, month, and day. Adding a second signature to it that took
>> exactly one argument (of type `date`) and copied it would be
>> significantly different from its other signature; in idiomatic Python,
>> one would typically make a separate, new function for this drastically
>> different signature.
> 
> That doesn't convince me. It's not very consistent along the various
> types: int("3ab0",16) is rather different than int(3.2) but they're the
> same function...

Strictly speaking int("3ab0",16) does not create an int from an int,
instead it creates an int from a string.

Maybe you want to say int(3) -> 3 ?

>> However, the `date` type is immutable, so there's no reason at all to
>> try and copy a new instance from an existing one anyway, thus a
>> single-argument copy-constructor is completely unnecessary, hence why
>> there isn't one.
> 
> Isn't the same for all other examples (int, float, str, Decimal...)?
> They're all immutable types, and some have several and rather different
> constructor signatures:

int(ob), float(ob), and str(ob) are type casting (strictly speaking it
is not a type casting, but you get the idea); while date() is a
constructor for the date object. Strictly speaking int(ob), float(ob),
and str(ob) merely calls the special ob.__int__, ob.__float__, and
ob.__str__. These special functions are there to convert the current
object into int, float, or str wherever defined. It just happens that
calling int.__int__, float.__float__, and str.__str__ just returns
themselves.

For Decimal, (I think) it is as a symmetry to float since Decimal is
intended to be used whenever IEEE 764 behavior does not suit you.
-- 
http://mail.python.org/mailman/listinfo/python-list


do replacement evenly

2009-06-02 Thread oyster
I have some strings, and I want to write them into a text files, one
string one line
but there is a requirement: every line has a max length of a certain
number(for example, 10), so I have to replace extra SPACE*3 with
SPACE*2, at the same time, I want to make the string looks good, so,
for "I am123456line123456three"(to show the SPACE clearly, I type it
with a number), the first time, I replace the first SPACE, and get "I
am23456line123456three", then I must replace at the second SPACE
block, so I get  "I am23456line23456three", and so on, if no SPACE*3
is found, I have to aString.replace(SPACE*2, SPACE).
I hope I have stated my case clear.

Then the question is, is there a nice solution?

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


Re: Why date do not construct from date?

2009-06-02 Thread Lie Ryan
Lie Ryan wrote:
> Gabriel Genellina wrote:
>> En Tue, 02 Jun 2009 03:14:22 -0300, Chris Rebert 
>> escribió:
>>
>>> On Mon, Jun 1, 2009 at 10:25 PM, Alexandr N Zamaraev
>>>  wrote:
>>> import datetime as dt
>>> d = dt.date(2009, 10, 15)
>>> dt.date(d)
 Traceback (most recent call last):
  File "", line 1, in 
 TypeError: function takes exactly 3 arguments (1 given)
 Why int form int, str from str, Decumal from Decumal can construct
 bat date from date not?
>>> Probably because the function signatures would be so different. str(),
>>> int(), etc *always* take *exactly one* argument -- the object to
>>> convert. In contrast, date() takes several integers corresponding to
>>> the year, month, and day. Adding a second signature to it that took
>>> exactly one argument (of type `date`) and copied it would be
>>> significantly different from its other signature; in idiomatic Python,
>>> one would typically make a separate, new function for this drastically
>>> different signature.
>> That doesn't convince me. It's not very consistent along the various
>> types: int("3ab0",16) is rather different than int(3.2) but they're the
>> same function...
> 
> Strictly speaking int("3ab0",16) does not create an int from an int,
> instead it creates an int from a string.
> 
> Maybe you want to say int(3) -> 3 ?
> 
>>> However, the `date` type is immutable, so there's no reason at all to
>>> try and copy a new instance from an existing one anyway, thus a
>>> single-argument copy-constructor is completely unnecessary, hence why
>>> there isn't one.
>> Isn't the same for all other examples (int, float, str, Decimal...)?
>> They're all immutable types, and some have several and rather different
>> constructor signatures:
> 
> int(ob), float(ob), and str(ob) are type casting (strictly speaking it
> is not a type casting, but you get the idea); while date() is a
> constructor for the date object. Strictly speaking int(ob), float(ob),
> and str(ob) merely calls the special ob.__int__, ob.__float__, and
> ob.__str__. These special functions are there to convert the current
> object into int, float, or str wherever defined. It just happens that
> calling int.__int__, float.__float__, and str.__str__ just returns
> themselves.
> 
> For Decimal, (I think) it is as a symmetry to float since Decimal is
> intended to be used whenever IEEE 764 behavior does not suit you.

In fact, the doc of int and float says "Convert a string or number to an
integer, if possible" and "Convert a string or number to a floating
point number, if possible" respectively. There is no mention that they
are constructors at all...

While the doc for str says "Return a nice string representation of the
object." the argument still holds since the "nice string representation"
for a string is the string itself...

Decimal is the rotten apple here since it just mimics float(). But that
is why Decimal is in separate module and there is no decimal() built-in.
Classes in modules are free to do anything they want to do... including
mimicking float() or deciding not to accept its own self as a valid
initializer.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do replacement evenly

2009-06-02 Thread Iain King
On Jun 2, 12:10 pm, oyster  wrote:
> I have some strings, and I want to write them into a text files, one
> string one line
> but there is a requirement: every line has a max length of a certain
> number(for example, 10), so I have to replace extra SPACE*3 with
> SPACE*2, at the same time, I want to make the string looks good, so,
> for "I am123456line123456three"(to show the SPACE clearly, I type it
> with a number), the first time, I replace the first SPACE, and get "I
> am23456line123456three", then I must replace at the second SPACE
> block, so I get  "I am23456line23456three", and so on, if no SPACE*3
> is found, I have to aString.replace(SPACE*2, SPACE).
> I hope I have stated my case clear.
>
> Then the question is, is there a nice solution?
>
> thanx

Assuming you want to crush all spaces into single space, you can:

while "  " in s:
s = s.replace("  ", " ")

readable but not efficient.  Better:

s = " ".join((x for x in s.split(" ") if x))

Note that this will strip leading and trailing spaces.

Or you can use regexps:

import re
s = re.sub(" {2,}", " ", s)


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


Re: What text editor is everyone using for Python

2009-06-02 Thread Christopher
On May 25, 1:35 pm, LittleGrasshopper  wrote:
> With so many choices, I was wondering what editor is the one you
> prefer when coding Python, and why. I normally use vi, and just got
> into Python, so I am looking for suitable syntax files for it, and
> extra utilities. I dabbled with emacs at some point, but couldn't get
> through the key bindings for commands. I've never tried emacs with vi
> keybindings (I forgot the name of it) but I've been tempted.
>
> So what do you guys use, and why? Hopefully we can keep this civil.

I use Eclipse with PyDev for serious projects.  However, when that is
too heavy or not available I use:

1) nano over ssh with syntax highlighting for python turned on
2) notepad++ on standalone Windows systems where I need to do quick
edits or fixes.

I used to use Crimson Editor, but it is not being developed anymore,
and notepad++ does everything crimson used to do and more.

-={C}=-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem building 64-bit python 2.6.2 on Solaris 10

2009-06-02 Thread John Center
Hi Martin,

I was able to compile ctypes with gcc4sparc without many changes to
the CFLAGS, etc.  I had another weird error, but upgrading to the
latest gcc4sparc fixed it.  One thing I'm not clear about is how
extensions are built.  I noticed that my CFLAGS are not being passed
to gcc when building the extensions, so some of them are failing to
find the correct includes & libraries.  How does one pass these flags?

Thanks.

-John


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


Re: do replacement evenly

2009-06-02 Thread Mike Kazantsev
On Tue, 2 Jun 2009 19:10:18 +0800
oyster  wrote:

> I have some strings, and I want to write them into a text files, one
> string one line
> but there is a requirement: every line has a max length of a certain
> number(for example, 10), so I have to replace extra SPACE*3 with
> SPACE*2, at the same time, I want to make the string looks good, so,
> for "I am123456line123456three"(to show the SPACE clearly, I type it
> with a number), the first time, I replace the first SPACE, and get "I
> am23456line123456three", then I must replace at the second SPACE
> block, so I get  "I am23456line23456three", and so on, if no SPACE*3
> is found, I have to aString.replace(SPACE*2, SPACE).
> I hope I have stated my case clear.
> 
> Then the question is, is there a nice solution?

Not so nice, but it should be faster than whole lot of string
manipulations, especially on longer lines:

  len_line = 55
  line = 'Thats  a whole line   of  some utter  nonsense ;)'

  words = line.split()
  count_space = len_line - len(''.join(words))
  count_span = len(words) - 1
  span_min = (count_space // count_span) * ' '
  count_span_max = count_space - (count_span * len(span_min))

  line = buffer(words[0])
  for word in words[1:]:
if count_span_max:
  count_span_max -= 1
  line += span_min + ' '
else: line += span_min
line += word

  print '%d chars: %r'%(len(line), line)

-- 
Mike Kazantsev // fraggod.net


signature.asc
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do replacement evenly

2009-06-02 Thread oyster
here is what I get
[code]
import re
reSplitObj=re.compile('([ \t]*)|([^ \t]*)')
def evenReplace(aStr, length):
aStr=aStr.rstrip()
tmp=reSplitObj.split(aStr)
tmp=[i for i in tmp if i not in ['', None]]
lenStr=[[0, len(i)][i.strip()!=''] for i in tmp]
lenSpc=[[0, len(i)][i.strip()==''] for i in tmp]
while sum(lenStr)+sum(lenSpc)>length:
if sum(lenSpc):
lenSpc[lenSpc.index(max(lenSpc))]-=1
else:
break
newSpc=[' '*i for i in lenSpc]
_=[]
for i in range(len(tmp)):
item=tmp[i]
if item.strip()!='':
_.append(item+newSpc[i])
else:
_.append(newSpc[i])

return ''.join(_)

if __name__=='__main__':
a='hello world'
b= evenReplace(a, 5)
print 'a="%s", len=%0i' %(a, len(a))
print 'b="%s", len=%0i' %(b, len(b))
print

a='helloworld   yeaheventeven '
b= evenReplace(a, 27)
print 'a="%s", len=%0i' %(a, len(a))
print 'b="%s", len=%0i' %(b, len(b))
print

[/code]


2009/6/2 oyster :
> I have some strings, and I want to write them into a text files, one
> string one line
> but there is a requirement: every line has a max length of a certain
> number(for example, 10), so I have to replace extra SPACE*3 with
> SPACE*2, at the same time, I want to make the string looks good, so,
> for "I am123456line123456three"(to show the SPACE clearly, I type it
> with a number), the first time, I replace the first SPACE, and get "I
> am23456line123456three", then I must replace at the second SPACE
> block, so I get  "I am23456line23456three", and so on, if no SPACE*3
> is found, I have to aString.replace(SPACE*2, SPACE).
> I hope I have stated my case clear.
>
> Then the question is, is there a nice solution?
>
> thanx
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Challenge supporting custom deepcopy with inheritance

2009-06-02 Thread Scott David Daniels

Michael H. Goldwasser wrote:
On Monday June 1, 2009, Scott David Daniels wrote: 


   Michael H. Goldwasser wrote:
   >     I'll accept the "small price for flexibility" that you
   >   note, if necessary. However, I still desire a cleaner solution.
   
   You seem to think that "deepcopy" is a well-defined concept. 


  It is clear from my original statement of the question that there is
  a need for classes to be able to customize their own semantics for
  supporting the deepcopy function.  That is why the deepcopy function
  looks for a __deepcopy__ method within a class as a hook.

  My concern involves the challenge of providing a valid
  implementation for __deepcopy__ at one level of inheritance without
  being overly dependent on the internal mechanism used by ancestor
  classes in supporting deepcopy.  I don't see how your comments
  address that question.


I only meant to say, if you are looking for something neater,
consider whether there is such a thing.  Issues with deepcopy
may be (and I suspect are) inherently messy.  Further,
inheritance usually provides (in practice) a "built from"
relationship, not an "is a" relationship.  "Liskov
Substitutability," is a design goal, honored except in corner
cases and where inconvenient.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


pyPgSql there is already a transaction in progres

2009-06-02 Thread someone
Hi,
I'm using pyPgSQL for accessing Postgres and do some update and select
queries.
and getting WARNING:  there is already a transaction in progress if I
run runUpdate more than once.
So, what happens is following:

1. SELECT address FROM address WHERE LOWER(address) = LOWER(%s); --
__existRecord
2. BEGIN;DELETE FROM failed WHERE uquery = %s;COMMIT; -- __delQuery
3. SELECT address FROM address WHERE LOWER(address) = LOWER(%s); --
again __existRecord
and here I'm getting the warning.

Can anyone explain me please what the problem is? I do select, then
delete transaction and then select again which doesn't work

Regards, Pet








class Bla:

def __init__:
pass

def runUpdate(self, number=5):
data = {}
data = self.__getUpdateItems(number)
for row in data:
try:
if self.__existRecord(row['q']):
self.__delQuery(row['q'])
except Exception, e:
print "Exception", e


def __delQuery(self, name):
query = """
BEGIN;DELETE FROM failed WHERE uquery = %s;COMMIT;
"""
try:
self.db.execute(query, name)
except Exception, e:
print "Exception: ", e
return True

def __existRecord(self, search):
query = """
SELECT address FROM address WHERE LOWER(address) = LOWER
(%s);
"""
try:
self.db.execute(query, search)
except Exception, e:
print "Exception: ", e
return self.db.fetchall()

def __getUpdateItems(self,number=5):
values = [number]
query = """
SELECT * FROM failed
WHERE id IS NULL
ORDER BY up DESC
LIMIT %s;
"""
result = []
try:
self.db.execute(query, *values)
result = self.db.fetchall()
except Exception, e:
print "Exception getUpdateItems: ", e
   return result
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Seach for encrypted socket wrapper

2009-06-02 Thread garabik-news-2005-05
Hans Müller  wrote:
> Hello experts,
> 
> I'm looking for secure way to pass messages from a python program to a 
> c-library in both ways.
> 
> This scenario is given:
> 
> display client  Calculation module in 
> COBOL (yes, big, old but it works well)
> (python, wxpython)  <- Network connection ->C-Lib beeing called 
> from COBOL to communicaty with
>display client
> 
> The network connection should be encrypted. And fail save.
> Has someone an idea what to use ?
> 
> I have had a short look on xml rpc which can run over a https server but this 
> seems quite fat.
> Better ideas ?!

Standard TCP connection, forwarded via stunnel or ssh, Should be no brainer if 
the
COBOL side is running on a reasonably modern unix.


-- 
 ---
| Radovan Garabík http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__garabik @ kassiopeia.juls.savba.sk |
 ---
Antivirus alert: file .signature infected by signature virus.
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: do replacement evenly

2009-06-02 Thread Scott David Daniels

oyster wrote:

I have some strings, and I want to write them into a text files, one
string one line
but there is a requirement: every line has a max length of a certain
number ... 


If you are doing this to fill and justify text, I seem to remember
a research result stating that filled text (with smooth left and right
margins) works well for proportional fonts, but decreases readability
for fixed pitch fonts, where ragged right (or ragged left) works better.
Sadly, I have no idea where I read that as it is only in the recesses
of my somewhat addled brain.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: pyPgSql there is already a transaction in progres

2009-06-02 Thread Paul Boddie
On 2 Jun, 15:32, someone  wrote:
> Hi,
> I'm using pyPgSQL for accessing Postgres and do some update and select
> queries.
> and getting WARNING:  there is already a transaction in progress if I
> run runUpdate more than once.

I think this is because you're using explicit transaction statements
amongst the SQL statements you're sending to the database system,
whereas pyPgSQL probably starts transactions on your behalf if you've
not enabled autocommit.

> So, what happens is following:
>
> 1. SELECT address FROM address WHERE LOWER(address) = LOWER(%s); --
> __existRecord
> 2. BEGIN;DELETE FROM failed WHERE uquery = %s;COMMIT; -- __delQuery
> 3. SELECT address FROM address WHERE LOWER(address) = LOWER(%s); --
> again __existRecord
> and here I'm getting the warning.

Here, statement #3 may well start a new transaction - a convenience
introduced by pyPgSQL in order to provide DB-API compliance and
automatic transactions - and when __delQuery is invoked, PostgreSQL
will complain that you are trying to start another transaction.

Really, you should use the commit method on the cursor object
(self.db, I presume) and the rollback method when you want to start a
new transaction without changing anything. Alternatively, you could
set autocommit to true on the connection object and be sure to always
use transaction statements (BEGIN, COMMIT, ROLLBACK) where
appropriate.

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


Re: what I would like python.el to do (and maybe it does)

2009-06-02 Thread rustom
> But since i like to do it The Right Way, I would
> like to let the python-mode worry about this...
>
> Sorry if this is just a bunch of obvious thoughts to most of you.
>
> Regards,
> Giovanni

I dont see whats the problem.
Heres my attempt to show you my emacs windows using python-mode
(python.el never worked for me)
## Window 1 file foo.py (python mode)
x = 1

y = 2

## Window 2 python interpreter
>>>


Goto the python file (foo.py)
Select the x=1 line
C-c | (which is py-execute-region)
Goto python interpreter window
>>> x
1
>>> y
...
NameError: y not defined

What more/less/else do you want?

Are you using python-mode.el or python.el?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: do replacement evenly

2009-06-02 Thread python
Here's how we normalize whitespace in multiline blocks of text. Perhaps
you can adapt this routine to your needs? Watch for line wrap.

# clean up duplicate whitespace, leading/trailing whitespace, triple
CRLF's
def fixwhitespace( text ):
output = []
lastLine = ''

# split text into list of individual lines
lines = text.strip().splitlines()
for line in lines:
# remove leading, trailing, and duplicate whitespace within a 
line
line = ' '.join( line.split( None ) )

# ignore multiple blank lines
if not line and not lastLine:
pass
else:
output.append( line )
lastLine = line

return '\n'.join( output )

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


Re: pyPgSql there is already a transaction in progres

2009-06-02 Thread Tep
On Jun 2, 3:58 pm, Paul Boddie  wrote:
> On 2 Jun, 15:32, someone  wrote:
>
> > Hi,
> > I'm using pyPgSQL for accessing Postgres and do some update and select
> > queries.
> > and getting WARNING:  there is already a transaction in progress if I
> > run runUpdate more than once.
>
> I think this is because you're using explicit transaction statements
> amongst the SQL statements you're sending to the database system,
> whereas pyPgSQL probably starts transactions on your behalf if you've
> not enabled autocommit.
>
> > So, what happens is following:
>
> > 1. SELECT address FROM address WHERE LOWER(address) = LOWER(%s); --
> > __existRecord
> > 2. BEGIN;DELETE FROM failed WHERE uquery = %s;COMMIT; -- __delQuery
> > 3. SELECT address FROM address WHERE LOWER(address) = LOWER(%s); --
> > again __existRecord
> > and here I'm getting the warning.
>
> Here, statement #3 may well start a new transaction - a convenience
> introduced by pyPgSQL in order to provide DB-API compliance and
> automatic transactions - and when __delQuery is invoked, PostgreSQL
> will complain that you are trying to start another transaction.

Ok, that make sense

>
> Really, you should use the commit method on the cursor object

You mean connection object, do you?

I've tried that, but forgotten to remove BEGIN;COMMIT; statements from
my queries
Now, I do commit on connection object after _each_ query and it seems
to work :)

> (self.db, I presume) and the rollback method when you want to start a
> new transaction without changing anything. Alternatively, you could
> set autocommit to true on the connection object and be sure to always
> use transaction statements (BEGIN, COMMIT, ROLLBACK) where
> appropriate.

In that way it works too, which means, everything is clear now

Thanks for help!

>
> Paul

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


Re: Seach for encrypted socket wrapper

2009-06-02 Thread bobicanprogram
On Jun 2, 5:28 am, Hans Müller  wrote:
> Hello experts,
>
> I'm looking for secure way to pass messages from a python program to a 
> c-library in both ways.
>
> This scenario is given:
>
> display client  Calculation module in 
> COBOL (yes, big, old but it works well)
> (python, wxpython)  <- Network connection ->  C-Lib beeing called from 
> COBOL to communicaty with
> display client
>
> The network connection should be encrypted. And fail save.
> Has someone an idea what to use ?
>
> I have had a short look on xml rpc which can run over a https server but this 
> seems quite fat.
> Better ideas ?!
> Importand is also that the C-Lib on the cobol side should be coded as simple 
> as possible.
> Platforms: Windows, *ix
>
> Thanks a lot.
>
> Hans


The SIMPL toolkit is quite lightweight (http://www.icanprogram.com/
simpl).  It can be used to join a Python program to a C program.
However,  SIMPL messages are treated as blocks of bytes from the
prespective of the toolkit.It should be quite straightforward to
graft an encription layer above this to do what you want.

If you want some "hello world" level Python-SIMPL examples you can
look here:  http://www.icanprogram.com/06py/main.html

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


Re: hash and __eq__

2009-06-02 Thread Aahz
In article <003e1491$0$9723$c3e8...@news.astraweb.com>,
Steven D'Aprano   wrote:
>On Sun, 31 May 2009 07:24:09 +0100, Arnaud Delobelle wrote:
>>
>> AFAIK, 'complexity' means 'worst case complexity' unless otherwise
>> stated.
>
>No, it means "average or typical case" unless otherwise specified. 
>Consult almost any comp sci text book and you'll see hash tables with 
>chaining (like Python dicts) described as O(1) rather than O(N), 
>Quicksort as O(N log N) instead of O(N**2), and similar. If the default 
>was "worst case unless otherwise specified", then Quicksort would be 
>called "Slower than Bubblesort Sort".
>
>(Both are O(N**2), but Quicksort does more work.)
>
>Here's a quote on-line:
>
>"You should be clear about which cases big-oh notation describes. By 
>default it usually refers to the average case, using random data. 
>However, the characteristics for best, worst, and average cases can be 
>very different..."
>
>http://leepoint.net/notes-java/algorithms/big-oh/bigoh.html

When talking about big-oh, I prefer to define "worst-case" as "real world
likely worst-case" -- for example, feeding an already-sorted list to
Quicksort.  However, the kind of worst-case that causes a dict to have
O(N) behavior I would call "pathological case".  I generally try to
define big-oh in terms of what I call worst-case, because I think it's
important to keep track of where your algorithm is likely to run into
problems, but I don't think it's worth the effort in most cases to worry
about pathological cases.

In the case of dicts, it's important to remember that pathological cases
are far more likely to arise from poorly designed hashable user classes
than from data problems per se; Python's hashing of built-in types has
almost twenty years of tuning.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

my-python-code-runs-5x-faster-this-month-thanks-to-dumping-$2K-
on-a-new-machine-ly y'rs  - tim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pyPgSql there is already a transaction in progres

2009-06-02 Thread Paul Boddie
On 2 Jun, 16:49, Tep  wrote:
> On Jun 2, 3:58 pm, Paul Boddie  wrote:
> > Really, you should use the commit method on the cursor object
>
> You mean connection object, do you?

Yes, I meant the connection object. :-)

> I've tried that, but forgotten to remove BEGIN;COMMIT; statements from
> my queries
> Now, I do commit on connection object after _each_ query and it seems
> to work :)

You should probably use rollback in order to close transactions just
in case you've issued a statement which changes the database. Think of
it as kind of a synchronisation operation.

[...]

> In that way it works too, which means, everything is clear now

Great!

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


Re: Creating a Google Code project for GSoC

2009-06-02 Thread Robert Kern

On 2009-06-01 18:54, Eric Pruitt wrote:

Hello everyone,

I am a student working on GSoC 2009 for PSF. My proposal involves making
changes to the subprocess module and subprocess.Popen. I wish to create
a Google Code project to host my changes so that I can receive feedback
from the community. Some of the code I have incorporated falls under an
MIT license. Python's license is not GPL but is GPL compatible. What
license should the Google Code project fall under? MIT, GPL or something
else?


You should talk to your mentor and the PSF GSoC coordinator, but generally code 
intended for inclusion in Python itself needs to be licensed under the Apache 
License v2.0 or the Academic Free License v2.1:


  http://www.python.org/psf/contrib/

You will also need to sign a contributor agreement. But talk to your mentor.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: how to get the path of a module (myself) ?

2009-06-02 Thread Stef Mientki



The same rule applies for your modules. As a general rule, NEVER say:

execfile('mymodule.py')

instead do:

import mymodule
mymodule.some_function()
mymodule.another_function()


(There are exceptions, but if you need to ask what they are, you're not 
ready to learn them! *wink*)



  

hi Steven,
maybe you hit the nail right on his head.
But I finally want to release my program, with or without proper 
imports, but working correctly.

And I'll leave the "import details" to some other guru.

thanks,
Stef

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


Safe to import __builtin__ ?

2009-06-02 Thread mrstevegross
Is it generally safe to explicitly import __builtin__ in python? That
is, my code reads like this:

=== foo.py ===
import __builtin__
...
print __builtin__.type('a')
=== EOF ===

It seems like it should be a safe import, but I just want to make
sure.

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


Re: how to get the path of a module (myself) ?

2009-06-02 Thread Robert Kern

On 2009-06-02 14:24, Stef Mientki wrote:



The same rule applies for your modules. As a general rule, NEVER say:

execfile('mymodule.py')

instead do:

import mymodule
mymodule.some_function()
mymodule.another_function()


(There are exceptions, but if you need to ask what they are, you're
not ready to learn them! *wink*)



hi Steven,
maybe you hit the nail right on his head.
But I finally want to release my program, with or without proper
imports, but working correctly.
And I'll leave the "import details" to some other guru.


Getting the "import details" right is how you get it to work correctly.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Safe to import __builtin__ ?

2009-06-02 Thread MRAB

mrstevegross wrote:

Is it generally safe to explicitly import __builtin__ in python? That
is, my code reads like this:

=== foo.py ===
import __builtin__
...
print __builtin__.type('a')
=== EOF ===

It seems like it should be a safe import, but I just want to make
sure.


Why do you want to import it?

See http://docs.python.org/library/__builtin__.html
--
http://mail.python.org/mailman/listinfo/python-list


Using C++ and ctypes together: a vast conspiracy? ;)

2009-06-02 Thread Joseph Garvin
So I was curious whether it's possible to use the ctypes module with
C++ and if so how difficult it is. I figure in principal it's possible
if ctypes knows about each compiler's name mangling scheme. So I
searched for "ctypes c++" on Google.

The third link will be "Using ctypes to Wrap C++ Libraries". If you
follow the link, it's broken. If you view the cache of the link, it's
someone pointing to another blog, retrograde-orbit.blogspot.com,
saying they discovered a way to do it easily. If you follow that link,
you get taken a page does not exist error.

Clearly there's some way to use ctypes with C++ and there's a vast
conspiracy preventing it from reaching the masses ;) What's even
stranger is that this link, despite being broken, has seemingly been
near the top of google's results for these terms for a couple weeks
(that's when I last tried), as if there were some underground group of
rebels trying to hint the truth to us... ;)

More seriously -- how difficult is it to use ctypes instead of saying,
boost::python, and why isn't this in a FAQ somewhere? ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using C++ and ctypes together: a vast conspiracy? ;)

2009-06-02 Thread Diez B. Roggisch

Joseph Garvin schrieb:

So I was curious whether it's possible to use the ctypes module with
C++ and if so how difficult it is. I figure in principal it's possible
if ctypes knows about each compiler's name mangling scheme. So I
searched for "ctypes c++" on Google.

The third link will be "Using ctypes to Wrap C++ Libraries". If you
follow the link, it's broken. If you view the cache of the link, it's
someone pointing to another blog, retrograde-orbit.blogspot.com,
saying they discovered a way to do it easily. If you follow that link,
you get taken a page does not exist error.

Clearly there's some way to use ctypes with C++ and there's a vast
conspiracy preventing it from reaching the masses ;) What's even
stranger is that this link, despite being broken, has seemingly been
near the top of google's results for these terms for a couple weeks
(that's when I last tried), as if there were some underground group of
rebels trying to hint the truth to us... ;)

More seriously -- how difficult is it to use ctypes instead of saying,
boost::python, and why isn't this in a FAQ somewhere? ;)


Because it's much more needed than name-mangling. Name mangling is 
(amongst other things) one thing to prevent 
C++-inter-compiler-interoperability which results from differing C++ ABIs.


I'm not an expert on this, but AFAIK no common ABI exists, especially 
not amongst VC++ & G++. Which means that to work for C++, ctypes would 
need to know about the internals of both compilers, potentially in 
several versions, and possibly without prior notice to changes.


Instead of dealing with this truly daunting task, tools such as SIP and 
SWIG or boost::python deal with this by utilizing the one tool that 
really knows about the ABI in use - the compiler itself.


So while I'd loved to be proven wrong, I fear your curiosity won't be 
satisfied - or at least not in the positive sense you certainly envisioned.


Diez





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


Re: Challenge supporting custom deepcopy with inheritance

2009-06-02 Thread Gabriel Genellina

En Tue, 02 Jun 2009 07:34:43 -0300, Lie Ryan  escribió:


Gabriel Genellina wrote:

En Mon, 01 Jun 2009 14:19:19 -0300, Michael H. Goldwasser
 escribió:


  I can examine the inherited slots to see which special methods are
  there, and to implement my own __deepcopy__ accordingly. But to do
  so well seems to essentially require reimplementing the complicated
  logic of the copy.deepcopy function.  That is, if my new class is
  the first to be implementing an explicit __deepcopy__ function, I
  seem to have no easy way to invoke the inherited version of
  "deepcopy(self)".


Yes, that's a problem. But there is a workaround: since __deepcopy__ is
searched *in the instance* (unlike many other __special__ methods, that
are usually searched in the class itself) you can fool the copy logic
into thinking there is no __deepcopy__ method defined, just by
(temporarily) setting an instance attribute __deepcopy__ to None. (It's
a hack, anyway)


I've never really used pickle before but maybe you could try pickling
then unpickling? It is a hack, but for some objects that does not have
__deepcopy__ it might be sufficient.


deepcopy essencially does that, without the intermediate storage.
The problem is, how to customize deepcopy(something) in a derived class,  
if there is no way to call the inherited behavior from its base class.


--
Gabriel Genellina

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


Creating Mac OS X app

2009-06-02 Thread sh00le
Hi,
This is my first post here, hope this is the right group, and sorry
for my broken English.

So, let's start. I have created small PyQt application Simple Task
Timer (http://code.google.com/p/simpletasktimer/). Also I created
windows binary distro with py2exe, and Linux packages (.rpm and .deb).
I would like to have Mac OS X .app binary distro but I don't have Mac
OS, and I can't install Mac OS as guest on Virtual Box.

Now, I'm searching for some volunteers with Mac OS who would like to
test application on Mac OS, and (if it's possible) to create .app
binary for Simple Task Timer. Any help would be appreciated.

Tnx for reading.

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


Re: Safe to import __builtin__ ?

2009-06-02 Thread mrstevegross
> Why do you want to import it?
>
> Seehttp://docs.python.org/library/__builtin__.html

I'm using a weird python environment that overloads a few builtin
functions. In order to run them, I need to explicitly invoke
"__builtin__.foo()" to make sure I get the real builtin version, not
the overloaded one.

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


Re: py2app and OpenGL, "No module named util" in ctypes

2009-06-02 Thread trhaynes
On May 28, 6:28 pm, Carl Banks  wrote:
> On May 28, 11:06 am, trhaynes  wrote:
>
>
>
> > I'm trying to use py2app to package an OpenGL app, so first I tried to
> > build the example here
>
> >http://svn.pythonmac.org/py2app/py2app/trunk/examples/PyOpenGL/
>
> > and I get the error:
>
> > >  File 
> > > "/opt/local/lib/python2.5/site-packages/PyOpenGL-3.0.0c1-py2.5.egg/OpenGL/platform/darwin.py",
> > >  line 24, in 
> > >    import ctypes, ctypes.util
> > >ImportError: No module named util
> > >2009-05-28 13:55:06.819 lesson5[19965:10b] lesson5 Error
> > >2009-05-28 13:55:06.821 lesson5[19965:10b] lesson5 Error
> > >An unexpected error has occurred during execution of the main script
>
> > >ImportError: No module named util
>
> > But when I open up my python interactive interpreter and "import
> > ctypes.util", it works fine (using lesson5.app/Contents/MacOS/python,
> > too).
>
> > Thanks for the help.
>
> What has happened is that py2app didn't bundle ctypes.util with the
> app, because py2app failed to detect that it was imported for some
> reason.
>
> A typical workaround is to imported in maually in your main script to
> make it explicit to py2app that it should be packaged.
>
> A word of caution: PyOpenGL uses entry hooks and that can cause a lot
> of trouble for application builder utilities like py2exe and py2app.
> In fact, I decided to stop using PyOpenGL in my projects in large part
> because of that issue (I use my own OpenGL wrapper now).  It's
> possible py2app has learned to deal with entry hooks by now, but these
> days I refuse to use packages that require entry hooks so I wouldn't
> know.
>
> Carl Banks

Thanks all.  I had to add ctypes.util to the list of includes for it
to work.
-- 
http://mail.python.org/mailman/listinfo/python-list


Copying objects and multiple inheritance

2009-06-02 Thread Brian Allen Vanderburg II
What is the best way to copy an object that has multiple inheritance 
with the copy module.  Particularly, some of the instances in the 
hierarchy  use the __copy__ method to create a copy (because even for 
shallow copies they need some information  updated a little 
differently), so how can I make sure all the information is copied as it 
is supposed to be even for the base classes that have special requirements.


Brian Vanderburg II
--
http://mail.python.org/mailman/listinfo/python-list


Re: what is the biggest number that i can send to Wave_write.writeframes(data)

2009-06-02 Thread Rob Williscroft
'2+ wrote in news:mailman.1017.1243932401.8015.python-l...@python.org in 
comp.lang.python:

> would like to take advantage of the wave module
> found a good example here:
> http://www.python-forum.org/pythonforum/viewtopic.php?f=2&t=10644
> 
> hmm .. i don't get how to write a stereo .. i mean i can set nchannels
> .. but how do i actually take control of each ch individually?

Interleave the channels, one sample for the left then one sample 
for the right (or maybe its the other way around).

> and what's the range(in float) of the data i can set in

The range of a signed 16 bit int, -2**15 to 2**15 - 1.

> wav_file.writeframes(struct.pack('h', data))?

Example:

import wave
from StringIO import StringIO

out = StringIO()

AMPLITUDE = 2 ** 15

w = wave.open( out, "w" )
w.setnchannels( 2 )
w.setsampwidth( 2 ) #BYTES
w.setframerate( 22000 )

from array import array
import math

F = 261.626
F2 = F * (2 ** (5 / 12.))
ang = 0.0
ang2 = 0.0
delta = ( math.pi * 2 * F  ) / 22000.0
delta2 = ( math.pi * 2 * F2  ) / 22000.0

for cycle in xrange( 4 ):
  data = array( 'h' )
  for pos in xrange( 22000 ):
amp = AMPLITUDE * (pos / 22000.0)
amp2 = AMPLITUDE - amp
if cycle & 1:
  amp, amp2 = amp2, amp
  
data.append( int( ( amp * math.sin( ang ) ) ) )
data.append( int( ( amp2 * math.sin( ang2 ) ) ) )

ang += delta
ang2 += delta2
  
  w.writeframes( data.tostring() )
  
w.close()

sample = out.getvalue()
out.close()

#a wx player

import wx

app = wx.PySimpleApp()

class Frame( wx.Dialog ):
  def __init__( self, *args ):
wx.Dialog.__init__( self, *args )
b = wx.Button( self, -1, "Ok" )
b.Bind( wx.EVT_BUTTON, self.button )
  
  def button( self, event ):
self.sound = wx.SoundFromData( sample ) 
self.sound.Play( wx.SOUND_ASYNC )

frame = Frame( None )
frame.Show()

app.MainLoop()

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using C++ and ctypes together: a vast conspiracy? ;)

2009-06-02 Thread Nick Craig-Wood
Diez B. Roggisch  wrote:
>  Joseph Garvin schrieb:
> > So I was curious whether it's possible to use the ctypes module with
> > C++ and if so how difficult it is. I figure in principal it's possible
> > if ctypes knows about each compiler's name mangling scheme. So I
> > searched for "ctypes c++" on Google.
[snip]
> > More seriously -- how difficult is it to use ctypes instead of saying,
> > boost::python, and why isn't this in a FAQ somewhere? ;)
> 
>  Because it's much more needed than name-mangling. Name mangling is 
>  (amongst other things) one thing to prevent 
>  C++-inter-compiler-interoperability which results from differing C++ ABIs.
> 
>  I'm not an expert on this, but AFAIK no common ABI exists, especially 
>  not amongst VC++ & G++. Which means that to work for C++, ctypes would 
>  need to know about the internals of both compilers, potentially in 
>  several versions, and possibly without prior notice to changes.

Probably depends on how far you want to dig into C++.  I'm sure it
will work fine for simple function calls, passing classes as anonymous
pointers etc.  If you want to dig into virtual classes with multiple
bases or the STL then you are probably into the territory you
describe.

That said I've used C++ with ctypes loads of times, but I always wrap
the exported stuff in extern "C" { } blocks.

-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using C++ and ctypes together: a vast conspiracy? ;)

2009-06-02 Thread A. Cavallo
Mmmm, 
not really a conspiracy but it is not that trivial

In wrapping c++ you might find useful the commands nm with c++filt
although they work under linux there is the same pair for every platform 
(under windows I remember there is objdump): they should only you need to wrap 
a c++ library.

I've been wrapping in the past c++ using boost and it was trivial although I 
haven't tried enough to break it.

swig, in older versions, is really bad: I can't comment on newer versions but 
I'd have a look to the generated code before using it.

sip it looks quite difficult to use, but is well maintained.

If you have a moderate control on the library design the ctype is the best 
approach IMHO.

Regards,
Antonio



On Tuesday 02 June 2009 21:50:24 Joseph Garvin wrote:
> So I was curious whether it's possible to use the ctypes module with
> C++ and if so how difficult it is. I figure in principal it's possible
> if ctypes knows about each compiler's name mangling scheme. So I
> searched for "ctypes c++" on Google.
>
> The third link will be "Using ctypes to Wrap C++ Libraries". If you
> follow the link, it's broken. If you view the cache of the link, it's
> someone pointing to another blog, retrograde-orbit.blogspot.com,
> saying they discovered a way to do it easily. If you follow that link,
> you get taken a page does not exist error.
>
> Clearly there's some way to use ctypes with C++ and there's a vast
> conspiracy preventing it from reaching the masses ;) What's even
> stranger is that this link, despite being broken, has seemingly been
> near the top of google's results for these terms for a couple weeks
> (that's when I last tried), as if there were some underground group of
> rebels trying to hint the truth to us... ;)
>
> More seriously -- how difficult is it to use ctypes instead of saying,
> boost::python, and why isn't this in a FAQ somewhere? ;)

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


Re: how to get the path of a module (myself) ?

2009-06-02 Thread Stef Mientki

Robert Kern wrote:

On 2009-06-02 14:24, Stef Mientki wrote:



The same rule applies for your modules. As a general rule, NEVER say:

execfile('mymodule.py')

instead do:

import mymodule
mymodule.some_function()
mymodule.another_function()


(There are exceptions, but if you need to ask what they are, you're
not ready to learn them! *wink*)



hi Steven,
maybe you hit the nail right on his head.
But I finally want to release my program, with or without proper
imports, but working correctly.
And I'll leave the "import details" to some other guru.


Getting the "import details" right is how you get it to work correctly.


Sorry,
but I realy don't understand the difference between the documents on my 
desk and a python file in a subpath.

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


Re: Using C++ and ctypes together: a vast conspiracy? ;)

2009-06-02 Thread Sebastian Wiesner


> Diez B. Roggisch  wrote:
>>  Joseph Garvin schrieb:
>> > So I was curious whether it's possible to use the ctypes module with
>> > C++ and if so how difficult it is. I figure in principal it's possible
>> > if ctypes knows about each compiler's name mangling scheme. So I
>> > searched for "ctypes c++" on Google.
> [snip]
>> > More seriously -- how difficult is it to use ctypes instead of saying,
>> > boost::python, and why isn't this in a FAQ somewhere? ;)
>> 
>>  Because it's much more needed than name-mangling. Name mangling is
>>  (amongst other things) one thing to prevent
>>  C++-inter-compiler-interoperability which results from differing C++
>>  ABIs.
>> 
>>  I'm not an expert on this, but AFAIK no common ABI exists, especially
>>  not amongst VC++ & G++. Which means that to work for C++, ctypes would
>>  need to know about the internals of both compilers, potentially in
>>  several versions, and possibly without prior notice to changes.
> 
> Probably depends on how far you want to dig into C++.  I'm sure it
> will work fine for simple function calls, passing classes as anonymous
> pointers etc.  If you want to dig into virtual classes with multiple
> bases or the STL then you are probably into the territory you
> describe.

Name mangeling starts with namespaces, and namespaces are a thing often seen 
in well-designed C++-libraries.  So even a simple C++-function call could 
become rather difficult to do using ctypes ...

> That said I've used C++ with ctypes loads of times, but I always wrap
> the exported stuff in extern "C" { } blocks.

No wonder, you have never actually used C++ with C types.  An extern "C" 
clause tells the compiler to generate C functions (more precisely, functions 
that conform to the C ABI conventions), so effectively you're calling into 
C, not into C++.

-- 
Freedom is always the freedom of dissenters.
  (Rosa Luxemburg)

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


Re: how to get the path of a module (myself) ?

2009-06-02 Thread Robert Kern

On 2009-06-02 18:00, Stef Mientki wrote:

Robert Kern wrote:

On 2009-06-02 14:24, Stef Mientki wrote:



The same rule applies for your modules. As a general rule, NEVER say:

execfile('mymodule.py')

instead do:

import mymodule
mymodule.some_function()
mymodule.another_function()


(There are exceptions, but if you need to ask what they are, you're
not ready to learn them! *wink*)



hi Steven,
maybe you hit the nail right on his head.
But I finally want to release my program, with or without proper
imports, but working correctly.
And I'll leave the "import details" to some other guru.


Getting the "import details" right is how you get it to work correctly.


Sorry,
but I realy don't understand the difference between the documents on my
desk and a python file in a subpath.


I really don't understand what relevance you think that has to writing correct 
Python programs. Yes, Python files are, indeed, files. But the correct way to 
write Python programs in multiple Python files is to organize them into modules 
and packages and use Python's import mechanism to make them reference each 
other. Please read the tutorial:


  http://docs.python.org/tutorial/modules.html

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Using C++ and ctypes together: a vast conspiracy? ;)

2009-06-02 Thread Dave Angel

Joseph Garvin wrote:

So I was curious whether it's possible to use the ctypes module with
C++ and if so how difficult it is. I figure in principal it's possible
if ctypes knows about each compiler's name mangling scheme. So I
searched for "ctypes c++" on Google.

The third link will be "Using ctypes to Wrap C++ Libraries". If you
follow the link, it's broken. If you view the cache of the link, it's
someone pointing to another blog, retrograde-orbit.blogspot.com,
saying they discovered a way to do it easily. If you follow that link,
you get taken a page does not exist error.

Clearly there's some way to use ctypes with C++ and there's a vast
conspiracy preventing it from reaching the masses ;) What's even
stranger is that this link, despite being broken, has seemingly been
near the top of google's results for these terms for a couple weeks
(that's when I last tried), as if there were some underground group of
rebels trying to hint the truth to us... ;)

More seriously -- how difficult is it to use ctypes instead of saying,
boost::python, and why isn't this in a FAQ somewhere? ;)

  
There are two possibilities here.  You might have an existing DLL, 
written entirely in C++, with thoroughly mangled exports.   Or you might 
have a body of code, to which you're willing to make modifications for 
the interface.  It's only the second I would attack with ctypes.  In 
fact, the name mangling itself varies between versions of the same 
compiler, never mind between different brands.


You should be able to export a class factory, defined as an extern("c"), 
and use that to get into the DLL.  Once you have that, you can call any 
virtual functions of the class without any additional
exports or name mangling needed.  As long as the methods you're using 
are virtual, and singly inherited, it's just a question of walking the 
vtable.  So you should be able to build wrappers, using ctypes, for each 
of those methods.


Note:  I haven't actually done it, as the machine with the C++ compiler 
installed as been down for longer than I've had Python, and I haven't 
wanted C++ enough to want to install it on my notebook computer.  But 
this is the approach I'd try.



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


Re: "Exploding" (**myvariable) a dict with unicode keys

2009-06-02 Thread Samuel Wan
I started using python last week and ran into exceptions thrown when
unicode dictionary keys are exploded into function arguments. In my
case, decoded json dictionaries did not work as function arguments.
There was a thread from Oct 2008
(http://www.gossamer-threads.com/lists/python/python/684379) about the
same problem. Here is my workaround:

-- start code ---
def safe_dict(d):
"""Recursively clone json structure with UTF-8 dictionary keys"""
if isinstance(d, dict):
return dict([(k.encode('utf-8'), safe_dict(v)) for k,v in 
d.iteritems()])
elif isinstance(d, list):
return [safe_dict(x) for x in d]
else:
return d

#Example
foo = {
'a':1,
'b':{'b1':2, 'b2':3},
'c':[
4,
{'D1':2, 'D2':3},
]
}
#generate and re-parse json to simulate dictionary with unicode keys
dictionary = json.loads(json.dumps(foo))

# shows unicode keys, like u"a"
print dictionary

# shows utf8 keys, like "a"
converted_dictionary = safe_dict(dictionary)
fun(**converted_dictionary)
-- end code ---

I really like python! Hope this contributes to the thread.

-Sam


 On Oct 3, 1:57 pm, Peter Otten <__pete...@web.de> wrote:
> "Martin v. Löwis" wrote:
> > Devin wrote:
> >> So Python can have unicode variable names but you can't
> >> "explode" (**myvariable) a dict with unicode keys? WTF?
>
> > That works fine for me.
>
> The OP probably means
>
> >>> def f(a=1): return a
> ...
> >>> f(**{"a": 42})
> 42
> >>> f(**{u"a": 42})
>
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: f() keywords must be strings
>
> Peter

Yes, that's exactly what I mean.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using C++ and ctypes together: a vast conspiracy? ;)

2009-06-02 Thread Roy Smith
In article <78lit5f1mvib...@mid.uni-berlin.de>,
 "Diez B. Roggisch"  wrote:

> > More seriously -- how difficult is it to use ctypes instead of saying,
> > boost::python, and why isn't this in a FAQ somewhere? ;)
> 
> Because it's much more needed than name-mangling. Name mangling is 
> (amongst other things) one thing to prevent 
> C++-inter-compiler-interoperability which results from differing C++ ABIs.

Indeed.  Name mangling is the most trivial way in which different C++ 
compilers do not interoperate.  Some other thorny issues include exception 
handling, template instantiation, physical layout of struct and class 
elements (i.e. padding/alignment), and how references are returned (i.e. 
Return Value Optimization).  I'm sure I've left out several critical items.

It's an ugly world out there.
-- 
http://mail.python.org/mailman/listinfo/python-list


is anyone using text to speech to read python documentation

2009-06-02 Thread eric_dex...@msn.com
 I wrote a small pre-processor for python documentation and I am
looking for advice on how to get the most natural sounding reading.  I
uploaded an example of a reading of lxml documentation as a podcast1

http://dexrow.blogspot.com/2009/06/python-voice-preprocessor.html.

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


Missing codecs in Python 3.0

2009-06-02 Thread samwyse
I have a Python 2.6 program (a code generator, actually) that tries
several methods of compressing a string and chooses the most compact.
It then writes out something like this:
  { encoding='bz2_codec', data = '...'}

I'm having two problems converting this to Py3.  First is the absence
of the bz2_codec, among others.  It was very convenient for my program
to delay selection of the decoding method until run-time and then have
an easy way to load the appropriate code.  Is this gone forever from
the standard libraries?

Second, I would write my data out using the 'string_escape' codec.
It, too, has been removed; there's a 'unicode_escape' codec which is
similar, but I would rather use a 'byte_escape' codec to produce
literals of the form b'asdf'.  Unfortunately, there isn't one that I
can find.  I could use the repr function, but that seems less
efficient.  Does anyone have any ideas?  Thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Safe to import __builtin__ ?

2009-06-02 Thread Ben Finney
mrstevegross  writes:

> Is it generally safe to explicitly import __builtin__ in python? That
> is, my code reads like this:
> 
> === foo.py ===
> import __builtin__
> ...
> print __builtin__.type('a')
> === EOF ===
> 
> It seems like it should be a safe import, but I just want to make
> sure.

Yes, it's safe (and this is what the ‘__builtin__’ module is intended
for: http://docs.python.org/library/__builtin__>).

Be careful, though: there's a separate name, ‘__builtins__’, that is
*not* meant to be imported. It's also implementation-specific, so
shouldn't be relied upon. My advice: don't use ‘__builtins__’ at all,
but be aware that it exists so you spell ‘__builtin__’ correctly.

-- 
 \ “This world in arms is not spending money alone. It is spending |
  `\  the sweat of its laborers, the genius of its scientists, the |
_o__)   hopes of its children.” —Dwight Eisenhower, 1953-04-16 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to find the last decorator of a chain

2009-06-02 Thread Aahz
In article ,
Gabriel   wrote:
>
>I have something like this:
>
>@render(format="a")
>@render(format="b")
>@
>def view(format, data):
>  return data
>
>Each render will do something with 'data' if format match, and nothing
>if not.
>
>But if there is no more renders to eval, the last one is the default,
>and must run even if the format doesn't match.

My inclination would be to make this explicit with something like this:

def make_render(func, format_list):
def tmp(format, data):
for f in format_list:
if MATCH(format, f):
render(data)
break
else:
render(data)
return tmp

def view(format, data):
return data
view = make_render(view, ['a', 'b'])

IOW, just because we have decorators doesn't mean that they're the best
solution for all function-wrapping problems.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

my-python-code-runs-5x-faster-this-month-thanks-to-dumping-$2K-
on-a-new-machine-ly y'rs  - tim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Missing codecs in Python 3.0

2009-06-02 Thread Chris Rebert
On Tue, Jun 2, 2009 at 7:15 PM, samwyse  wrote:
> I have a Python 2.6 program (a code generator, actually) that tries
> several methods of compressing a string and chooses the most compact.
> It then writes out something like this:
>  { encoding='bz2_codec', data = '...'}
>
> I'm having two problems converting this to Py3.  First is the absence
> of the bz2_codec, among others.  It was very convenient for my program
> to delay selection of the decoding method until run-time and then have
> an easy way to load the appropriate code.  Is this gone forever from
> the standard libraries?

That appears to be the case. "bz2" is not listed on
http://docs.python.org/3.0/library/codecs.html , but it is listed on
the counterpart 2.6 doc page.
You can always use the `bz2` module instead. Or write your own
encoder/decoder for bz2 and register it with the `codecs` module.

> Second, I would write my data out using the 'string_escape' codec.
> It, too, has been removed; there's a 'unicode_escape' codec which is
> similar, but I would rather use a 'byte_escape' codec to produce
> literals of the form b'asdf'.  Unfortunately, there isn't one that I
> can find.  I could use the repr function, but that seems less
> efficient.  Does anyone have any ideas?  Thanks.

Well, if you can guarantee the string contains only ASCII, you can
just unicode_escape it, and then prepend a "b".
On the other hand, I don't see any reason why repr() would be
inefficient as compared to the codec method.

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


Re: Challenge supporting custom deepcopy with inheritance

2009-06-02 Thread Aahz
In article ,
Michael H. Goldwasser   wrote:
>
>Assume that class B inherits from class A, and that class A has
>legitimately customized its deepcopy semantics (but in a way that is
>not known to class B).  If we want a deepcopy of B to be defined so
>that relevant state inherited from A is copied as would be done for
>class A, and with B able to control how to deepcopy the extra state
>that it introduces.  I cannot immediately find a general way to
>properly implement the deepcopy of B.
>
>  [...]
>
>class A(object):
>def __init__(self, aTag):
>self.__aTag = aTag
>self.__aList = []

IMO, your problem starts right here.  Not only are you using customized
attributes for each class, you're using class-private identifiers.  You
would vastly simplify your work if you switch to single-underscore
attributes.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

my-python-code-runs-5x-faster-this-month-thanks-to-dumping-$2K-
on-a-new-machine-ly y'rs  - tim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Missing codecs in Python 3.0

2009-06-02 Thread Carl Banks
On Jun 2, 7:35 pm, Chris Rebert  wrote:
> On Tue, Jun 2, 2009 at 7:15 PM, samwyse  wrote:
> > I have a Python 2.6 program (a code generator, actually) that tries
> > several methods of compressing a string and chooses the most compact.
> > It then writes out something like this:
> >  { encoding='bz2_codec', data = '...'}
>
> > I'm having two problems converting this to Py3.  First is the absence
> > of the bz2_codec, among others.  It was very convenient for my program
> > to delay selection of the decoding method until run-time and then have
> > an easy way to load the appropriate code.  Is this gone forever from
> > the standard libraries?
>
> That appears to be the case. "bz2" is not listed 
> onhttp://docs.python.org/3.0/library/codecs.html, but it is listed on
> the counterpart 2.6 doc page.
> You can always use the `bz2` module instead. Or write your own
> encoder/decoder for bz2 and register it with the `codecs` module.

IIRC, they decided the codecs would only be used for bytes<->unicode
encodings in Python 3.0 (which was their intended use all along),
moving other mappings (like bz2) elsewhere.  Not sure where they all
went, though.

It was convenient, admittedly, but also confusing to throw all the
other codecs in with Unicode codecs.



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


Re: Using C++ and ctypes together: a vast conspiracy? ;)

2009-06-02 Thread Lawrence D'Oliveiro
In message , Sebastian Wiesner wrote:

> 
> 
>> That said I've used C++ with ctypes loads of times, but I always wrap
>> the exported stuff in extern "C" { } blocks.
> 
> No wonder, you have never actually used C++ with C types.  An extern "C"
> clause tells the compiler to generate C functions (more precisely,
> functions that conform to the C ABI conventions), so effectively you're
> calling into C, not into C++.

Seems like the only sane way to do it. In all other directions lies madness.

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


Re: Seach for encrypted socket wrapper

2009-06-02 Thread Lawrence D'Oliveiro
In message <4a24f0cc$0$3278$8e6e7...@newsreader.ewetel.de>, Hans Müller 
wrote:

> display clientCalculation 
> module in COBOL (yes, big, old but it
> works well)
> (python, wxpython)<- Network connection ->C-Lib beeing called from
> COBOL to communicaty with
>  display client
> 
> The network connection should be encrypted. And fail save.

Not sure what you mean by "fail save". But I have used protocols built on 
this sort of framework






in several projects now.

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


Re: Using C++ and ctypes together: a vast conspiracy? ;)

2009-06-02 Thread Kay Schluehr
On 3 Jun., 05:51, Lawrence D'Oliveiro  wrote:
> In message , Sebastian Wiesner wrote:
>
> > 
>
> >> That said I've used C++ with ctypes loads of times, but I always wrap
> >> the exported stuff in extern "C" { } blocks.
>
> > No wonder, you have never actually used C++ with C types.  An extern "C"
> > clause tells the compiler to generate C functions (more precisely,
> > functions that conform to the C ABI conventions), so effectively you're
> > calling into C, not into C++.
>
> Seems like the only sane way to do it. In all other directions lies madness.

Yes but creating C stubs is also hard in presence of everything that
is not basic C++. How would you wrap the STL? I suspect one ends up in
creating a variant of SWIG and I wonder if it's not a good idea to
just use SWIG then.
-- 
http://mail.python.org/mailman/listinfo/python-list


problem with sockets and transferring binary files

2009-06-02 Thread thebiggestbangtheory
Dear all,
   I am a python newbie. I am now progressing to writing a
network app in python to learn more about it. I have a client and a
server in python. The client sends a msg to the server asking it to
tar a binary .dbxml file and then send it over to it. The steps are:
from the
1. Client sends msg to server
2. Server tars up binary file and Encrypts it using ezpycrypto
3. Server sends it to client
4. Client receives file and decrypts it and untars it

Surprisingly, the sha1 hash of the encrypted data before it is sent
from server is different  from the encrypted file data received by the
client. I post some code below to provide more info about what I am
doing.

[code]
#client after sending initial msg
#get server replywhich sends back the .dbxml file
myHost = '127.0.0.1'
myPort = 20001

s1 = socket(AF_INET, SOCK_STREAM)# create a TCP socket
s1.bind((myHost, myPort))# bind it to the server
port
s1.listen(1) # allow 1 simultaneous
  # pending connections

connection, address = s1.accept() # connection is a new socket
while 1:
  data = connection.recv(1000) # receive up to 1000
bytes
  if data:
info=decryptfile(data)

#we have recieved a compressed .tar.gz file
#write out info to a file
buf = open(currentpath+'received-container.tar.gz', 'w')
buf.write(info)
buf.close()

#testing code: must be removed
os.system('sudo sha1sum '+currentpath+'received-xml-
container.tar.gz')

#uncompress
os.system('sudo tar -xvzf '+currentpath+'received-xml-
container.tar.gz')

[/code]
[code]
#the server after receiving the msg from client
#dump the binary file
os.system('sudo cp '+'/'+path+'1.binary '+currentpath
+'1.binary')

#compress the file
os.system('sudo tar -cvzf '+currentpath+'1.bin.tar.gz
'+currentpath+'1.binary')

#encrypt the file specified in command line
cipher=encryptfile(secretkey, currentpath+'1.bin.tar.gz')

#send it over to sender
send_to_sender(cipher, senderaddress)

#testing code: needs to be removed
buf = open(currentpath+'cipher', 'w')
buf.write(cipher)
buf.close()
os.system('sudo sha1sum '+currentpath+'cipher')
[/code]
[code]
#function code
def send_to_sender(cipher, servername):
PORT = 20001
BUFF = 1000
clientSocket = socket(AF_INET, SOCK_STREAM)
HOST = servername
ADDR = (HOST, PORT)
clientSocket.connect(ADDR)
clientSocket.send(cipher)
clientSocket.close()
[/code]

What I see at the client side is

7105b60d3167f2424d9e2806c49cca86c00577ba  received-container.tar.gz

gzip: stdin: unexpected end of file
tar: Unexpected EOF in archive
tar: Unexpected EOF in archive
tar: Error is not recoverable: exiting now
da39a3ee5e6b4b0d3255bfef95601890afd80709  received-container.tar.gz

gzip: stdin: unexpected end of file
tar: Child returned status 1
tar: Error exit delayed from previous errors

It seems two file pieces are received! but why? The buffer size is big
enough to accept the whole thing in one go. The binary file is about
460K in size.

Any pointers, comments will be greatly appreciated :-).

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


Re: Missing codecs in Python 3.0

2009-06-02 Thread Martin v. Löwis
samwyse wrote:
> I have a Python 2.6 program (a code generator, actually) that tries
> several methods of compressing a string and chooses the most compact.
> It then writes out something like this:
>   { encoding='bz2_codec', data = '...'}
> 
> I'm having two problems converting this to Py3.  First is the absence
> of the bz2_codec, among others.  It was very convenient for my program
> to delay selection of the decoding method until run-time and then have
> an easy way to load the appropriate code.  Is this gone forever from
> the standard libraries?

bz2 compression is certainly not gone from the standard library; it
is still available from the bz2 module.

I recommend that you write it like

  { decompressor = bz2.decompress, data = '...'}

Then you can still defer invocation of the decompressor until you
need the data.

> Second, I would write my data out using the 'string_escape' codec.
> It, too, has been removed; there's a 'unicode_escape' codec which is
> similar, but I would rather use a 'byte_escape' codec to produce
> literals of the form b'asdf'.  Unfortunately, there isn't one that I
> can find.  I could use the repr function, but that seems less
> efficient.  Does anyone have any ideas?

Why does the repr() function seem less efficient? Did you measure
anything to make it seem so?

I would recommend to use repr() exactly.

Regards,
Martin

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


Re: problem with sockets and transferring binary files

2009-06-02 Thread Gabriel Genellina
En Wed, 03 Jun 2009 01:54:02 -0300,   
escribió:



   I am a python newbie. I am now progressing to writing a
network app in python to learn more about it. [...]
Surprisingly, the sha1 hash of the encrypted data before it is sent
from server is different  from the encrypted file data received by the
client.



  data = connection.recv(1000) # receive up to 1000
bytes


recv returns *up* *to* 1000 bytes: maybe only one byte.
You'll have to keep recv'ing the pieces until you get an empty string  
(when client closes the connection), or send the file size first and then  
the actual data.



buf = open(currentpath+'received-container.tar.gz', 'w')
buf.write(info)
buf.close()


If you're on Linux it doesn't matter, but the 'w' above should be 'wb' for  
a binary file.



def send_to_sender(cipher, servername):
...
clientSocket.send(cipher)


Similar to recv above: send() might not send the whole string at once (try  
sendall instead).


--
Gabriel Genellina

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


Re: how to get the path of a module (myself) ?

2009-06-02 Thread Gabriel Genellina

En Tue, 02 Jun 2009 06:11:30 -0300, Vlastimil Brom
 escribió:


[...] just in case the main problem would be the
use of __file__ ...
It seems, that the exe files generated from py2exe don't recognise
this variable;
sometimes I used code like

try:
__file__
except NameError: # py2exe
__file__ = sys.path[0]


I think you meant __file__ = sys.argv[0]

cf. e.g.  
http://mail.python.org/pipermail/python-list/2001-May/085384.html


That's a rather old post. The "right" way to obtain a resource from a
package is using pkgutil.get_data(), and py2exe should support it by now.
(I haven't tested, but I think it does).
http://docs.python.org/library/pkgutil.html

--
Gabriel Genellina

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


Re: Why date do not construct from date?

2009-06-02 Thread Gabriel Genellina

En Tue, 02 Jun 2009 08:07:32 -0300, Lie Ryan  escribió:

Gabriel Genellina wrote:

En Tue, 02 Jun 2009 03:14:22 -0300, Chris Rebert 
escribió:

On Mon, Jun 1, 2009 at 10:25 PM, Alexandr N Zamaraev
 wrote:



import datetime as dt
d = dt.date(2009, 10, 15)
dt.date(d)

Traceback (most recent call last):
 File "", line 1, in 
TypeError: function takes exactly 3 arguments (1 given)



Why int form int, str from str, Decumal from Decumal can construct
bat date from date not?


Probably because the function signatures would be so different. str(),
int(), etc *always* take *exactly one* argument -- the object to
convert. In contrast, date() takes several integers corresponding to
the year, month, and day. Adding a second signature to it that took
exactly one argument (of type `date`) and copied it would be
significantly different from its other signature; in idiomatic Python,
one would typically make a separate, new function for this drastically
different signature.


That doesn't convince me. It's not very consistent along the various
types: int("3ab0",16) is rather different than int(3.2) but they're the
same function...


Strictly speaking int("3ab0",16) does not create an int from an int,
instead it creates an int from a string.
Maybe you want to say int(3) -> 3 ?


I was replying to the argument "different signature => separate function".


However, the `date` type is immutable, so there's no reason at all to
try and copy a new instance from an existing one anyway, thus a
single-argument copy-constructor is completely unnecessary, hence why
there isn't one.


Isn't the same for all other examples (int, float, str, Decimal...)?
They're all immutable types, and some have several and rather different
constructor signatures:


int(ob), float(ob), and str(ob) are type casting (strictly speaking it
is not a type casting, but you get the idea); while date() is a
constructor for the date object. Strictly speaking int(ob), float(ob),
and str(ob) merely calls the special ob.__int__, ob.__float__, and
ob.__str__.


Well, not really:

py> "10".__int__
Traceback (most recent call last):
   File "", line 1, in 
AttributeError: 'str' object has no attribute '__int__'
py> "10".__float__
Traceback (most recent call last):
   File "", line 1, in 
AttributeError: 'str' object has no attribute '__float__'

int() and float() do the work themselves when given a string (they look
more like "true" constructors than str(), which delegates to __str__ as
you already said)

En Tue, 02 Jun 2009 08:23:27 -0300, Lie Ryan  escribió:


In fact, the doc of int and float says "Convert a string or number to an
integer, if possible" and "Convert a string or number to a floating
point number, if possible" respectively. There is no mention that they
are constructors at all...


I think this comes from the prehistoric ages when int/float/str were  
functions, not built-in types.


En Tue, 02 Jun 2009 04:45:19 -0300, Peter Otten <__pete...@web.de>  
escribió:



For date you'd have to make the type check anyway, e. g.

if isinstance(x, tuple):
   x = date(*x)
else:
   x = date(x) # useless will only succeed if x already is a date

as there would be no other way to create a date from a single value.

So the date() call in the else branch is completely redundant unless you
change date() to accept multiple types via the same signature:

for x in "2000-01-01", datetime.now(), (2000, 1, 1):
print date(x)


That's a more pragmatic response, in the line "because it isn't very  
useful". I can accept this other too: "because whoever wrote the datetime  
module didn't care to provide such constructor".


--
Gabriel Genellina

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


Re: problem with sockets and transferring binary files

2009-06-02 Thread thebiggestbangtheory
On Jun 2, 10:29 pm, "Gabriel Genellina" 
wrote:
> En Wed, 03 Jun 2009 01:54:02 -0300,   
> escribió:
>
> >            I am a python newbie. I am now progressing to writing a
> > network app in python to learn more about it. [...]
> > Surprisingly, the sha1 hash of the encrypted data before it is sent
> > from server is different  from the encrypted file data received by the
> > client.
> >           data = connection.recv(1000) # receive up to 1000
> > bytes
>
> recv returns *up* *to* 1000 bytes: maybe only one byte.
> You'll have to keep recv'ing the pieces until you get an empty string  
> (when client closes the connection), or send the file size first and then  
> the actual data.
>
> >             buf = open(currentpath+'received-container.tar.gz', 'w')
> >             buf.write(info)
> >             buf.close()
>
> If you're on Linux it doesn't matter, but the 'w' above should be 'wb' for  
> a binary file.
>
> > def send_to_sender(cipher, servername):
> >     ...
> >     clientSocket.send(cipher)
>
> Similar to recv above: send() might not send the whole string at once (try  
> sendall instead).
>
> --
> Gabriel Genellina

Thanks! :-) very helpful
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wrapping methods of built-in dict

2009-06-02 Thread shailesh
On May 21, 10:13 pm, George Sakkis  wrote:
> On May 21, 5:55 pm, shailesh  wrote:
>
> > There doesn't seem to be a predicate returning method wrappers. Is
> > there an alternate way to query an object for attributes that are of
> > method wrappers?
>
> Sure:>>> MethodWrapper = type({}.__init__)
> >>> isinstance([].__len__, MethodWrapper)
>
> True
>
> But you're better off catching everything by checking with callable()
> (or equivalently hasattr(obj, '__call__')).
>
> > This exercise also makes me question if I'm going about this
> > correctly. If I want to add functionality to the methods of a class or
> > an object are decorators and the inspect module the pythonic way to go
> > about it? I can think of alternative implementations either through
> > metaclasses or proxy objects.
>
> In my experience, it's quite unlikely to really want to decorate
> indiscriminately *all* methods of a class/instance, let alone all the
> special methods (e.g. __getattribute__ very rarely needs to be
> overridden). Do you have an actual use case or are you just playing
> around ?

The use case I'm exploring is automatic lock acquisition and release.
I've been trying to create a decorator which protects objects against
concurrent modification by placing all attribute behind a mutex. More
fine grained locking will probably perform better, but the convenience
and reliability of auto-locking is nice. Suggestions for alternate
implementations are most welcome.

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


Python reimport

2009-06-02 Thread peteshinners
I've implemented a working reimport that, "does what you want". After
a bit of testing with friends, I'm releasing version 1.0 tonight.

http://code.google.com/p/reimport/

There's still work to do, but this already does a bit of fancy
transmuting to push the reimport changes into the runtime. This is not
a fully solveable problem, but this also allows modules to define
callbacks that can assist the process.

Looking for a wider audience to test with. At minimum, my friends and
I are using this as a huge relief to alternative workarounds. At best
this release will spur wider adoption and further development.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Copying objects and multiple inheritance

2009-06-02 Thread Gabriel Genellina
En Tue, 02 Jun 2009 19:02:47 -0300, Brian Allen Vanderburg II  
 escribió:


What is the best way to copy an object that has multiple inheritance  
with the copy module.  Particularly, some of the instances in the  
hierarchy


("...some of the classes in...", I presume?)

use the __copy__ method to create a copy (because even for shallow  
copies they need some information  updated a little differently), so how  
can I make sure all the information is copied as it is supposed to be  
even for the base classes that have special requirements.


If you don't control all the clases involved, there is little hope for a  
method like __copy__ to work at all... All classes must be written with  
cooperation in mind, using super() the "right" way. See "Python's Super  
Considered Harmful" [1] and "Things to Know About Python Super" [2][3][4]


That said, and since multiple inheritance is the heart of the problem,  
maybe you can redesign your solution *without* using MI? Perhaps using  
delegation instead?


[1] http://fuhm.net/super-harmful/
[2] http://www.artima.com/weblogs/viewpost.jsp?thread=236275
[3] http://www.artima.com/weblogs/viewpost.jsp?thread=236278
[4] http://www.artima.com/weblogs/viewpost.jsp?thread=237121

--
Gabriel Genellina

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