comp.lang.python - 26 new messages in 11 topics - digest
comp.lang.python
http://groups.google.com/group/comp.lang.python?hl=en
comp.lang.python@googlegroups.com
Today's topics:
* Need help to pass self.count to other classes. - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/944e986629fc0536?hl=en
* Append to an Excel file - 3 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/6e21b15ce9abeb32?hl=en
* Clarifications on compiling for Windows - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/57d7d539bc25372c?hl=en
* Link to module Stack - 4 messages, 4 authors
http://groups.google.com/group/comp.lang.python/t/5f7014f20243d059?hl=en
* C Module's '1.#INF' changes to 'inf' at Python - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/3031bc575be48cc0?hl=en
* lightweight encryption of text file - 5 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/b31a5b5f58084f12?hl=en
* Porblem with xlutils/xlrd/xlwt - 5 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/c81ebab2554b9f2f?hl=en
* table from csv file - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/1b3241d76be564ad?hl=en
* How to get many places of pi from Machin's Equation? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/eb0ff21fb5dbcf25?hl=en
* Accessing python from a network share in windows 7 - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/e2d3b424a78df3bd?hl=en
* Standardized interpreter speed evaluation tool - 2 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/a573cd475adf454e?hl=en
==============================================================================
TOPIC: Need help to pass self.count to other classes.
http://groups.google.com/group/comp.lang.python/t/944e986629fc0536?hl=en
==============================================================================
== 1 of 1 ==
Date: Fri, Jan 8 2010 10:14 pm
From: Lie Ryan
On 1/8/2010 3:56 PM, Steven D'Aprano wrote:
> Unfortunately this won't do what you expect, because sys.ps1 and ps2
> should be either strings, or objects with a __str__ method. They aren't
> called to generate the prompt.
but their __str__ does get called to generate the prompt.
import sys
class kbInterfaceHelper(object):
def __init__(self, str_func):
self.str_func = str_func
def __str__(self):
return self.str_func()
class kbInterface(object):
def __init__(self):
self.count = 0
def prompt1(self):
self.count += 1
return "[%d]> " % self.count
def prompt2(self):
l = len(str(self.count))+1
return "%s " % "."*l
def dhook(self, value):
print "[%d out]" % self.count
def ehook(self, type, value, trace):
print "[%d err]\n" % value
kbi = kbInterface()
sys.ps1 = kbInterfaceHelper(kbi.prompt1)
sys.ps2 = kbInterfaceHelper(kbi.prompt2)
sys.displayhook = kbi.dhook
sys.excepthook = kbi.ehook
==============================================================================
TOPIC: Append to an Excel file
http://groups.google.com/group/comp.lang.python/t/6e21b15ce9abeb32?hl=en
==============================================================================
== 1 of 3 ==
Date: Sat, Jan 9 2010 12:30 am
From: pp
Hi All,
How do I add a line to an existing file. This should append to the
existing data in the excel file, which was saved previously.
Thanks,
PP
== 2 of 3 ==
Date: Sat, Jan 9 2010 12:47 am
From: Jason Scheirer
On Jan 9, 12:30 am, pp <parul.pande...@gmail.com> wrote:
> Hi All,
>
> How do I add a line to an existing file. This should append to the
> existing data in the excel file, which was saved previously.
>
> Thanks,
> PP
http://pypi.python.org/pypi/xlwt
== 3 of 3 ==
Date: Sat, Jan 9 2010 12:58 am
From: pp
On Jan 9, 1:47 am, Jason Scheirer <jason.schei...@gmail.com> wrote:
> On Jan 9, 12:30 am, pp <parul.pande...@gmail.com> wrote:
>
> > Hi All,
>
> > How do I add a line to an existing file. This should append to the
> > existing data in the excel file, which was saved previously.
>
> > Thanks,
> > PP
>
> http://pypi.python.org/pypi/xlwt
Hi Jason and all,
Thanks
I have seen this.. my question is there a way to append to a excel
file which has been closed. Any specific modes which can be added to
the sheet so that it adds a line to the data which was return in some
earlier running of the program.
Thanks.
==============================================================================
TOPIC: Clarifications on compiling for Windows
http://groups.google.com/group/comp.lang.python/t/57d7d539bc25372c?hl=en
==============================================================================
== 1 of 2 ==
Date: Sat, Jan 9 2010 12:56 am
From: Jason Scheirer
On Jan 7, 10:51 pm, Mensanator <mensana...@aol.com> wrote:
> On Jan 8, 12:19 am, peteshinners <p...@shinners.org> wrote:
>
>
>
>
>
>
>
> > My presentation for Pycon is coming together, but I need to make sure
> > my information about compiling Python and Python extensions for
> > Windows is correct. I'm really only experienced with this on the Linux
> > side of things.
>
> > First of all, is the Windows FAQ fairly up to date? Should people be
> > referring to section 6 if they are going to build an application with
> > an embedded Python interpreter?http://www.python.org/doc/faq/windows/#how-can-i-embed-python-into-a-...
>
> > If I understand correctly, compiled extensions for Python on Windows
> > should match the compiler that was used to build the interpreter
> > itself? Is there a list somewhere that shows which version of msvc was
> > used to compile the recent Python binaries?
>
> > Thank you for feedback. I definitely want to make sure I have this
> > correct before telling anybody else?
>
> You aren't going to try it?
At a high level: YES. Avoid FILE* and you are golden on Windows. Works
like a charm.
MSVC 2008 works for 2.6 with the least effort (I strongly recommend
having it installed as that's what the build uses). If you have VS2008
you will have no problem whatsoever with setup.py install, even with C
extensions. I'd like to verify the same with earlier versions of VS
but I can't. MinGW works, too, but with slightly more effort: there
are some command line arguments you have to issue setup.py to know how
to use/where the MinGW compiler is.
== 2 of 2 ==
Date: Sat, Jan 9 2010 2:24 am
From: "Martin v. Loewis"
> First of all, is the Windows FAQ fairly up to date?
Fairly, yes.
> Should people be
> referring to section 6 if they are going to build an application with
> an embedded Python interpreter?
I think that's very selective in its view of problems - why would I
be using SWIG, for example? (yet there are three issues dedicated to
SWIG in this section)
pythonNN.dll is not in \windows\system, but in system32 or winsxs.
pythonNN.lib is *not* a static library, but (as the text then notes)
an import library. So even if you link with pythonNN.lib, you *still*
need pythonNN.dll at run-time (what is discussed as a drawback of
dynamic linking). Of course, it might be possible to build a static
library out of Python (which then still might be called pythonNN.lib).
IMO, it should be possible to link Python into the executable (at
the expense of not supporting dynamic loading of extension modules
anymore).
> If I understand correctly, compiled extensions for Python on Windows
> should match the compiler that was used to build the interpreter
> itself? Is there a list somewhere that shows which version of msvc was
> used to compile the recent Python binaries?
See PCbuild/readme.txt of the respective Python release.
2.3: VC 6
2.4, 2.5: VC 7.1 / VS .NET 2003
2.6, 3.1: VC 9 / VS 2008
Regards,
Martin
==============================================================================
TOPIC: Link to module Stack
http://groups.google.com/group/comp.lang.python/t/5f7014f20243d059?hl=en
==============================================================================
== 1 of 4 ==
Date: Sat, Jan 9 2010 1:07 am
From: kzagradskiy
Link to module Stack:
http://groups.google.com/group/comp.lang.python/browse_thread/thread/e6a0668bb2be9a8e/64cb44a120baeca2?lnk=gst&q=stack+module#64cb44a120baeca2
Here's the stack module for py4th.
nick
---------------<cut here>----------------
#!/usr/Util/bin/python
#
# @(#)stack.py 1.1
#
# stack.py
# generic stack class.
class Stack:
def __init__(self):
self.__heap = []
def push (self, word):
self.__heap.append (word)
def pop (self):
if len(self.__heap) == 0:
raise InnerInterpreterError, "stack underflow"
result = self.__heap[-1]
del self.__heap[-1]
return result
def __repr__(self):
return `self.__heap`
def __str__(self):
return `self.__heap`
def flush (self):
self.__heap = []
== 2 of 4 ==
Date: Sat, Jan 9 2010 1:25 am
From: Steven D'Aprano
On Sat, 09 Jan 2010 01:07:39 -0800, kzagradskiy wrote:
> class Stack:
> def __init__(self):
> self.__heap = []
A "heap" has a technical meaning in programming. To describe the
internals of a stack as "heap" will be disconcerting and confusing to
anyone who knows about stacks and heaps.
> def push (self, word):
> self.__heap.append (word)
> def pop (self):
> if len(self.__heap) == 0:
> raise InnerInterpreterError, "stack underflow"
"InnerInterpreterError" is the most inappropriate exception name I've
ever seen. It has nothing to do with the interpreter, it's a stack error.
> result = self.__heap[-1]
> del self.__heap[-1]
That is better written as result = self.__heap.pop().
--
Steven
== 3 of 4 ==
Date: Sat, Jan 9 2010 2:56 am
From: Dave Angel
Steven D'Aprano wrote:
> On Sat, 09 Jan 2010 01:07:39 -0800, kzagradskiy wrote:
>
>
>> class Stack:
>> def __init__(self):
>> self.__heap = []
>>
>
> A "heap" has a technical meaning in programming. To describe the
> internals of a stack as "heap" will be disconcerting and confusing to
> anyone who knows about stacks and heaps.
>
>
>
>> def push (self, word):
>> self.__heap.append (word)
>> def pop (self):
>> if len(self.__heap) == 0:
>> raise InnerInterpreterError, "stack underflow"
>>
>
> "InnerInterpreterError" is the most inappropriate exception name I've
> ever seen. It has nothing to do with the interpreter, it's a stack error.
>
>
It has everything to do with the (Forth) interpreter. Exceptions can
readily be named according to their application -- it's not always about
Python. Anyway, Forth has an inner-interpreter and an
outer-interpreter, and the name will make sense to a Forth programmer.
>> result = self.__heap[-1]
>> del self.__heap[-1]
>>
>
> That is better written as result = self.__heap.pop().
>
>
>
or even better, without the extra local var:
def pop (self):
if len(self.__heap) == 0:
raise InnerInterpreterError, "stack underflow"
return self.__heap.pop(1)
P.S. - I'm puzzled why the OP even put this message here. There's no
question posted with it.
DaveA
== 4 of 4 ==
Date: Sat, Jan 9 2010 3:40 am
From: Duncan Booth
Dave Angel <davea@ieee.org> wrote:
> or even better, without the extra local var:
>
> def pop (self):
> if len(self.__heap) == 0:
> raise InnerInterpreterError, "stack underflow"
> return self.__heap.pop(1)
pop(1)?
Anyway if would be simpler and almost certainly faster to not bother
checking before the pop:
def pop(self):
try:
return self.__heap.pop()
except IndexError:
raise InnerInterpreterError, "stack underflow"
and if performance mattered the OP might even consider pre-binding the pop
method in __init__:
self.__pop = self.__heap.pop
but that's probably premature optimisation.
> P.S. - I'm puzzled why the OP even put this message here. There's no
> question posted with it.
Me too. It's a repost of something from 2004. Bizarre.
==============================================================================
TOPIC: C Module's '1.#INF' changes to 'inf' at Python
http://groups.google.com/group/comp.lang.python/t/3031bc575be48cc0?hl=en
==============================================================================
== 1 of 1 ==
Date: Sat, Jan 9 2010 1:22 am
From: Mark Dickinson
On Jan 8, 3:36 pm, Robert Kern <robert.k...@gmail.com> wrote:
> On 2010-01-08 07:48 AM, CELEN Erman wrote:
> > My problem is that I've noticed a strange behavior in Python while
> > handling FPEs on Windows after switching compilers (msvc8 to msvc9) and
> > I am trying to find out how Python handles INF values to figure out
> > where the problem might be.
> > [...]
>
> Python 2.6 changed the string representations of the special floating point
> values inf and nan. Previously, the string representation was left up to the C
> runtime, so they differed between platforms. Python 2.6 normalized the string
> representation across all platforms. The underlying values are the same. What
> version of Python are you using?
In addition to this, for good or ill Python 2.6 also standardized
exceptional behaviour for the math module functions: log10(0.0) and
sqrt(-1) used to produce different results across implementations, but
now both should consistently produce ValueError regardless of the
platform. This is achieved by dealing directly with special cases in
the input before delegating to the relevant libm function; this of
course has an associated performance cost. There are some notes on
the (intended) current behaviour at the top of the Modules/
mathmodule.c file:
http://svn.python.org/view/*checkout*/python/branches/release26-maint/Modules/mathmodule.c
--
Mark
==============================================================================
TOPIC: lightweight encryption of text file
http://groups.google.com/group/comp.lang.python/t/b31a5b5f58084f12?hl=en
==============================================================================
== 1 of 5 ==
Date: Sat, Jan 9 2010 1:52 am
From: Anthra Norell
Daniel Fetchinson wrote:
> I have a plain text file which I would like to protect in a very
> simple minded, yet for my purposes sufficient, way. I'd like to
> encrypt/convert it into a binary file in such a way that possession of
> a password allows anyone to convert it back into the original text
> file while not possessing the password one would only see the
> following with the standard linux utility 'file':
>
> [fetchinson@fetch ~]$ file encrypted.data
> encrypted.data: data
>
> and the effort required to convert the file back to the original text
> file without the password would be equivalent to guessing the
> password.
>
> I'm fully aware of the security implications of this loose
> specification, but for my purposes this would be a good solution.
>
> What would be the simplest way to achieve this using preferably stock
> python without 3rd party modules? If a not too complex 3rd part
> module made it really simple that would be acceptable too.
Daniel,
Here's what looks like another thread veering off into package-ology,
leaving a stumped OP behind.
"Don't use a random generator for encryption purposes!" warns the
manual, of which fact I was reminded in no uncertain terms on this forum
a few years ago when I proposed the following little routine in response
to a post very similar to yours. One critic challenged me to encode my
credit card data and post it. Which I did. Upon which another critic
conjured up the horror vision of gigahertzes hacking my pathetic little
effort to pieces as I was reading his message. Of the well-meaning kind,
he urged me to put an immediate stop to this foolishness. I didn't.
No unplanned expenditures ensued.
Or to quote ... I forget who: Fools and innovators are people who don't
care much about what one is not supposed to do.
So, take or leave what follows for what it is worth or not worth, I am
confident it works and would serve your purpose, which, as I understand,
is not to write a text book on cryptology.
Regards
Frederic
##############################
import random
def crypt_string (string, key, floor = 0, size_of_set = 255):
# key is a number. The sign of that number controls which way the
process
# goes. If the number is positive, the result is an encryption. A
negative
# number orders a decryption.
if key == 0: return string # No processing
import random
MAX_CHUNK_SIZE = 32
MIN_CHUNK_SIZE = 16
def process_sequence (sequence):
s = ''
for c in sequence:
r = random.randint (0, size_of_set - 1)
s += chr (((ord (c) - floor + r * sign) % size_of_set) + floor)
return s
def shuffle_sequence (sequence):
random.shuffle (sequence)
return sequence
sign = (key > 0) * 2 - 1
random.seed (key * sign)
s = ''
if sign > 0: # forward
i = 0
while i < len (string):
random_size_of_chunk = random.randint (MIN_CHUNK_SIZE,
MAX_CHUNK_SIZE)
clear_chunk_shuffled = shuffle_sequence (list (string
[i:i+random_size_of_chunk]))
code_chunk_shuffled = process_sequence (clear_chunk_shuffled)
s += code_chunk_shuffled
i += len (code_chunk_shuffled)
else: # backward
i = 0
while i < len (string):
random_size_of_chunk = random.randint (MIN_CHUNK_SIZE,
MAX_CHUNK_SIZE)
code_chunk_shuffled = list (string [i:i+random_size_of_chunk])
real_size_of_chunk = len (code_chunk_shuffled)
unshuffling_template = shuffle_sequence (range
(real_size_of_chunk)) # 1. same ...
clear_chunk_shuffled = process_sequence
(code_chunk_shuffled) # 2. ... order
clear_chunk = real_size_of_chunk * [None]
for ii in range (real_size_of_chunk):
clear_chunk [unshuffling_template[ii]] =
clear_chunk_shuffled [ii]
s += ''.join (clear_chunk)
i += real_size_of_chunk
return s
def _crypt_file (in_file, out_file, key):
BUFFER_SIZE = 1024
while 1:
s = in_file.read (BUFFER_SIZE)
if s == '': break
out_file.write (crypt_string (s, key))
def crypt_file (in_file_name, out_file_name, key):
in_file = open (in_file_name, 'rb')
out_file = open (out_file_name, 'wb')
_crypt_file (in_file, out_file, key)
out_file.close ()
== 2 of 5 ==
Date: Sat, Jan 9 2010 2:26 am
From: Daniel Fetchinson
>>>>> I have a plain text file which I would like to protect in a very
>>>>> simple minded, yet for my purposes sufficient, way. I'd like to
>>>>> encrypt/convert it into a binary file in such a way that possession of
>>>>> a password allows anyone to convert it back into the original text
>>>>> file while not possessing the password one would only see the
>>>>> following with the standard linux utility 'file':
>>>>>
>>>>> [fetchinson@fetch ~]$ file encrypted.data
>>>>> encrypted.data: data
>>>>>
>>>>> and the effort required to convert the file back to the original text
>>>>> file without the password would be equivalent to guessing the
>>>>> password.
>>>>>
>>>>> I'm fully aware of the security implications of this loose
>>>>> specification, but for my purposes this would be a good solution.
>>>>>
>>>>> What would be the simplest way to achieve this using preferably stock
>>>>> python without 3rd party modules? If a not too complex 3rd party
>>>>> module made it really simple that would be acceptable too.
>>>>
>>>> Paul Rubin's p3.py algorithm is probably the most straightforward way to
>>>> meet
>>>> these requirements. It's not a standard crypto algorithm by any means,
>>>> but
>>>> Paul
>>>> knows his stuff and has devised it with these deployment restrictions in
>>>> mind.
>>>>
>>>> http://www.nightsong.com/phr/crypto/p3.py
>>>
>>> Thanks a lot, currently I'm having trouble using this code on python
>>> 2.6 but probably some small tweaking will fix it.
>>
>> Actually, it also doesn't work with python 2.5 and currently I don't
>> have access to anything older. array.array raises a
>>
>> ValueError: string length not a multiple of item size
>>
>> Does anyone recall a change to array.array?
>>
>> The full traceback is
>>
>> Traceback (most recent call last):
>> File "p3.py", line 163, in<module>
>> _test()
>> File "p3.py", line 143, in _test
>> c1 = e(plain,key)
>> File "p3.py", line 69, in p3_encrypt
>> xkey = _expand_key(k_enc, n+4)
>> File "p3.py", line 41, in _expand_key
>> return array ('L', j)
>> ValueError: string length not a multiple of item size
>
> Are you on a 64-bit platform? Unfortunately, array's integer typecodes are
> platform-specific, but p3.py requires a 32-bit integer and was written on a
> 32-bit platform. It's reasonably straightforward to fix. Put this bit of
> (untested) code at the top of the file and replace occurrences of 'L' with
> uint32:
>
> # Find the typecode of a 32-bit unsigned integer.
> for typecode in 'IL':
> if len(array(typecode, [0]).tostring()) == 4:
> uint32 = typecode
> break
> else:
> raise RuntimeError("Neither 'I' nor 'L' are unsigned 32-bit integers.")
Thanks!
That was exactly the problem, I'm on a 64 bit machine and your fix
seems to work indeed.
Cheers,
Daniel
--
Psss, psss, put it down! - http://www.cafepress.com/putitdown
== 3 of 5 ==
Date: Sat, Jan 9 2010 2:45 am
From: Daniel Fetchinson
On 1/9/10, Steven D'Aprano <steve@remove-this-cybersource.com.au> wrote:
> On Fri, 08 Jan 2010 20:14:51 +0100, Daniel Fetchinson wrote:
>
>> I have a plain text file which I would like to protect in a very simple
>> minded, yet for my purposes sufficient, way. I'd like to encrypt/convert
>> it into a binary file in such a way that possession of a password allows
>> anyone to convert it back into the original text file while not
>> possessing the password one would only see the following with the
>> standard linux utility 'file':
>>
>> [fetchinson@fetch ~]$ file encrypted.data
>> encrypted.data: data
>
> If that is your sole requirement,
No, that was not my sole requirement, I also wrote:
"""
and the effort required to convert the file back to the original text
file without the password would be equivalent to guessing the
password.
"""
> then the addition of a single non-text
> byte (say, a null) anywhere in the file would be sufficient to have file
> identify it as data.
Yes, but this would not satisfy the other requirement quoted above.
One could read the file without an effort that is equivalent to
guessing a random password.
> You say "encrypt/convert" -- does this mean that you
> don't care if people can read the text in a hex editor, so long as file
> identifies it as data?
I do care. See the quote above :)
> Would something like a binary Vigenere Cipher be sufficient?
>
>
> # Untested
> def encrypt(plaintext, password):
> cipher = []
> for i, c in enumerate(plaintext):
> shift = password[i % len(password)]
> shift = ord(shift)
> cipher.append((ord(c) + shift) % 256)
> return ''.join([chr(n) for n in cipher])
>
> def decrypt(ciphertext, password):
> plain = []
> for i, c in enumerate(ciphertext):
> shift = password[i % len(password)]
> shift = ord(shift)
> plain.append((256 + ord(c) - shift) % 256)
> return ''.join([chr(n) for n in plain])
Thanks, this looks simple enough and probably sufficient for my purposes!
I'll see if I'll use this or Paul Rubin's p3.py.
> Is it acceptable if there is a chance (small, possibly vanishingly small)
> that file will identify it as text? As far as I know, even the
> heavyweight "serious" encryption algorithms don't *guarantee* that the
> cipher text will include non-text bytes.
Hmmm, that's a good point, but actually it doesn't matter if 'file'
identifies it as text with a very small probability.
>> and the effort required to convert the file back to the original text
>> file without the password would be equivalent to guessing the password.
>
> If you seriously mean that, then "lightweight encryption" won't do the
> job, because it is vulnerable to frequency analysis, which is easier than
> guessing the password. You need proper, heavy-weight encryption.
Well, probably you are right and I should have been more clear. What
typically people call obfuscation is sufficient for me, as long as the
obfuscation involves a password, something that your solution seems to
do.
>> I'm fully aware of the security implications of this loose
>> specification, but for my purposes this would be a good solution.
>
> Can you explain what your objection to real encryption is?
Not much really, I simply don't want to overkill, that's all. First
and foremost I wouldn't want to introduce a dependency on a 3rd party
module and also wouldn't want to read documentation of a complex API
when all I need are two functions: encrypt( text, password) and
decrypt( text, password ). I really like your solution because that's
all it does.
> The problem is that, as I see it, you've assumed a solution rather than
> state what your requirements are. I'm *guessing* that you are more
> concerned of having to learn to use a complex API,
Well, that's sort of true about learning a complex API :) But it's
also true that I'm not storing anything really valuable in the file
but still wouldn't want to leave it lying around in plain text. In
case I lose the laptop with the file I seriously doubt anybody who
finds it will go through each and every file and try to find what's in
it, even though they look like data files and there is no hint what so
ever that any one of them contains encrypted info. If they see a text
file, well, that can give them ideas, so let's encrypt a little bit.
So basically that's the story, granted, it's not a full specification
or anything like that, it's a description of a vague situation but
that's really all I have :)
Cheers,
Daniel
== 4 of 5 ==
Date: Sat, Jan 9 2010 2:49 am
From: Daniel Fetchinson
> > I have a plain text file which I would like to protect in a very
> > simple minded, yet for my purposes sufficient, way. I'd like to
> > encrypt/convert it into a binary file in such a way that possession of
> > a password allows anyone to convert it back into the original text
> > file while not possessing the password one would only see the
> > following with the standard linux utility 'file':
> >
> > [fetchinson@fetch ~]$ file encrypted.data
> > encrypted.data: data
> >
> > and the effort required to convert the file back to the original text
> > file without the password would be equivalent to guessing the
> > password.
> >
> > I'm fully aware of the security implications of this loose
> > specification, but for my purposes this would be a good solution.
> >
> > What would be the simplest way to achieve this using preferably stock
> > python without 3rd party modules? If a not too complex 3rd part
> > module made it really simple that would be acceptable too.
>
>
>
>
> Daniel,
>
> Here's what looks like another thread veering off into package-ology,
> leaving a stumped OP behind.
>
> "Don't use a random generator for encryption purposes!" warns the
> manual, of which fact I was reminded in no uncertain terms on this forum
> a few years ago when I proposed the following little routine in response
> to a post very similar to yours. One critic challenged me to encode my
> credit card data and post it. Which I did. Upon which another critic
> conjured up the horror vision of gigahertzes hacking my pathetic little
> effort to pieces as I was reading his message. Of the well-meaning kind,
> he urged me to put an immediate stop to this foolishness. I didn't.
>
> No unplanned expenditures ensued.
>
> Or to quote ... I forget who: Fools and innovators are people who don't
> care much about what one is not supposed to do.
>
> So, take or leave what follows for what it is worth or not worth, I am
> confident it works and would serve your purpose, which, as I understand,
> is not to write a text book on cryptology.
>
> Regards
>
> Frederic
>
>
> ##############################
>
>
> import random
>
>
> def crypt_string (string, key, floor = 0, size_of_set = 255):
>
> # key is a number. The sign of that number controls which way the
> process
> # goes. If the number is positive, the result is an encryption. A
> negative
> # number orders a decryption.
>
> if key == 0: return string # No processing
>
> import random
>
> MAX_CHUNK_SIZE = 32
> MIN_CHUNK_SIZE = 16
>
> def process_sequence (sequence):
> s = ''
> for c in sequence:
> r = random.randint (0, size_of_set - 1)
> s += chr (((ord (c) - floor + r * sign) % size_of_set) + floor)
> return s
>
> def shuffle_sequence (sequence):
> random.shuffle (sequence)
> return sequence
>
> sign = (key > 0) * 2 - 1
> random.seed (key * sign)
>
> s = ''
>
> if sign > 0: # forward
>
> i = 0
> while i < len (string):
> random_size_of_chunk = random.randint (MIN_CHUNK_SIZE,
> MAX_CHUNK_SIZE)
> clear_chunk_shuffled = shuffle_sequence (list (string
> [i:i+random_size_of_chunk]))
> code_chunk_shuffled = process_sequence (clear_chunk_shuffled)
> s += code_chunk_shuffled
> i += len (code_chunk_shuffled)
>
> else: # backward
>
> i = 0
> while i < len (string):
> random_size_of_chunk = random.randint (MIN_CHUNK_SIZE,
> MAX_CHUNK_SIZE)
> code_chunk_shuffled = list (string [i:i+random_size_of_chunk])
> real_size_of_chunk = len (code_chunk_shuffled)
> unshuffling_template = shuffle_sequence (range
> (real_size_of_chunk)) # 1. same ...
> clear_chunk_shuffled = process_sequence
> (code_chunk_shuffled) # 2. ... order
> clear_chunk = real_size_of_chunk * [None]
> for ii in range (real_size_of_chunk):
> clear_chunk [unshuffling_template[ii]] =
> clear_chunk_shuffled [ii]
> s += ''.join (clear_chunk)
> i += real_size_of_chunk
>
> return s
>
>
>
> def _crypt_file (in_file, out_file, key):
>
> BUFFER_SIZE = 1024
> while 1:
> s = in_file.read (BUFFER_SIZE)
> if s == '': break
> out_file.write (crypt_string (s, key))
>
>
> def crypt_file (in_file_name, out_file_name, key):
>
> in_file = open (in_file_name, 'rb')
> out_file = open (out_file_name, 'wb')
> _crypt_file (in_file, out_file, key)
> out_file.close ()
Thanks a lot!
Your description is a good fit for my purposes, indeed I don't plan on
writing a text book on encryption :) Also, I don't plan on encrypting
credit card numbers either, all I need is that a file doesn't look
obviously full of ascii characters but something that is generic data.
And since it will not be an entire system, with lots of files of this
type, only we are talking about a single file, there is no incentive
to decipher my algorithm.
I'll take a look at your code, thanks a lot,
Daniel
--
Psss, psss, put it down! - http://www.cafepress.com/putitdown
== 5 of 5 ==
Date: Sat, Jan 9 2010 3:05 am
From: Dave Angel
Anthra Norell wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">Daniel
> Fetchinson wrote:
> > I have a plain text file which I would like to protect in a very
> > simple minded, yet for my purposes sufficient, way. I'd like to
> > encrypt/convert it into a binary file in such a way that possession of
> > a password allows anyone to convert it back into the original text
> > file while not possessing the password one would only see the
> > following with the standard linux utility 'file':
> >
> > [fetchinson@fetch ~]$ file encrypted.data
> > encrypted.data: data
> >
> > and the effort required to convert the file back to the original text
> > file without the password would be equivalent to guessing the
> > password.
> >
> > I'm fully aware of the security implications of this loose
> > specification, but for my purposes this would be a good solution.
> >
> > What would be the simplest way to achieve this using preferably stock
> > python without 3rd party modules? If a not too complex 3rd part
> > module made it really simple that would be acceptable too.
>
>
>
>
> Daniel,
>
> Here's what looks like another thread veering off into package-ology,
> leaving a stumped OP behind.
>
> "Don't use a random generator for encryption purposes!" warns the
> manual, of which fact I was reminded in no uncertain terms on this
> forum a few years ago when I proposed the following little routine in
> response to a post very similar to yours. One critic challenged me to
> encode my credit card data and post it. Which I did. Upon which
> another critic conjured up the horror vision of gigahertzes hacking my
> pathetic little effort to pieces as I was reading his message. Of the
> well-meaning kind, he urged me to put an immediate stop to this
> foolishness. I didn't.
>
> No unplanned expenditures ensued.
>
> Or to quote ... I forget who: Fools and innovators are people who
> don't care much about what one is not supposed to do.
>
> So, take or leave what follows for what it is worth or not worth, I am
> confident it works and would serve your purpose, which, as I
> understand, is not to write a text book on cryptology.
>
> Regards
>
> Frederic
>
> <snip>
The problem I'd have with this approach (not studied in detail), is that
there's no reason that next year's Python must use the same random
number generator, or the same shuffle algorithm. So in order to assure
that "encrypted" archives will be recoverable, one should store with
them the CPython implementation, in source form, just in case that's
needed to reconstruct things.
DaveA
==============================================================================
TOPIC: Porblem with xlutils/xlrd/xlwt
http://groups.google.com/group/comp.lang.python/t/c81ebab2554b9f2f?hl=en
==============================================================================
== 1 of 5 ==
Date: Sat, Jan 9 2010 2:24 am
From: pp
Whenever i run the code below I get the following error:
AttributeError: 'Book' object has no attribute 'on_demand'
WARNING: Failure executing file: <copy.py>
Why is it so??
from xlrd import open_workbook
from xlwt import easyxf
from xlutils.copy import copy
rb = open_workbook('source.xls',formatting_info=True)
rs = rb.sheet_by_index(0)
wb = copy(rb)
ws = wb.get_sheet(0)
plain = easyxf('')
for i,cell in enumerate(rs.col(2)):
if not i:
continue
ws.write(i,2,cell.value,plain)
for i,cell in enumerate(rs.col(4)):
if not i:
continue
ws.write(i,4,cell.value-1000)
wb.save('output.xls')
== 2 of 5 ==
Date: Sat, Jan 9 2010 2:42 am
From: Jon Clements
On Jan 9, 10:24 am, pp <parul.pande...@gmail.com> wrote:
> Whenever i run the code below I get the following error:
>
> AttributeError: 'Book' object has no attribute 'on_demand'
> WARNING: Failure executing file: <copy.py>
>
> Why is it so??
>
> from xlrd import open_workbook
> from xlwt import easyxf
> from xlutils.copy import copy
> rb = open_workbook('source.xls',formatting_info=True)
> rs = rb.sheet_by_index(0)
> wb = copy(rb)
> ws = wb.get_sheet(0)
> plain = easyxf('')
> for i,cell in enumerate(rs.col(2)):
> if not i:
> continue
> ws.write(i,2,cell.value,plain)
> for i,cell in enumerate(rs.col(4)):
> if not i:
> continue
> ws.write(i,4,cell.value-1000)
> wb.save('output.xls')
I suspect your version of xlrd is not up to date (although I thought
on_demand was ages ago!).
Make sure all the tools are the latest versions from http://www.python-excel.org
There's also a dedicated Google Group for the xl* products listed on
that page.
hth
Jon.
== 3 of 5 ==
Date: Sat, Jan 9 2010 2:44 am
From: pp
On Jan 9, 3:42 am, Jon Clements <jon...@googlemail.com> wrote:
> On Jan 9, 10:24 am, pp <parul.pande...@gmail.com> wrote:
>
>
>
> > Whenever i run the code below I get the following error:
>
> > AttributeError: 'Book' object has no attribute 'on_demand'
> > WARNING: Failure executing file: <copy.py>
>
> > Why is it so??
>
> > from xlrd import open_workbook
> > from xlwt import easyxf
> > from xlutils.copy import copy
> > rb = open_workbook('source.xls',formatting_info=True)
> > rs = rb.sheet_by_index(0)
> > wb = copy(rb)
> > ws = wb.get_sheet(0)
> > plain = easyxf('')
> > for i,cell in enumerate(rs.col(2)):
> > if not i:
> > continue
> > ws.write(i,2,cell.value,plain)
> > for i,cell in enumerate(rs.col(4)):
> > if not i:
> > continue
> > ws.write(i,4,cell.value-1000)
> > wb.save('output.xls')
>
> I suspect your version of xlrd is not up to date (although I thought
> on_demand was ages ago!).
> Make sure all the tools are the latest versions fromhttp://www.python-excel.org
>
> There's also a dedicated Google Group for the xl* products listed on
> that page.
>
> hth
> Jon.
yeah all my versions are latest from http://www.python-excel.org .
just checked!!
what could be the problem?
== 4 of 5 ==
Date: Sat, Jan 9 2010 2:52 am
From: Jon Clements
On Jan 9, 10:44 am, pp <parul.pande...@gmail.com> wrote:
> On Jan 9, 3:42 am, Jon Clements <jon...@googlemail.com> wrote:
>
>
>
> > On Jan 9, 10:24 am, pp <parul.pande...@gmail.com> wrote:
>
> > > Whenever i run the code below I get the following error:
>
> > > AttributeError: 'Book' object has no attribute 'on_demand'
> > > WARNING: Failure executing file: <copy.py>
>
> > > Why is it so??
>
> > > from xlrd import open_workbook
> > > from xlwt import easyxf
> > > from xlutils.copy import copy
> > > rb = open_workbook('source.xls',formatting_info=True)
> > > rs = rb.sheet_by_index(0)
> > > wb = copy(rb)
> > > ws = wb.get_sheet(0)
> > > plain = easyxf('')
> > > for i,cell in enumerate(rs.col(2)):
> > > if not i:
> > > continue
> > > ws.write(i,2,cell.value,plain)
> > > for i,cell in enumerate(rs.col(4)):
> > > if not i:
> > > continue
> > > ws.write(i,4,cell.value-1000)
> > > wb.save('output.xls')
>
> > I suspect your version of xlrd is not up to date (although I thought
> > on_demand was ages ago!).
> > Make sure all the tools are the latest versions fromhttp://www.python-excel.org
>
> > There's also a dedicated Google Group for the xl* products listed on
> > that page.
>
> > hth
> > Jon.
>
> yeah all my versions are latest fromhttp://www.python-excel.org.
> just checked!!
> what could be the problem?
Does rb = xlrd.open_workbook('somesheet.xls', on_demand=True) work by
itself?
== 5 of 5 ==
Date: Sat, Jan 9 2010 2:56 am
From: pp
On Jan 9, 3:52 am, Jon Clements <jon...@googlemail.com> wrote:
> On Jan 9, 10:44 am, pp <parul.pande...@gmail.com> wrote:
>
>
>
> > On Jan 9, 3:42 am, Jon Clements <jon...@googlemail.com> wrote:
>
> > > On Jan 9, 10:24 am, pp <parul.pande...@gmail.com> wrote:
>
> > > > Whenever i run the code below I get the following error:
>
> > > > AttributeError: 'Book' object has no attribute 'on_demand'
> > > > WARNING: Failure executing file: <copy.py>
>
> > > > Why is it so??
>
> > > > from xlrd import open_workbook
> > > > from xlwt import easyxf
> > > > from xlutils.copy import copy
> > > > rb = open_workbook('source.xls',formatting_info=True)
> > > > rs = rb.sheet_by_index(0)
> > > > wb = copy(rb)
> > > > ws = wb.get_sheet(0)
> > > > plain = easyxf('')
> > > > for i,cell in enumerate(rs.col(2)):
> > > > if not i:
> > > > continue
> > > > ws.write(i,2,cell.value,plain)
> > > > for i,cell in enumerate(rs.col(4)):
> > > > if not i:
> > > > continue
> > > > ws.write(i,4,cell.value-1000)
> > > > wb.save('output.xls')
>
> > > I suspect your version of xlrd is not up to date (although I thought
> > > on_demand was ages ago!).
> > > Make sure all the tools are the latest versions fromhttp://www.python-excel.org
>
> > > There's also a dedicated Google Group for the xl* products listed on
> > > that page.
>
> > > hth
> > > Jon.
>
> > yeah all my versions are latest fromhttp://www.python-excel.org.
> > just checked!!
> > what could be the problem?
>
> Does rb = xlrd.open_workbook('somesheet.xls', on_demand=True) work by
> itself?
Yes it does. The problem is with line: wb = copy(rb)
here I am getting the error: AttributeError: 'Book' object has no
attribute 'on_demand'
Thanks ..
==============================================================================
TOPIC: table from csv file
http://groups.google.com/group/comp.lang.python/t/1b3241d76be564ad?hl=en
==============================================================================
== 1 of 1 ==
Date: Sat, Jan 9 2010 2:26 am
From: Jon Clements
On Jan 8, 8:31 pm, J <dreadpiratej...@gmail.com> wrote:
> On Fri, Jan 8, 2010 at 13:55, Jon Clements <jon...@googlemail.com> wrote:
> > On Jan 8, 5:59 pm, marlowe <marlowequ...@hotmail.com> wrote:
> >> I am trying to create a table in python from a csv file where I input
> >> which columns I would like to see, and the table only shows those
> >> columns. I have attached an example of the csv file i am using, and
> >> some of the code I have written. I am having trouble converting
> >> variables between lists, dictionaries and tuples. Is there a name for
> >> what I am attempting to do? any help to get me on the right track with
> >> this is appreciated.
>
> >> test.csv
>
> I had to edit that and comma delimit it, because cut and paste gave me
> random numbers/types of whitespace...
>
> [code snipped]
>
>
>
> > This might be a useful starting point (I'm guessing this is what
> > you're after...)
>
> > Let's assume your 'CSV' file is tab separated as it's certainly not
> > comma separated :)
>
> > import csv
> > csvin = csv.reader(open('test.csv'), delimiter='\t')
> > header = dict( (val.strip(),idx) for idx, val in enumerate(next
> > (csvin)) )
>
> > We can use header as a column name->column index lookup eg header
> > ['Open'] == 1
>
> > from operator import itemgetter
> > wanted = ['Open', 'Close'] # Although you'll want to use raw_input and
> > split on ','
> > getcols = itemgetter(*[header[col] for col in wanted])
>
> > getcols is a helper function that'll return a tuple of the columns in
> > the requested order...
>
> > for row in csvin:
> > print getcols(row)
>
> > Loop over the rest of the file and output the required columns.
>
> As someone who knows just enough to be dangerous... what about this:
>
> import csv
>
> reader = open('C:/test.txt','rb')
> data = csv.DictReader(reader,restval='000',restkey='Misc')
[snip]
DictReader works, but what use to bug me was the fact you couldn't
then output the cols in the 'correct' order afterwards, so you had
to store the header row anyway to re-order the rows...
(although admittedly this doesn't affect the OP's question).
However, I see that 2.6+ offers .fieldnames on DictReader objects.
Cheers,
Jon.
==============================================================================
TOPIC: How to get many places of pi from Machin's Equation?
http://groups.google.com/group/comp.lang.python/t/eb0ff21fb5dbcf25?hl=en
==============================================================================
== 1 of 1 ==
Date: Sat, Jan 9 2010 3:31 am
From: "Richard D. Moores"
Machin's Equation is
4 arctan (1/5) - arctan(1/239) = pi/4
Using Python 3.1 and the math module:
>>> from math import atan, pi
>>> pi
3.141592653589793
>>> (4*atan(.2) - atan(1/239))*4
3.1415926535897936
>>> (4*atan(.2) - atan(1/239))*4 == pi
False
>>> abs((4*atan(.2) - atan(1/239))*4) - pi < .000000000000000001
False
>>> abs((4*atan(.2) - atan(1/239))*4) - pi < .0000000000000001
False
>>> abs((4*atan(.2) - atan(1/239))*4) - pi < .000000000000001
True
>>>
Is there a way in Python 3.1 to calculate pi to greater accuracy using
Machin's Equation? Even to an arbitrary number of places?
Thanks,
Dick Moores
==============================================================================
TOPIC: Accessing python from a network share in windows 7
http://groups.google.com/group/comp.lang.python/t/e2d3b424a78df3bd?hl=en
==============================================================================
== 1 of 1 ==
Date: Sat, Jan 9 2010 3:55 am
From: Anssi Saari
aj <mailtome200420032002@gmail.com> writes:
> I access python from a network share. This works fine on XP but on
> windows 7 it throws the following error:
>
> Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit
> (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import random
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "t:\win32\python-2.6.1\lib\random.py", line 871, in <module>
> _inst = Random()
> File "t:\win32\python-2.6.1\lib\random.py", line 96, in __init__
> self.seed(x)
> File "t:\win32\python-2.6.1\lib\random.py", line 110, in seed
> a = long(_hexlify(_urandom(16)), 16)
> WindowsError: [Error 127] The specified procedure could not be found
>
> Is there some security policy that I need to enable/disable to use
> python from a network on windows 7?
Well, there was just a complaint about this sort of thing on a local
newsgroup here. Specifically, someone was trying to execute a Windows
program from a share and every time Windows 7 pops up a warning window
saying that the program is maybe from the evil interwebby and are you
really sure you actually want to run it. So probably that's the
command line version of same.
Solution is apparently specifying your server to be in the local
intranet, in IE's security settings. Apparently there is a non-working
autodetection for what is a local intranet, so specifying the server
IP address by hand in the advanced settigns is the working solution.
==============================================================================
TOPIC: Standardized interpreter speed evaluation tool
http://groups.google.com/group/comp.lang.python/t/a573cd475adf454e?hl=en
==============================================================================
== 1 of 2 ==
Date: Sat, Jan 9 2010 4:50 am
From: Steve Holden
Chris Rebert wrote:
> On Fri, Jan 8, 2010 at 2:25 AM, alexru <taradov@gmail.com> wrote:
>> Is there any standardized interpreter speed evaluation tool? Say I
>> made few changes in interpreter code and want to know if those changes
>> made python any better, which test should I use?
>
> Although apparently undocumented, test.pystone is some sort of
> interpreter benchmark.
>
It's undocumented because it's not considered a representative
benchmark.Sure, you can use it to get *some* idea of relative
performance, but a single program is a very poor tool for such a complex
topic a comparing implementations of a dynamic language.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/
== 2 of 2 ==
Date: Sat, Jan 9 2010 4:50 am
From: Steve Holden
Chris Rebert wrote:
> On Fri, Jan 8, 2010 at 2:25 AM, alexru <taradov@gmail.com> wrote:
>> Is there any standardized interpreter speed evaluation tool? Say I
>> made few changes in interpreter code and want to know if those changes
>> made python any better, which test should I use?
>
> Although apparently undocumented, test.pystone is some sort of
> interpreter benchmark.
>
It's undocumented because it's not considered a representative
benchmark.Sure, you can use it to get *some* idea of relative
performance, but a single program is a very poor tool for such a complex
topic a comparing implementations of a dynamic language.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010 http://us.pycon.org/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/
==============================================================================
You received this message because you are subscribed to the Google Groups "comp.lang.python"
group.
To post to this group, visit http://groups.google.com/group/comp.lang.python?hl=en
To unsubscribe from this group, send email to comp.lang.python+unsubscribe@googlegroups.com
To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.python/subscribe?hl=en
To report abuse, send email explaining the problem to abuse@googlegroups.com
==============================================================================
Google Groups: http://groups.google.com/?hl=en
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home