Re: SQLite or files?

2009-10-05 Thread AggieDan04
On Sep 17, 9:10 am, J Kenneth King ja...@agentultra.com wrote:
 ici iltch...@gmail.com writes:
  I likeshelvefor saving small amounts of data, user preferences,
  recent files etc.
 http://docs.python.org/library/shelve.html

 I like it too, but I hear the great powers that be are going to
 deprecate it.

If you want the convenience of shelve without the limitations of dbm,
you can do:


Implementation of Python shelves using SQLite.

from __future__ import division

import UserDict
import pickle
import sqlite3

def to_db_type(value):

If value's type is supported natively in SQLite, return value.
Otherwise, return a pickled representation.

if value is None or isinstance(value, (int, long, float,
basestring)):
return value
else:
return buffer(pickle.dumps(value))

def from_db_type(value):

Converts a value from the database to a Python object.

if isinstance(value, buffer):
return pickle.loads(value)
else:
return value

class SQLiteShelf(UserDict.DictMixin):

Shelf implementation using an SQLite3 database.

def __init__(self, filename):
self._database = sqlite3.connect(filename)
self._database.execute(CREATE TABLE IF NOT EXISTS Shelf 
   (Key TEXT PRIMARY KEY NOT NULL, Value
BLOB))
self._open = True
def __del__(self):
self.close()
def __getitem__(self, key):
row = self._database.execute(SELECT Value FROM Shelf WHERE
Key=?,
 [key]).fetchone()
if row:
return from_db_type(row[0])
else:
raise KeyError(key)
def __setitem__(self, key, value):
self._database.execute(INSERT OR REPLACE INTO Shelf VALUES
(?, ?),
   [key, to_db_type(value)])
def __delitem__(self, key):
self._database.execute(DELETE FROM Shelf WHERE Key=?, [key])
def keys(self):
Return a list of keys in the shelf.
return [row[0] for row in
self._database.execute(SELECT Key FROM Shelf)]
def close(self):
Commit changes and close the file.
if self._database is not None:
self._database.commit()
self._database.close()
self._database = None
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: arrays in python

2009-09-23 Thread AggieDan04
On Sep 23, 3:02 pm, Simon Forman sajmik...@gmail.com wrote:
 On Wed, Sep 23, 2009 at 1:14 PM, Rudolf yellowblueyel...@gmail.com wrote:
  Can someone tell me how to allocate single and multidimensional arrays
  in python. I looked online and it says to do the following x =
  ['1','2','3','4']

  However, I want a much larger array like a 100 elements, so I cant
  possibly do that. I want to allocate an array and then populate it
  using a for loop. Thanks for your help.
  --
 http://mail.python.org/mailman/listinfo/python-list

 In python they're called 'lists'.  There are C-style array objects but
 you don't want to use them unless you specifically have to.
...
 But if you do this:

 two_dimensional_list = [ [] for var in some_iterable]

 The list of lists you create thereby will contain multiple references
 to the /same/ inner list object.

No, that creates a list of distinct empty lists.  If you want multiple
references to the same inner list, it's

inner_list = []
two_dimensional_list = [inner_list for var in some_iterable]

or

two_dimensional_list = [[]] * num_copies
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Am I doing this wrong? Why does this seem so clumsy (time, datetime vs. DateTime)

2009-09-20 Thread AggieDan04
On Sep 19, 9:22 pm, Schif Schaf schifsc...@gmail.com wrote:
 The other day I needed to convert a date like August 2009 into a
 seconds-since-epoch value (this would be for the first day of that
 month, at the first second of that day).

 In Python, I came up with this:

 
 #!/usr/bin/env python

 import datetime
 import time

 time_in_sse = time.mktime(
     datetime.datetime(2009, 8, 1).timetuple()
 )

(datetime.datetime(2009, 8, 1) - datetime.datetime(1970, 1, 1)).days *
86400

But still, this should be part of the datetime class.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why indentation is use to denote block of code?

2009-09-13 Thread AggieDan04
On Sep 13, 6:27 pm, Steven D'Aprano st...@remove-this-
cybersource.com.au wrote:
 On Sun, 13 Sep 2009 15:15:40 -0700, Chris Rebert wrote:
  In fact it's pretty much impossible to automatically indent Python code
  that has had its indentation removed; it's impossible to know for sure
  where the dedents should occur.

 Just like most other syntactic elements -- if you remove all the return
 statements from Python code, or dot operators, it's impossible to
 automatically add them back in.

 The only difference is that some (badly written?) applications mangle
 leading whitespace, but very few feel free to remove other text on a whim.

 I don't recall actually using a mail client or newsreader that removes
 leading whitespace when posting, but I've occasionally seen posts from
 others with all indentation removed, so presumably such badly-behaved
 applications do exist.

I haven't seen it in a mail client, but it's very common in internet
forums.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: print() a list

2009-09-05 Thread AggieDan04
On Sep 5, 1:51 am, Dero pict...@gmail.com wrote:
 On Sep 5, 2:35 pm, Mark Tolonen metolone+gm...@gmail.com wrote:

  DarkBlue pict...@gmail.com wrote in message

 news:b9c0c4ac-5f8f-4133-b928-9e55ab4b2...@x5g2000prf.googlegroups.com...

  I am trying to get used to the new print() syntax prior to installing
   python 3.1:
...
  Without the following statement, print does not work the new way.  What
  you are printing is a tuple of the two list elements.

  from __future__ import print_function
...
 I thought in 2.6 both print and print() were equally implemented
 without the future import requirement.

That couldn't be done because the print() syntax can't be
distinguished from old-style print with a tuple.

~$ python2.6 -c print(1, 2)
(1, 2)
~$ python3.0 -c print(1, 2)
1 2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is behavior of += intentional for int?

2009-08-29 Thread AggieDan04
On Aug 29, 8:08 am, Paul McGuire pt...@austin.rr.com wrote:
 On Aug 29, 7:45 am, zaur szp...@gmail.com wrote:

  Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
  [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
  Type copyright, credits or license() for more information. a=1
   x=[a]
   id(a)==id(x[0])
  True
   a+=1
   a
  2
   x[0]

  1

  I thought that += should only change the value of the int object. But
  += create new.
  Is this intentional?

 ints are immutable.  But your logic works fine with a mutable object,
 like a list:

Technically, mutability isn't the issue: There's nothing enforcing
that a mutable object HAS to have an __iadd__ method that returns the
same object.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What python can NOT do?

2009-08-29 Thread AggieDan04
On Aug 28, 7:05 pm, Tim Chase python.l...@tim.thechases.com wrote:
 qwe rty wrote:
  i know that an interpreted language like python can't be used to make
  an operating system or system drivers.

 As long as you are willing to write the OS hooks in C, you can
 write the userspace device drivers in Python:

Writing your OS hooks in C isn't a problem because you could write a C
compiler in Python ;-)

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


Re: Read C++ enum in python

2009-08-19 Thread AggieDan04
On Aug 18, 6:03 pm, Ludo
olivier.anospamrnospamnnospamanospamenosp...@affaires.net wrote:
 Hello,

 I work in a very large project where we have C++ packages and pieces of
 python code.

 I've been googleing for days but what I find seems really too
 complicated for what I want to do.

 My business is, in python, to read enum definitions provided by the
 header file of an c++ package.
 Of course I could open the .h file, read the enum and transcode it by
 hand into a .py file but the package is regularly updated and thus is
 the enum.

 My question is then simple : do we have :
         - either a simple way in python to read the .h file, retrieve the c++
 enum and provide an access to it in my python script

Try something like this:



file_data = open(filename).read()
# Remove comments and preprocessor directives
file_data = ' '.join(line.split('//')[0].split('#')[0] for line in
file_data.splitlines())
file_data = ' '.join(re.split(r'\/\*.*\*\/', file_data))
# Look for enums: In the first { } block after the keyword enum
enums = [text.split('{')[1].split('}')[0] for text in re.split(r'\benum
\b', file_data)[1:]]

for enum in enums:
last_value = -1
for enum_name in enum.split(','):
if '=' in enum_name:
enum_name, enum_value = enum_name.split('=')
enum_value = int(enum_value, 0)
else:
enum_value = last_value + 1
last_value = enum_value
enum_name = enum_name.strip()
print '%s = %d' % (enum_name, enum_value)
print

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


Re: Bug in format specification in Python 3?

2009-08-11 Thread AggieDan04
On Aug 11, 3:28 pm, Robert Dailey rcdai...@gmail.com wrote:
 Hello,

 According to the Python 3.1 documentation, I can have a format
 specification like so:

 print( 'This is a hex number: {:#08x}'.format( 4 ) )

 This will print:

 This is a hex number: 0x04

 I notice that the '0x' portion is counted in the width, which was
 specified as 8. This seems wrong to me. Is this by design? If so, why?
 I expect that the width portion to only apply to the input + padding
 only. I don't consider the '0x' portion part of the padding. But maybe
 it is...

It's unintuitive to me, too, but it's the same thing that Python 2.x
did:

 print '%#08x' % 4
0x04

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


Re: random number including 1 - i.e. [0,1]

2009-06-09 Thread AggieDan04
On Jun 9, 4:33 pm, Esmail ebo...@hotmail.com wrote:
 Hi,

 random.random() will generate a random value in the range [0, 1).

 Is there an easy way to generate random values in the range [0, 1]?
 I.e., including 1?

You could do random.uniform(0, 1.0002).  Due to floating-
point rounding, there are TWO original values that would return 1.0:
0.99978 or 0.99989; this may give you more
1.0's than you expected, and that's not even considering that Python's
PRNG could be non-uniformly-distributed over the 53-bit fractions.  If
you're nit-picky enough to care about the less-than-winning-the-
lottery chance of getting the maximum random value in the first place,
this might be a problem.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 4 hundred quadrillonth?

2009-05-21 Thread AggieDan04
On May 21, 5:45 pm, norseman norse...@hughes.net wrote:
 seanm...@gmail.com wrote:
  The explaination in my introductory Python book is not very
  satisfying, and I am hoping someone can explain the following to me:

  4 / 5.0
  0.80004

  4 / 5.0 is 0.8. No more, no less. So what's up with that 4 at the end.
  It bothers me.

 ==

 Machine architecture, actual implementation of logic on the chip and
 what the compiler maker did all add up to creating rounding errors. I
 have read where python, if left to its own, will output everything it
 computed. I guess the idea is to show
         1) python's accuracy and
         2) what was left over
 so the picky people can have something to gnaw on.

If you want to be picky, the exact value is
0.8000444089209850062616169452667236328125 (i.e.,
3602879701896397/2**52).  Python's repr function rounds numbers to 17
significant digits.  This is the minimum that ensures that float(repr
(x)) == x for all x (using IEEE 754 double precision).

 Astrophysics, Astronomers and like kind may have wants of such.
 If you work much in finite math you may want to test the combo to see if
   it will allow the accuracy you need. Or do you need to change machines?

The error in this example is roughly equivalent to the width of a red
blood cell compared to the distance between Earth and the sun.  There
are very few applications that need more accuracy than that.


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


Re: 4 hundred quadrillonth?

2009-05-21 Thread AggieDan04
On May 21, 5:36 pm, Chris Rebert c...@rebertia.com wrote:
 On Thu, May 21, 2009 at 2:53 PM, Carl Banks pavlovevide...@gmail.com wrote:
  On May 21, 2:05 pm, seanm...@gmail.com wrote:
  The explaination in my introductory Python book is not very
  satisfying, and I am hoping someone can explain the following to me:

   4 / 5.0

  0.80004

  4 / 5.0 is 0.8. No more, no less.
...

 The `decimal` module's Decimal type is also an option to consider:

 Python 2.6.2 (r262:71600, May 14 2009, 16:34:51)
  from decimal import Decimal
  Decimal(4)/Decimal(5)

 Decimal('0.8')

 Decimal(1) / Decimal(3) * 3
Decimal(0.)
 Decimal(2).sqrt() ** 2
Decimal(1.999)

Decimal isn't a panacea for floating-point rounding errors.  It also
has the disadvantage of being much slower.

It is useful for financial applications, in which an exact value for
0.01 actually means something.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Into itertools

2009-04-26 Thread AggieDan04
On Apr 26, 11:32 am, bearophileh...@lycos.com wrote:
 Some idioms are so common that I think they deserve to be written in C
 into the itertools module.

 1) leniter(iterator)
...
 2) xpairwise(iterable)
...
 3) xpairs(seq)
...
 4) xsubsets(seq)
...

Good suggestions.  Another useful function I'd like to see in
itertools is the Cartesian product.  This can be implemented as:

def cartesian_product(*args):
Iterates over the Cartesian product of args[0], args[1], ...
if not args:
return
elif len(args) == 1:
for item in args[0]:
yield (item,)
else:
for item in args[0]:
for item2 in cartesian_product(*args[1:]):
yield (item,) + item2
--
http://mail.python.org/mailman/listinfo/python-list


Re: and [True,True] -- [True, True]?????

2009-04-20 Thread AggieDan04
On Apr 20, 2:03 am, bdb112 boyd.blackw...@gmail.com wrote:
 Is there any obvious reason why
 [False,True] and [True,True]
 gives [True, True]

 Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit
 (Intel)]

X and Y == (Y if X else X)
X or Y == (X if X else Y)

[False, True] is true, so the and operator returns the second argument.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert \n and \t symbols to new lines and tabs?

2009-04-13 Thread AggieDan04
On Apr 13, 6:30 pm, DSblizzard dsblizz...@gmail.com wrote:
 How to convert string with \n and \t symbols to natural string - with
 new lines and tabs?

'String with tab\\t and newline\\n'.decode('string-escape')
--
http://mail.python.org/mailman/listinfo/python-list


Re: Floor value in math operators

2009-04-09 Thread AggieDan04
On Apr 8, 12:08 pm, David Smith d...@cornell.edu wrote:
 Avi wrote:
  Hi,

  This will be a very simple question to ask all the awesome programmers
  here:

  How can I get answer in in decimals for such a math operator:

  3/2

  I get 1. I want to get 1.5

  Thanks in advance,
  Avi

 I'm going to assume your operands are variables instead of numeric
 literals.  Why not consider doing a type conversion to float or Decimal
 and then perform the division?

Because float(x) and Decimal(x) fail for complex numbers and lose
precision if x is a rational or a multi-precision float.
--
http://mail.python.org/mailman/listinfo/python-list


Re: newbie: precision question

2009-03-20 Thread AggieDan04
On Mar 20, 10:12 pm, Lada Kugis lada.kugis@@gmail.com wrote:
 I'm a newbie learning python, so forgive for, what may seem to some,
 like a stupid question.

 I understand the basic integer and fp type, but what I'm having a
 little trouble are the long type

An int is limited to 32 or 64 bits.  A long can be as big as you
need it to be.

People didn't like OverflowErrors very much, so Python 2.2 allowed
operations on ints to return longs, and Python 3.0 will phase out
int entirely, but long is being renamed to int.

 and infinite precision type.

 Also, when I do

  math.pi - (math.sqrt(math.pi))**2.

 I get

 4.4408920985006262e-016

 Please, could someone in just a few words, in newbie speak, explain
 why does that happen ? And what do the types actually mean ? What I
 mean, how can something have infinite precision but still not return
 zero as a result.

Because float isn't an infinite-precision type.  Therefore, it has
rounding errors.

Doesn't even have anything to do with the binary number system.  You
may familar with decimal calculators in which (1/3) * 3 = 0. *
3 = 0. != 1.  Same kind of thing.

 (Btw, I always thought floating points had precision
 up to 8 significant digits, doubles 16).

Single and double precision are *both* floating point.  It's just that
C and Python disagree on which of those the name float refers to.
--
http://mail.python.org/mailman/listinfo/python-list