[Tutor] Iterating a dict with an iteration counter? How would *you* do it?

2013-02-04 Thread Modulok
List,

Simple question: Is there a common pattern for iterating a dict, but also
providing access to an iteration counter? Here's what I usually do (below). I'm
just wondering if there are other, more clever ways::

data = {'a': apple, 'b': banana, 'c': cherry}
i = 0
for k,v in data.items():
print(i: %s, k: %s, v: %s % (i,k,v))
i += 1

Another variant, same idea::

data = {'a': apple, 'b': banana, 'c': cherry}
for i,k,v in zip(range(len(data)), data.keys(), data.values()):
print(i: %s, k: %s, v: %s % (i,k,v))


How would you do it?
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Iterating a dict with an iteration counter? How would *you* do it?

2013-02-04 Thread Modulok
Hmm.. no kidding. Well, at least I knew I was over-complicating it.

Cheers!
-Modulok-


On 2/4/13, Dave Angel da...@davea.name wrote:
 On 02/04/2013 12:13 PM, Modulok wrote:
 List,

 Simple question: Is there a common pattern for iterating a dict, but also
 providing access to an iteration counter? Here's what I usually do
 (below). I'm
 just wondering if there are other, more clever ways::

  data = {'a': apple, 'b': banana, 'c': cherry}
  i = 0
  for k,v in data.items():
  print(i: %s, k: %s, v: %s % (i,k,v))
  i += 1

 Another variant, same idea::

  data = {'a': apple, 'b': banana, 'c': cherry}
  for i,k,v in zip(range(len(data)), data.keys(), data.values()):
  print(i: %s, k: %s, v: %s % (i,k,v))


 How would you do it?
 -Modulok-

 enumerate()


 for i, (k, v) in enumerate(data.items()):

 --
 DaveA
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] optparse.OptionParser options in alphabetical order in help display

2012-12-18 Thread Modulok
 Does anybody know if there is a way to make --help option to display
 options in alphabetical order?

I know this sounds like spam and doesn't answer your question, (sorry!) but you
should check out the third part module 'docopt'. It is *extremely* simple and a
lot more flexible. It made me actually want to write command line interfaces
again.


http://www.youtube.com/watch?v=pXhcPJK5cMc
http://docopt.org/

Again, sorry for the spam but everyone I've shown has switched and were glad
they did. It's also on PyPi and github. In fact, the github page is probably the
best place to check it out.

-Modulok-

On 12/18/12, rail shafigulin rail.shafigu...@gmail.com wrote:
 Does anybody know if there is a way to make --help option to display
 options in alphabetical order? Right now it displays options in the order I
 added them. I'm using Python 3.1

 Any help is appreciated.
 Thanks.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] code to generate my own text captchas

2012-10-24 Thread Modulok
On 10/24/12, Tsila Hassine tsila.hass...@gmail.com wrote:
 Hello all,
 I am looking for simple python code that will take a given string and
 distort it, captcha like. it is for artistic purposes, so no verification
 required. I just need the image q text distortion code.
 Thanks!!!
 tsila

You might look into writing a shell script or even python script wrapped around
ImageMagick.

-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Passing arguments to running a python script on a remote machine from a python script on local machine .

2012-09-20 Thread Modulok
 I forgot you need to escape special characters in the arguments. You
 can add quoting and escape special characters at the same time with
 the undocumented function pipes.quote:

 import pipes

 args = tuple(pipes.quote(arg) for arg in (arg1, arg2, arg3))
 cmd = 'python test.py %s %s %s' % args

 Notice there are no longer quotes around each %s in cmd. Python 3.3
 will have shlex.quote:

 http://docs.python.org/dev/library/shlex.html#shlex.quote

Why is ``pipes.quote`` undocumented? It's useful.

-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] [Semi-OT] Yes or no on using a Graphical IDE?

2012-09-15 Thread Modulok
 Hey all, not trying to contribute to the flames of one graphical IDE over
 another. I'm just trying to figure out if they are worth the learning
 curve? I have been doing most of my work in vi and the graphical IDE I'm
 supposed to use for a class keeps adding crap that I have to erase, and I
 have to move my hands to use the GUI parts instead of just typing.

 Is there a point in which a GUI IDE becomes more of a help than a
 hindrance?

 Thanks!

 Leam

Leam,

It's really a personal taste. I can't speak for others, but this is my basic
setup: I use a highly customised graphical text editor (jEdit) with several
plugins specific to what I'm doing. I guess it kind of equates to a lightweight
IDE. I combine this with an ssh connection to a FreeBSD box for all the
wonderful *nix command line tools, scripts, debuggers, etc that are out there.

I like the idea of an IDE, but haven't met one I really care for. I much prefer
a GUI editor over a purely console based one. That is, I like the ability to
use a mouse to aid in quickly moving text around. I also like the sub-pixel
anti-aliased fonts that you don't always get on a console. (Of course, this
depends on the console.) You can do most things with command line editors,
(some even support using a mouse) but I never found it to be as fast. Again,
it's personal and I'm probably getting off the subject. This is more of a
console vs. GUI debate.

I short, I'd say use whatever you're comfortable with. After that, use what
your friends/co-workers use. The popup auto-complete for class names or
variable names in IDE's is nice and can often save you from having to look
something up, but it isn't critical. Console tools like ipython can make up for
some of that, but even so that's not something I generally write code in.

Perhaps others have more insight.
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Does anyone use UML?

2012-09-13 Thread Modulok
List,

Does anyone use UML (Unified Modeling Language) with python? If so, what tools
do you use? Is it worth the added effort?

-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Genetic module recommendations?

2012-08-18 Thread Modulok
List,

I'm looking for a good genetic module. (Stable, well documented, pythonic,
etc.)

I'm writing a breeding simulator where users select parent organisms to breed
based on traits they favor, e.g: eye color, height, etc. The human player is
the fitness function. I guess this is artificial selection? After breeding
the user gets an offspring which carries traits from its parents.

It's only a game and a crude approximation of nature at best. However, the
algorithm has to be stable enough this can go on for several hundred
generations without entropy reducing to the point of haulting evolution. On the
other hand, I don't want so much entropy that it's reduce to a random search.

Before I write my own, I thought I'd ask to see if there was a third party,
de-facto standard Python genetic module. Or at least one that is highly
recommended.

Any suggestions?

Thanks!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] specifying my default python installation

2012-08-17 Thread Modulok
On 8/17/12, debbym de...@glance.net wrote:
 I am new to both freebsd and python.
 I have python 2.6 and 3.2 both installed on freebsd.
 python runs python 2.6 and I need to use python3.2 to run python 3.2
 Do I need to do something to make python 3.2 the default?

FreeBSD doesn't have an 'alternatives' system like debian flavors. However,
there's nothing wrong with your install. I run FreeBSD on several boxes. On
this box I have python 2.6, 2.7, and 3.2 installed. My default 'python'
executable is a symlink that points to /usr/local/bin/python, which itself is
version 2.6. (The box I'm on is FreeBSD 8.1)

If I want a program to run in python3.2, I put something like this (or
similar) as the shebang line at the top of the file:

#!/usr/bin/evn python3.2

Or to get the interpretter just type 'python3.2'. Don't worry about the shebang
lines being cross platform either; Once you package up your scripts into python
packages, using distutils or similar, all shebang lines will be stripped. Upon
re-installation on the target platform they'll be replaced appropriately. (In
fact, some platforms even put 'env' in /bin instead of FreeBSD's /usr/bin.)

I would also recommend against changing the default 'python' symlink, as some
tools may depend on it being at a specific version. One I can think of off the
top of my head is the third party `xps` tool for searching ports. This is most
notable when talking about python2.x vs. the 3.x branch, as python 3 broke
backward compatibility with things like print statements becoming print
functions.

If you find it irritating to have to type 'python3.2' instead of just 'python',
you could create an alias for your shell, so that 'python' is aliased to
'python3.2'. I use tcsh, so I in my case my $HOME/.cshrc file might look
something like this:

alias python /usr/local/bin/python3.2

Then I would type 'source .cshrc' or logout and back in for changes to take
affect. As an alternative, you could create a symlink from your own bin
directory instead. For example:

cd
mkdir bin
ln -s /usr/local/bin/python3.2 ./bin/python

This should work once you type 'rehash' (in tcsh) or logout and log back in.
Most default installs will list the 'bin' directory, found in a given user's
home directory, on the default $PATH. You can verify this by typing 'echo
$PATH' and making sure '/home/you/bin' is listed. This isn't as good of an
option as simply using the alternate shebangs, as it affectively replaces your
version of python with the version you choose, but it will work.

Finally, if you want to get carried away, you can install a virtual python as
mentioned.

For even more options, you might subscribe to questi...@freebsd.org ;)
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Confusion with Python, Bash and Command Prompt

2012-08-09 Thread Modulok
...
 My Question:
 Is it true that doing that is as same as doing #!/usr/bin/env python
 on Unix? Because I think that the matter of shebang is limited to Bash
 and Windows don't have a bash, it has a Command Prompt. And I don't
 think such thing happens in Windows.

It has nothing directly do with bash. It has to do with the operating system's
'program loader'. It's the low level code responsible for setting up an
execution environment for a new process. It looks for environment variables,
etc. For example on FreeBSD most shebang parsing defined in envopts.c.

Basically, whenever you request a file to be executed, the program loader (not
your shell) looks at the first line of the file for a shebang. If found, it
executes the file the shebang line references and passes the path to the
current script file as the first argument.

That said, different operating systems' program loaders', regardless of the
shell you're using (be it bash, tcsh, sh, etc), will process shebang lines
differently. Some ignore them entirely. The syntax can even vary slightly from
one OS to another (and not just the file paths).

So does it apply to Windows? No. Windows has no concept of shebang lines. File
types are determined exclusively their extensions, as is the executability of a
file. (There's a registry looking that occurs to determine what program to pass
the file to.)

If you rename a python script from foo.py to foo.jpg, windows will attempt to
open it in an image viewer, regardless of any shebang lines present. (Contrast
this with most unix-like flavors where extensions are meaningless.
Executability is determined by a file-system level permission bit and the
interpreter is determined by the program loader reading shebang lines. The file
would be passed to the python interpretter, assuming a correct shebang.)

You are right in your assumption; It does not apply to Windows. The tutorial is
incorrect.

-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] While learning Py: To IDE or not to IDE?

2012-05-20 Thread Modulok
 Since you are using Solaris, I expect your options for IDEs are limited.
 You're probably best off using Unix as your IDE:

 http://blog.sanctum.geek.nz/series/unix-as-ide/

 which is my preferred solution. There's very little I can't do between my
 editor and a terminal window with a few tabs open.


Apparently I'm not alone.

I've not found an IDE I liked much either. They all feel kind of
bloated with 37+
useless features I don't need. Instead, I use jEdit, a few choice plugins and
an ssh connection to a command shell on a FreeBSD file server. (The fact that
jEdit was written in java is irritating form a licensing perspective on some
OS's but the editor itself is top notch.)

A decent editor combined with a good command shell is all I've ever needed. If
I'm on the console alone, for minor editing I just use nano.

Personally, and this is just me, I've felt that big IDE's add a lot of
interface and fluff but not a lot of substance. One of the benefits of learning
a few basic editors and how to really use a command shell, is that it doesn't
matter what brand of linux/BSD/unix you're on, you're still pretty much at
home. That said, IDE's still have their place, especially when writing a lot
of GUI stuff.

Learning to use a command line at first feels really clunky and primitive, but
eventually it eclipses most GUI's and IDE's in terms of speed and the tools
available. You can also ooze right into system administration without much
effort.


But again, that's just me :p
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] TypeError: 'int' object is not callable

2012-05-16 Thread Modulok
On 5/16/12, Greg Christian glchrist...@comcast.net wrote:
 Can anyone tell me what I am doing wrong here. When trying to call the
 factors function from main with x = factors(Tn), getting the error message:
 “TypeError: 'int' object is not callable”? Any help would be appreciated.
 Thanks.


 def factors(n):
 L = []
 for i in range(1, int(n ** 0.5) + 1):
 if (n % i == 0):
 L.append(i)
 return L

 def main():
 factors = 0
 counter = 0
 L = []
 while len(L)  50:
 counter += 1
 L.append(counter)
 Tn = sum(L)
 x = factors(Tn)
 #print x
 print(sum(L))


 if __name__ == '__main__':
 main()

You declared 'factors' as a variable on line 1 in main::

factors = 0

This masks the call to the function 'factors'. You get the error because you
assigned factors an integer and you cannot 'call' an integer. The easiest
solution is to use another name for the variable 'factors' instead.

-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there space a between #! and /usr/bin/env python ?

2012-05-02 Thread Modulok
On 5/1/12, Santosh Kumar sntshkm...@gmail.com wrote:
 Its getting complicated now. Will it effect or not?

No. It won't. Spaces between '#!' and '/foo/bar/whatever' are ignored.

Long Answer:

Don't worry about it. For example, on one of my Ubuntu linux boxes there's
69 rc files shipped with the OS that use the variant: '#! /bin/sh' (with
space). And there's 26 that use the variant '#!/bin/sh' without a space; It
really doesn't matter. (For the curious, you can find out like this)::

grep --ignore-case --regex '^#!/. *' --recursive /etc/rc* | wc

And this respectively::

grep --ignore-case --regex '^#!/.*' --recursive /etc/rc* | wc

On my FreeBSD server all files shipped with the OS don't uses spaces. They're
just '#!/bin/sh'. However, some of my own scripts do, and they work regardless.
i.e. It doesn't really matter. On Windows they're ignored entirely.


-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to have the name of a function inside the code of this function?

2012-04-06 Thread Modulok
On 4/6/12, Karim kliat...@gmail.com wrote:

 Hello all,


 I have :

  def foo():
 print( getattr(foo, 'func_name'))

 Where I get the name of the function but I add to give the name of this
 function. Indeed it is not very helpful...
 I checked the globals() but how I can do to get
 globals()['toto'].func_name. This is not more helpful ;o)

 If you have any idea to get the caller name inside the caller.


The following works, but only on implementations which provide stack frame
support. As the docs kindly point out:

...this isn't guaranteed to exist in all implementations of Python.

Example code:


import inspect
def foo():
'''Print my own name.'''
frame_info = inspect.getframeinfo(inspect.currentframe())
print(frame_info.function)


foo()


That said, there's probably a better way to solve whatever bigger problem
you're trying solve.

-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] breeds of Python .....

2012-03-31 Thread Modulok
After following the reading suggestions, I soon found myself looking
at quite a few code examples that would only run under a particular
version of python.  Finally, I converted the example that I was
working on to run under Python3.  I just wondered if you guys would
advise a newbie like me to concentrate on Python3 or stay with Python2
and get into bad habits when it comes to change eventually?  Apart
from the print and input functions, I haven't so far got a lot to
re-learn.

Kind regards,Barry.


Barry,

If you're just starting out, go with 3.x. If you have a need for some third
party modules that aren't yet available for 3.x, you'll have to stick with 2.x.
Most beginner tutorials will work without changes, except for the print
statement is now a function, e.g:

print foo

Is now:

print(foo)

There isn't a whole lot of difference in syntax to learn. Some modules have
been renamed, some module functions re-worked, etc. Probably the biggest change
is the move to all unicode strings. One thing you can do if you're running 2.x
but want to get into the 3.x swing of things is turn on 3.x warnings. It will
tell you if you did something the 2to3 tool can't automatically fix:

python2.6 -3

If you want, you can actually use the 3.x style print function and true
division when using 2.x by putting this at the top of your code::

from __future__ import print_function
from __future__ import division

Now in 2.x, just like 3.x this will raise an exception:

print foo #-- Now fails in 2.x
print(foo)#-- Works.

-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Syntax error help

2012-03-30 Thread Modulok
On 3/30/12, chris knarvik x23ch...@gmail.com wrote:
 Alright i have been trying to right a (relatively) simple to calculate area
 and volume below is my current working code
 def areamenu():
 print 'Square (1)'
 print 'triangle (2)'
 print 'rectangle (3)'
 print 'trapazoid (4)'
 print 'circle (5)'

 def squareacalc():
 sidelength = input('enter side length: ')
 print ' the side length is' sidelength ** 2

 def displaymenu():
 print 'please make a selection';
 print 'Area (1)';
 choice = input(raw_input('enter selection number'):
 if (choice == 1):
 Areamenu():

 else:
 print 'choice' , choice, ' is wrong try again'

 def selctiona():
 Areamenu();
 choicea = input(raw_input'enter selection');
 if (choicea == 1):
 squareacalc()



  print 'good bye'

 I keep getting this error
 Traceback (most recent call last):
   File pyshell#3, line 1, in module
 import Area
   File C:\Python27\Area.py, line 10
 areamenu()
^
 SyntaxError: invalid syntax

 can anyone tell me what im doing wrong i cant see the problem
 help would be appreciated

Chris,

Your code has numerous problems. First, the only lines that should end in a
colon ':' are lines that define something, i.e. class and function signatures,
etc. Your code has them sprinkled in places where they really don't belong. For
instance:

choice = input(raw_input('enter selection number'):  #-- No.

Additionally, python statements are almost never terminated with a semicolon
';'. Your code has those in random places as well. Python statements *can* be
semicolon terminated, but this should *only* be used if there is more than one
statement per line. (Generally a discouraged practice, unless in the case of a
list comprehensions):

choicea = input(raw_input'enter selection'); #-- Not needed.

The other problem I see is a lot of mis-matched parentheses. For instance your
code has places where there are two opening parentheses, but only one closing
parenthesis:

choice = input(raw_input('enter selection number'):

Should be:

choice = input(raw_input('enter selection number'))

However, the above line is pretty nasty. It's making an unnecessary function
call. Above, its waiting for user input to the 'input' function, and using the
return value of the 'raw_input' function for that input, which itself is
waiting for user input. i.e. an input waiting for an input. It should instead
be something like this:

choicea = input('enter selection: ')

*If* you decide to use the 'raw_input()' function instead, remember to
type-cast the value that gets entered. By default with 'raw_input()' it is
interpreted as a string and not an integer. Thus, the comparison 'if (choicea
== 1)' wouldn't work with 'raw_input()' expected.

This is a problem as well:

print ' the side length is' sidelength ** 2

The print statement only takes a single argument, or multiple arguments *if*
they are comma separated, e.g:

print ' the side length is', sidelength ** 2

However, this whole thing would be better written using string substitution::

print ' the side length is %s' % (sidelength ** 2)

This is also incorrect:

Areamenu()

Your code defines a function named 'areamenu', not one named 'Areamenu'.
Remember, python is case sEnsItiVe. e.g: Foo() and foo() are different.

Good luck!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] tabbed output

2012-02-12 Thread Modulok
On 2/12/12, Michael Lewis mjole...@gmail.com wrote:
 I am having a weird issue. I have a print statement that will give me
 multiple outputs separated by a tab; however, sometimes there is a tab
 between the output and sometimes there is not. It seems sort of sporadic.
 My code is below and two sample outputs are below that (one that works how
 I expect, and the other showing the issue (tab separation not occurring
 between all pieces of the output) What is going on?

 def CheckNames():
 names = []
 for loop in range(1,4):
 while True:
 name = raw_input('''Name #%s: ''' %(loop))
 if name not in names:
 names.append(name)
 break
 print '%s is already in the data. Try again.' %(name)
 sorted_names = sorted(names)
 for element in list(sorted_names):
 print 'Hurray for %s!\t' %(element),

 Sample Output1:

 Name #1: mike
 Name #2: bret
 Name #3: adam
 Hurray for adam!Hurray for bret!   Hurray for mike!

 Sample Output2(there is a tab between output 2  3, but not 1  2):

 Name #1: abe
 Name #2: alan
 Name #3: adam
 Hurray for abe! Hurray for adam!  Hurray for alan!


You should use spaces, not tabs. Tabs only align with tab stops, which will
depend on the length of the words (names). To make it easy to use spaces
instead, use the 'format()' method available on string objects. A one-line
modification of your could would look like this::

def CheckNames():
names = []
for loop in range(1,4):
while True:
name = raw_input('''Name #%s: ''' %(loop))
if name not in names:
names.append(name)
break
print '%s is already in the data. Try again.' %(name)
sorted_names = sorted(names)
for element in list(sorted_names):
print {value:30}.format(value=Hurray for %s! % element),
# The line above is all that was changed.


The result, is that 'value' will be output as left-aligned '', and a minimum
of 30 characters wide '30'. The 'value' is specified as a keyword argument to
the format() method. In the example above, 'value' is also making use of
python's older string formatting method. Using a monospaced font, your output
will always be lined up, as long as the 'value' string never exceeds 30
characters wide.

You can optionally *not* specify the 'value' variable and instead use a
positional argument to the format method like this, but it makes it less clear
what you're doing::

print {0:30}.format(Hurray for %s! % element),

As a final note, if 'CheckNames' is a function and not a method, it should be
all lowercase, or use_underscores rather than camelCase. This is not enforced
by python, but is kind of the de-facto standard.

Read more about the format method here:

http://docs.python.org/library/string.html#formatspec
http://docs.python.org/library/string.html#formatstrings


-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Database Scripting

2012-02-08 Thread Modulok
The closest thing you'll find will probably be the third party module
'sqlalchemy'. You can install it via easy_install or pip. If that doesn't meet
your needs I'm not sure what else would. (But would love to hear about it.)

-Modulok-

On 2/8/12, Brad Hudson brad.hud...@gmail.com wrote:
 Can someone provide information on the best modules/python tools to use for
 general database scripting? I'm interested in something that works across
 the board for Oracle, MySQL, MS SQL Server, and DB2. I was hoping a good
 generic ODBC module would be out there, but I'm having difficulty locating
 one that works for all.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] decimal precision in python

2012-02-06 Thread Modulok
For money, you should probably use the builtin module 'decimal' instead:

http://docs.python.org/library/decimal.html

There's also the third party module 'mpmath' which provides arbitrary precision
floating point arithmetic.

http://mpmath.googlecode.com/svn/trunk/doc/build/index.html

-Modulok-

On 2/6/12, Kapil Shukla shukla.ka...@gmail.com wrote:
 i tried writing a small code to calculate option price using the binomial
 tree model. I compared my results with results of the same program in
 excel. There seems to be a minor difference due to decimal precision as
 excel is using 15 decimal precision and python (both 2.7 and 3.1) using 11.
 (at least that's what shown on shell)

 can some one guide me whats the equivalent of using a double datatype on
 python and i can't use long() in 3.1 any more.

 Please also suggest a free editor for python which can at least repeat
 previous command with a key stroke

 regards
 kapil

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Error Checking/Defensive Programming

2012-01-25 Thread Modulok
It's easier to ask for forgiveness than permission. Ask yourself Is this an
action that could fail in a specific way? If yes, you need try/except. If no,
you probably need if/else. When dealing with data such as user input or opening
files and so forth, use try/except. When those actions fail, they fail in
highly specific ways. (No read/write access, no space, invalid user data, etc.)

while True:
try:
number = float(raw_input(Enter a number between 1-10: ))
except ValueError:
print(Error: You need to enter a number.)
else:
# If they got this far, we have a number of some kind.
# Check that it is in the valid range:
if number = 10 and number = 1:
# It's valid, stop the loop!
break;
else:
print(Error: Number must be in the range of 1-10.)
print(Yay, the number %.2f! % number)


On the other hand, if I was looking for an internal condition, I would use
if/else:

win_number = 3
if number == 3:
print(You won!)
else:
print(You loose!)


The rule doesn't always hold true, but it's a general guideline.

Hope that helps.
-Modulok-

On 1/25/12, Michael Lewis mjole...@gmail.com wrote:
 Hi everyone,

 I am new to python and have a noob question.

 Is it generally better to use try/except/else statements or if/elif/else?
 Or, is there a time and place for each?

 For a simple example, assume I want a user to enter a number

 1) try:
number = float(input('enter a number: ')
except ValueError:
print('enter a number.')
else:
print('you entered a number')

 *OR*
 *
 *
 2) number = float(input('enter a number: ')
 if number =0 or  0:
 print('you entered a number')
 else:
  print('enter a number.')

 Thanks for the help.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Simple Question (I Hope)

2012-01-14 Thread Modulok
On 1/14/12, Chris Kavanagh cka...@msn.com wrote:
 I was looking at this code from the Python Docs
 (http://docs.python.org/library/email-examples.html), trying to learn
 how to send email from a Pyhton script. Anyways, part of this code
 confused me. Here's the script:

 1 # Import smtplib for the actual sending function
 2 import smtplib
 3
 4 # Import the email modules we'll need
 5 from email.mime.text import MIMEText
 6
 7 # Open a plain text file for reading.  For this example, assume that
 8 # the text file contains only ASCII characters.
 9 fp = open(textfile, 'rb')
 10 # Create a text/plain message
 11 msg = MIMEText(fp.read())
 12 fp.close()
 13
 14 # me == the sender's email address
 15 # you == the recipient's email address
 16 msg['Subject'] = 'The contents of %s' % textfile
 17 msg['From'] = me
 18 msg['To'] = you
 19
 20 # Send the message via our own SMTP server, but don't include the
 21 # envelope header.
 22 s = smtplib.SMTP('localhost')
 23 s.sendmail(me, [you], msg.as_string())
 24 s.quit()

 What I don't understand is lines 16-18, more specifically the
 msg['Subject'] format. I thought this was only done with dics??
 Obviously the variable msg isn't a dic, so how can this be done??

 I actually put lines 11, 16,17,18, in the interpreter, then printed out
 msg, so I get what it's doing, but my question still stands. How can one
 do this, when I thought it could only be done with dictionaries???

Chris,

I haven't looked at the module, but you should be aware that you can have
user-defined classes which behave like builtin types, with their own customised
features. You can also subclass a dict and customise it to do whatever. That
said, as long as an object provides dictionary access methods, it can be
treated like a dict in every respect. As far as python is concerned, if it
looks like a duck and quacks like a duck - it's a duck. (Or in this case a
dict.) It doesn't matter what the 'type' is, what is important is how you can
access it.

Here's an example::


# example.py
# The following exapmle could be done more cleanly by subclassing the builtin
# dict type, but for illustrative purposes this was not done. Instead, we show
# several dict methods being defined on our dict-like class 'Foo':

class Foo(object):
'''This object behaves like a builtin dict that refuses the value red.'''
def __init__(self, x, y):
self.x = x  #-- We can have our own properties too.
self.y = y
self.data = {}

def __getitem__(self, key):
'''Return 'key' when accessed like self[key]'''
return self.data[key]

def __setitem__(self, key, value):
'''Sets self[key] =  value'''
if value == red:
raise ValueError(Red is not acceptable!)
else:
self.data[key] = value

def items(self):
'''These could do whatever you want.'''
return self.data.items()

def keys(self):
'''These could do whatever you want.'''
return self.data.keys()

def values(self):
'''These could do whatever you want.'''
return self.data.values()


#===
# Now let's use it!
#===

a = Foo(x=3, y=5)

# Is 'a' a dict?
# False
print type(a)

# Is it an instance of a dict?
# False
print isinstance(a, dict)

# Can we *use* a like a dict?
a['sky'] =  orange
a['ocean'] = blue

for k,v in a.items():
print k,v

for v in a.values():
print v

## Yes! Yet, it has it's own set of unique features:

print a.x   #-- Prints 3
print a.y   #-- Prints 5
a['blood'] = red  #-- Raises exception.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Your thoughts on designing python code for unit testing?

2012-01-04 Thread Modulok
In general, write the unit test *before* you write the code. This way your code
is designed to be unit tested by default. It also provides a better way to
verify that your implementation of a desired feature actually works as
intended.

For example, when I'm writing a new module I document it first. That is, I
write up a bunch of code samples on how to use the module. This gives me a feel
for what features I want and how I want the module to work. This is my sketch.
I use the Sphinx documentation generator for this, but it could be as
simple as a text document. After that I write a bunch of unit tests, which fail
because there is no module written yet. Then, I write the module code to make
each unit test pass, one by one.

If I want a new feature I document it, write the unit test, then implement it
until the unit test passes. If a feature is difficult to unit test, you
probably need to re-think how you're implementing it, or re-think the interface
itself. That said, this isn't always the case. With code that has to interact
with many external programs, unit testing certain features can be difficult, if
not impossible. Just try to get the best coverage you can.

Everyone has a little different process, but that's how I do it.
-Modulok-

On 1/4/12, brian arb brianjames...@gmail.com wrote:
 What are some of the strategies for designing code to be unit tested?

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] sqlite3: turning on foreign key support thru python

2011-12-16 Thread Modulok
 How do I tell if it succeeded (short of trying an operation that should be
 blocked by foreign keys)?  How do I use that cursor object returned by the
 pragma query to tell if its a '1' (on) or a '0' (off) and verify the state?


The cursor object contains the result set. It's a python generator object. (Or
at least a generator interface.) You have to iterate over it in order to see
the resulting rows which are stored as a tuple. Not all operations return a
result row. (For example, conn.execute('pragma foreign_keys=ON' will return a
cursor object, but it won't generate any result rows, as there were
none returned by the database.)

To see the result of your second command, do something like this::

rows = conn.execute('pragma foreign_keys')
for r in rows:
print r


You'll then see something like this when foreign keys are turned on::

(1,)

Or this when they're turned off::

(0,)

Hope that helps.
-Modulok-

On 12/16/11, Monte Milanuk memila...@gmail.com wrote:
 I'm setting up an sqlite3 database to use as a base for some programming
 stuff I
 want to work on.  Currently using python 2.7, which appears to have a new
 enough
 version of sqlite (just barely) to support foreign keys.

 As I understand things, sqlite by default has foreign keys turned off,
 unless
 specifically compiled otherwise or until you turn on foreign keys using
 'pragma
 foreign_keys=ON'.  And it needs to be turned on for each connection too.

 So... just putzing around using the python interactive shell...


 import sqlite3
 sqlite3.sqlite_version
 '3.6.21'
 conn = sqlite3.connect('contacts.db')
 conn.execute('pragma foreign_keys=ON')
 sqlite3.Cursor object at 0x00B61860
 conn.execute('pragma foreign_keys')
 sqlite3.Cursor object at 0x00B6F020


 It appears I am able to successfully import sqlite3, its of a recent enough
 version to support foreign keys ( 3.6.19), I connected it to an existing
 database 'contacts.db', and when I execute the pragma statement to turn on
 foreign key support it returns a cursor object.  Similarly, when I send a
 pragma
 statement to query the status of foreign key support, it returns a cursor
 object.

 Now for the stupid question(s):

 How do I tell if it succeeded (short of trying an operation that should be
 blocked by foreign keys)?  How do I use that cursor object returned by the
 pragma query to tell if its a '1' (on) or a '0' (off) and verify the state?

 TIA,

 Monte

 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] where python is used in real world

2011-12-04 Thread Modulok
 2. If one wants to make a commercial software using python, how can he
 hide the code?

While it's a valid question, it's fun to imagine it in the physical world: We
need to permanently weld the engine compartment closed so that no one can steal
our engine ideas.

-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File vs. Database (possible off topic)

2011-11-21 Thread Modulok
On 11/21/11, Ken G. beachkid...@gmail.com wrote:
 It occurred to me last week while reviewing the files I made in using
 Python, it could be somewhat similar to a database.

 What would be a different between a Python files and Python databases?
 Granted, the access in creating them are different, I really don't see
 any different in the format of a file and a database.

 Again, this may be off topic, but where can I review the basic concepts
 of creating a database/file.  For example, when is a back up file
 created, after inputting a new value?  Is sorting a consider a separate
 program after inputting a new value?  It has been some 30 years since I
 took a course in basic data processing and I am hazy in trying to
 remember the basic concepts.

 If this is off topic, I apologized for posting here.

 Ken, Kentucky, USA

Generally speaking,

If you ever even think the word 'database', your best choice 98% of the time is
sqlite. (The module is called 'sqlite3' in python.) Reading up on SQL on
wikipedia and sqlite3 in the python docs is a good place to start!

Eventually, if you start storing a massive number of records and need things
like concurrent access and load balancing across multiple physical machines and
so forth, sqlite isn't going to cut the mustard. In such cases people use a
dedicated database server like postgresql, mysql, etc; A totally separate
program that does nothing but database black magic. Your python programs will
talk to the database server through a module written for that server. The
database server will fetch, sort, update and store the actual data.

Python has bindings to these heavy weight database backends through third party
modules that abstract the details for you. The most popular module is probably
sqlalchemy. It talks to postgresql, mysql and a few others. It's a good idea to
get used to sqlite and general SQL concepts before you jump into sqlalchemy!

Good luck!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] methods vs. functions

2011-08-22 Thread Modulok
On 8/22/11, Prasad, Ramit ramit.pra...@jpmorgan.com wrote:
 Steven D'Aprano wrote:
(Methods are very similar to functions. At the most basic level, we can
pretend that a method is just a function that comes stuck to something
else. Don't worry about methods for now.)

 Can someone please explain the difference between methods and functions?

 Thanks,
 Ramit

At the most basic level, they're the same. If you have a named, stand-alone
section of code that (optionally) operates on some argument passed to it, it's
called a function. If you have the same exact code, but you group it together
into a named unit along with the data it (optionally) operates on, it's called
a method. Technically in Python, they're both objects, both callables and can
be called in similar ways. The distinction is quite minimal. Here's a few
examples:


# A function that expects the first argument to be some object it operates on.
# This is just like a method, except it hasn't been declared within any class.
# Therefore, it's called a function:

def setx(foo):
foo.x = 1


# The same exact thing again, but declared in a 'Bar' class. Now it's
# called a method. Normally the first parameter to every instance method is
# named 'self', (A convention you should adhere to.) To make this example
# clearer, however, I use the name 'foo' instead just like the last example:

class Bar(object):
def setx(foo):
foo.x = 1


The call itself is a little different:

# As a function you must pass the arguments:

a = Bar()
setx(a) #-- Explicitly pass the object as an argument.

# As a method the first argument is implied:

a = Bar()
a.setx()#-- First argument is passed automatically for you.

That said, you could also call a method as if it were a function living in the
Bar namespace:

a = Bar()
Bar.setx(a)

You can even declare a function within a class that *doesn't* operate on any
instance of the class. Just like an ordinary function, you must pass all
arguments. This is called a static method and is declared with the
'@staticmethod' decorator:

class Baz(object):
@staticmethod
def bonzo(x, y):
return x+y

You can then call it like this:

Baz.bonzo(3, 5)

This looks remarably similar to calling a function that exists in some
namespace. For example:

import random
random.randrange(3, 5)


So the ultimate difference? Pretty much just where you declare it. If it's in a
class it's called a method, outside of a class its called a function.
Especially in python - the distinction is small.

-Kurt-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] floats

2011-06-06 Thread Modulok
 Can someone till me how to get a two decimal precision every time?

print %.2f % (500/1000.0)

# or...

result = 500 / 1000.0
print %.2f % result


Using 'new' style string formatting works too:

print {0:.2f}.format(500/1000.0)

-Modulok-

On 6/6/11, Michael bridges micha_el2...@yahoo.com wrote:
 i saw it somewhere, but where?

 i want to 10 / 1000 and get 0.01 not 0
 if 1000 is made 1000.00 then 0.01 is printed
 but that gives 500 / 1000.00 is 0.5 not 0.50

 i might be thinking C# not python.

 can someone till me how to get a two decimal precision every time?

 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Clunky Password maker

2011-05-25 Thread Modulok
On 5/25/11, Wolf Halton wolf.hal...@gmail.com wrote:
 Is there a less clunky way to do this?
 [code]
 def new_pass():
 series = ['`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-',
 '=', \
   '~', '!', '@', '#', '$', '%', '^', '', '*', '(', ')', '_',
 '+', \
   'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']',
 '\\', \
   'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}',
 '|', \
   'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', ', \
   'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '', \
   'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', \
   'Z', 'X', 'C', 'V', 'B', 'N', 'M', '', '', '?']
 passwd = []
 p = input(Enter the length you want your password to be: )
   # length of password
 for i in range(p):
 r = random.randint(0, 94)
 passwd.append(series[r]) # Append a random char from series[] to
 passwd
 #print passwd
 #print passwd[0], passwd[1], passwd[2], passwd[3]
 print 
 print .join(map(str, passwd)),  is your new password. \n
 [/code]

 [output]

 Enter 1 to run a MD5hash on your password
 Enter 2 to run a SHA1   hash on your password
 Enter 3 to run a SHA224 hash on your password
 Enter 9 to get a new randomy password
 Enter 10 to run away...  he he he

 Enter your choice here 9
 Enter the length you want your password to be: 4

 !bnR  is your new password.

 [/output]

Depending on what your passwords are going to be protecting, be aware that the
default generator in the random module is:

...completely unsuitable for cryptographic purposes.

Instead, create an instance of the 'SystemRandom' class. You also don't need to
create a list of all of your values. A simple string will do. You should also
look into the 'string' module, as it defines 'letters', 'digits' and
'punctuation' characters for you. Thus, your code be something like:

import random
import string
passlen = 10 # How long should it be?

r = random.SystemRandom()
chars = string.letters + string.digits + string.punctuation
passwd = 
for i in range(passlen):
passwd += r.choice(chars)
print passwd

-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Titles from a web page

2011-05-04 Thread Modulok
You might look into the third party module, 'BeautifulSoup'. It's designed to
help you interrogate markup (even poor markup), extracting nuggets of data based
on various criteria.

-Modulok-

On 5/4/11, louis leichtnam l.leicht...@gmail.com wrote:
 Hello Everyone,

 I'm trying to write a program that looks in a webpage in find the titles of
 a subsection of the page:

 For example you have the list of the title of stories in a newspaper under
 the section World and you you click on it you have the entire story.

 I want a program that print the title only of this special section of the
 page.

 Can you help me out? I tried using regular expression but I keep hitting
 walls and I don't know what to do...

 Thank you

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to solve this problem in python?

2011-04-24 Thread Modulok
Ratna,

This list doesn't usually do your homework. However, we will help you with key
issues. What have you tried already? Where are you stuck? Is there a certain
aspect you don't understand? (Questions like these get lots of help around
here. Informally saying do my homework generally doesn't.)

-Modulok-

On 4/24/11, Ratna Banjara mast.ra...@gmail.com wrote:
  Write a function named countRepresentations that returns the number
 of ways that an amount of money in rupees can be represented as rupee
 notes. For this problem we only use  rupee notes in denominations of
 1, 2, 5, 10 and 20 rupee notes.

 The signature of the function is:
def countRepresentations(int numRupees)

 For example, countRepresentations(12) should return 15 because 12
 rupees can be represented in the following 15 ways.
   1. 12 one rupee notes
   2. 1 two rupee note plus 10 one rupee notes
   3. 2 two rupee notes plus 8 one rupee notes
   4. 3 two rupee notes plus 6 one rupee notes
   5. 4 two rupee notes plus 4 one rupee notes
   6. 5 two rupee notes plus 2 one rupee notes
   7. 6 two rupee notes
   8. 1 five rupee note plus 7 one rupee notes
   9. 1 five rupee note, 1 two rupee note and 5 one rupee notes
   10. 1 five rupee note, 2 two rupee notes and 3 one rupee notes
   11. 1 five rupee note, 3 two notes and 1 one rupee note
   12. 2 five rupee notes and 2 one rupee notes
   13. 2 five rupee notes and 1 two rupee note
   14. 1 ten rupee note and 2 one rupee notes
   15. 1 ten rupee note and 1 two rupee note

 Hint: Use a nested loop that looks like this. Please fill in the
 blanks intelligently, i.e. minimize the number of times that the if
 statement is executed.
 for (int rupee20=0; rupee20=__; rupee20++)
for (int rupee10=0; rupee10=__; rupee10++)
   for (int rupee5=0; rupee5=__; rupee5++)
  for (int rupee2=0; rupee2=__; rupee2++)
 for (int rupee1=0;  rupee1=__; rupee1++)
 {
 if (___)
count++
 }

 --
 Regards,
 Ratna P Banjara
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Metaclass confusion...

2011-04-20 Thread Modulok
Peter,

 ... the class, i. e. the instance of the metaclass with all its attributes
 has already been created by the type.__new__() method. If you move the
 manipulation of the members dict into a custom __new__() method you get
 the desired behaviour...

Thank you! You've solved my problem and broadened my understanding :)
Excellent examples as well. Love the class name too.

-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Metaclass confusion...

2011-04-19 Thread Modulok
List,

I've been messing with metaclasses. I thought I understood them until I ran
into this. (See code below.) I was expecting the generated class, 'Foo' to have
an 'x' class-level attribute, as forced upon it by the metaclass 'DracoMeta'
at creation. Unfortunately, it doesn't and I don't know why. I'm obviously
missing something big. I thought a metaclass created the class object,
so this should work. (But obviously doesn't.)


!-- Begin Code --
class DracoMeta(type):
'''Metaclass that creates a serial number as a class property.'''
def __init__(self, name, bases, members):
# Force a class attribute on the class-to-be:
members['serial'] = 3

# Now make the class:
type.__init__(self, name, bases, members)

class Foo(object):
__metaclass__ = DracoMeta

print hasattr(Foo, 'serial')#-- I was really expecting this to be True.
!-- End Code --

I could add the attribute in the definition or a decorator, but the point was
learning to use (albeit abuse) metaclasses. Anyway, if anyone could take
a look I'd be grateful.

Thanks!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] String formatting question.

2011-03-29 Thread Modulok
For simple strings I use the %s % foo version, for more complex stuff I use
the .format() method. I find it easier to control spacing and alignments with
the .format() method, but that's just me.

-Modulok-


On 3/29/11, Blockheads Oi Oi breamore...@yahoo.co.uk wrote:
 On 29/03/2011 20:41, Prasad, Ramit wrote:
 Is there a difference (or preference) between using the following?
 %s %d % (var,num)
 VERSUS
 {0} {1}.format(var,num)


 Ramit

 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor


  From Python 2.7.1 docs at
 http://docs.python.org/tutorial/inputoutput.html Since str.format() is
 quite new, a lot of Python code still uses the % operator. However,
 because this old style of formatting will eventually be removed from the
 language, str.format() should generally be used..

 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] time taken to execute certain task

2011-03-17 Thread Modulok
On 3/16/11, tee chwee liong tc...@hotmail.com wrote:

 hi,

 i would like to know the time taken to execute a certain task in python. i
 used time.time and time.clock and i see the time taken is different? what is
 the right method to use?

 import time
 def testtime(num):
 start=time.time()
 #print start
 for n in range(num):
 #print n
 print time.time()-start

 testtime(101)

 start = time.clock()
 for x in range(101):
   y = x  # do something
 end = time.clock()
 print Time clock elapsed = , end - start, seconds

 thanks
 tcl


Also look into the builtin module 'timeit' if you're trying to benchmark things.
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Shared web host and setting the python environment...

2011-03-04 Thread Modulok
List,

Background:
I'm on a linux based shared web host. They cater to PHP, not python.
(There's no third party python modules even installed!) So I installed
a virtual python in my home directory, plus easy_install and a bunch
of modules. Great!

The Problem:
Unfortunately, the web server uses the system python, not my virtual
python, or my modules. (It does execute my scripts as my uid though.)
I need modify the environment of every one of my python scripts,
perhaps appending to sys.path, so that my third party modules in my
home directory can be found. I have zero control over the web server
process or its environment.

Possible Solutions I thought of:
One way to do this would be to edit 'sys.path' at the top of every
python script. (Sounds ugly.) Another would be to import the 'user'
module and go that route. (Fine, but it's depricated. What replaces
it?) A third idea would be to re-direct all requests via mod_rewrite
to a single python file or shell script, which sets the environment
and calls my python scripts as a sub-process. (Slow, which is fine,
but some security concerns here.)

Given my situation, what's the best way to accomplish this? (Aside
from a new hosting company or a virtual private server.)

Any suggestions appreciated. Thanks!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Help - want to display a number with two decimal places

2011-03-04 Thread Modulok
On 3/4/11, lea-par...@bigpond.com lea-par...@bigpond.com wrote:
 Hello

 I have created the following code but would like the program to include two
 decimal places in the amounts displayed to the user. How can I add this?

 My code:


 # Ask user to enter purchase price
 purchasePrice = input ('Enter purchase amount and then press the enter key
 $')

 # Tax rates
 stateTaxRate = 0.04
 countrySalesTaxRate = 0.02

 # Process taxes for purchase price

 stateSalesTax = purchasePrice * stateTaxRate
 countrySalesTax = purchasePrice * countrySalesTaxRate

 # Process total of taxes
 totalSalesTax = stateSalesTax + countrySalesTax

 # Process total sale price
 totalSalePrice = totalSalesTax + purchasePrice

 # Display the data
 print '%-18s %9d' % ('Purchase Price',purchasePrice)
 print '%-18s %9d' % ('State Sales Tax',astateSalesTax)
 print '%-18s %9d' % ('Country Sales Tax',countrySalesTax)
 print '%-18s %9d' % ('Total Sales tax',totalSalesTax)
 print '%-18s %9d' % ('Total Sale Price',totalSalePrice)


Lea,

Notice that 'd' in your string substitution means integers, not
floats. Any decimal places will be truncated when using 'd'. For
floats use 'f' instead. You an also specify a precision, such as
'%.2f' shows two decimal places.

However, to make all of your numbers line up nicely, regardless of how
long they are, you need to look into advanced string formatting via
the builtin string method 'format()'. It takes a little practice to
understand and use, but the results are exactly what you want.
(See: http://docs.python.org/library/stdtypes.html#str.format)

Here's an example you could put at the bottom of your code to see it in action:

print {0:18} {1:18.2f}.format(Country Sales Tax, countrySalesTax)
print {0:18} {1:18.2f}.format(Purchase Price, purchasePrice)
# First prints the first argument (the 0th index) to 'format(),
# left aligned '', and 18 characters wide, whitespace padded.
# Then prints the second argument, (the 1st index) right aligned,
# also 18 characters wide, but the second argument is specified to
# be a float 'f', that has a precision of 2 decimal places, '.2'.


-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File transfer HTTP - SFTP

2011-03-01 Thread Modulok
This isn't a python solution, but if you have an ssh connection to
both servers, (I assume so) you can forward them directly. It would
look like this in an operating system shell like tcsh or bash:

me@baz scp -r m...@foo.com:/home/me/pictures m...@bar.com:/somewhere/

You could wrap the above command with python via the subprocess module
if needed.
-Modulok-


On 3/1/11, Emanuel Lauria emanuel.lau...@gmail.com wrote:
 Sorry if im annoying, but I think this is a better question than my previous
 one of today.

 I have some Images in an HTTP Server that I need to transfer to an SFTP
 server using a Python script.

 So far I can download them to my hard drive, and upload them to the sftp
 server; quite easy. I would like to do the transfer without touching my hard
 drive.

 How could I do that?

 Im using paramiko, but STPClient.put() reads from the filesystem.

 Thanks

 put(self, localpath, remotepath, callback=None)
 Copy a local file (localpath) to the SFTP server as remotepath.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Generator expressions...

2011-02-27 Thread Modulok
List,

I was messing around with generator expressions. I tried to make a
script that would read a few bytes from '/dev/urandom' for eternity.
It then did something pointless like computing checksums and printing
them out. Unfortunately, the script only runs a few seconds and then
terminates. I'm not sure why.  I tried running it on /dev/zero as well
with the same result; The process terminates, albeit normally. (Exit
status 0. It's not being killed by the kernel or anything.) I was
expecting it to run forever. Below is my code:

## Begin code
#!/usr/bin/env python

# This script will only work on UNIX flavors with a /dev/urandom
#
# It reads from /dev/urandom for eternity, or until you press 'ctrl+c' to
# interrupt it. It computes the hashes forever.
# The point being illustrated is that its memory usage is about constant,
# despite an infinitely large file being read.

import hashlib

fd = open('/dev/urandom', 'rb')
gen = (hashlib.sha256(i).hexdigest() for i in fd.read(4096))

try:
for i in gen:
print i #-- This loop should never end... but does. Why?

except KeyboardInterrupt:
gen.close()
fd.close()
print \nBye!

## End code

I've got to be missing something obvious.
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generator expressions...

2011-02-27 Thread Modulok
 import hashlib

 fd = open('/dev/urandom', 'rb')
 gen = (hashlib.sha256(i).hexdigest() for i in fd.read(4096))

 try:
for i in gen:
print i #-- This loop should never end... but does. Why?

 except KeyboardInterrupt:
gen.close()
fd.close()
print \nBye!


 Check out the generator expression. What are you iterating over? How
 long is the string returned by the read?

I knew it was subtle. I was trying to use 'read(4096)' like open()'s
buffersize parameter. (Which it's obviously isn't.)

Thanks!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] accessing another system's environment

2011-02-26 Thread Modulok
I'm coming into this thread late so I might be off the mark here, but
it seems like you're going about it backwards:

Instead of trying to reach in and modify a user's environment, which
is highly variable and process dependent, why not just wrap the
software they're running? Have a python script wrap all of the
programs you're trying to configure on the client's machine. (No
matter how you do it, you'd have to install a client program of some
kind anyway.) When they launch the 'program' in question, they're
really launching a python script. The script checks in with a remote
server that holds the config files or environment data. (Or whatever
else you need.) The client script says some thing like I'm john,
running program version x.x. Give me my env variables.)

The server then replies with any variables that the client needs to
set and their values. You could do this with a python script running
on a server sending ajax responses. (There's an ajax module in the
standard library.) The wrapper, running on the client gets the
response and set any environment variables for the process it's about
to launch. It then starts the real program, passing the properly
configured environment on to it.

You have to write two programs. 1. A client wrapper that asks the
server for its data and 2. A simple server that passes any data back
to the client.

In effect, you'll be able to change the clients configuration,
environment variables or *anything else* that needs done before your
script launches the the real client program. You don't have to deal
with screwing around with the client's environment or the complexities
that brings up either.


On 2/26/11, Dave Angel da...@ieee.org wrote:
 On 01/-10/-28163 02:59 PM, Steve Willoughby wrote:
 On 26-Feb-11 01:19, ALAN GAULD wrote:
 Bill,

 That's the same thing we are talking about.
 The problem is those environment variables are
 highly variable so you can't talk about a machine's environment.
 Two users on the same machine (at the same time) may have
 very different environments. And a batch file or program can

 I'm a Unix hacker, so forgive me if my understanding of Windows is a bit
 naive. I think, though, that Windows has a set of environment variables
 which are system-wide, added automatically to the user set of variables
 when a new process is launched. Yes, they can be changed or deleted but
 there is a standard set applied to all users.

 If that's a correct assumption on my part, there must be somewhere that
 can be read from, probably (I would guess) in the registry. So a script
 which could read/write those registry keys may do what is required here.

 The issue of exposing that to remote machines remains a dangling issue,
 though.

 Of course, it's not entirely clear we're solving a Python question,
 although this discussion may well go more solidly into that space.


 Indeed.  in Windows, there are two sets of registry keys for environment
 variables, one is system wide, and one is per user.  When Explorer
 launches a console or an application for a particular user, it combines
 those two sets of keys to come up with an initial set of environment
 variables.

 I tried to launch a VirtualBox XP machine, but it failed for some
 reason.  Probably I have too much else running.  So I can't tell you the
 key names.

 I'd suggest asking about remotely accessing the registry on the
 python-win32 forum.  I'm sure the win32 extension have a way, I just
 don't know if it'll work from a Linux client.

 DaveA
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] accessing another system's environment

2011-02-26 Thread Modulok
On 2/26/11, Modulok modu...@gmail.com wrote:
...
 The server then replies with any variables that the client needs to
 set and their values. You could do this with a python script running
 on a server sending ajax responses. (There's an ajax module in the
 standard library.)
...

Sorry, I meant a 'json' module, not 'ajax'. I've been doing too much
web programming recently :p. You could probably even get away with not
having to write a server, just set up a web server to handle it,
sending a well-formed response.

-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Try except really better than if?

2011-01-09 Thread Modulok
On 1/9/11, Karim karim.liat...@free.fr wrote:

 Hello all,

 I am using more and more try except statement. But I discussed with a
 very experienced C++ programmer.
 And he told me that at least in C++ using too many try -catch statements
 are making the code slower. And it should
 does the same for python (C implementation). My simple question: Is this
 true? And why using try-except is indeed encouraged
 to code as a pythonista?

 Regards
 Karim

Exceptions are almost always slower to catch. You can confirm this via
the 'timeit' module in the standard library. However, if the
performance of exceptions themselves become significant, there are
bigger, more fundamental problems with your code.

Python isn't a language chosen for execution speed. Python is chosen
for ease of use and readability. If you find you have to sacrifice
that for your project, you might look into a faster language, but not
before trying a few things (which solves the problem 99% of the time):

1. Test it. Don't guess. Actually benchmark your code. (See the timeit module.)
Is it fast enough? If you have a cron job that runs once every minute
that turns over a few log files, having it run in 0.026 seconds is no
better than having one that runs in 0.015.

2. Find where the bottleneck is. Again use timeit, and start to look
at our iterative algorithms. Better algorithms can speed up some code
significantly. (But again, only if you must!) Ask for help on this
list, see if there's a module written by someone that does what you
want, or research various algorithms that fit your purpose yourself.

3. Still not fast enough? Implement those speed-critical pieces of
your code in C and call them from Python. This should be rarely
needed.

4. Still not fast enough? You either didn't do step 1 or screwed up
between step 2 and 3, or you need more hardware.

A try...except...finally block is a lot easier to read, and more
flexible than an if...elif block, for catching specific exceptions.
Even if your code was twice as slow with exceptions, but your code
still runs 'fast enough' for whatever purpose you've written it for,
then it's fast enough. Don't obfuscate it. That said, don't use
exceptions so liberally that you no longer worry about checking for
good inputs. If something usually succeeds just go for it and use an
exception as accident insurance. If it will usually fail, check it
with an if statement first.

-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Weighted Random Choice - Anyone have an efficient algorithm?

2010-12-22 Thread Modulok
Does anyone know of an efficient way of doing a weighted random
choice? (I don't even know what algorithms like this would be called.)
Preferably, something that doesn't grow exponentially with the number
of elements in the list, or the size of their respective values.

For example: Assume I have a list of integer elements. I want to pick
an index from that list, using the value of said elements to control
the probability of selecting a given index:

w = [5, 20, 75]
wrand(w)

Where wrand() will return '2', (the index of 75),  about 75% of the time.
It would return '1', (the index of 20) about 20% of the time, and 0,
about 5% of the time. It could return the actual value, but returning
the index seems more flexible.

The implementation doesn't have to work exactly like this, even if the
weight values don't add up to 100, or are arbitrary, that's fine.
Hopefully you get the idea. Here's what I tried (it works, but is
slow):

### Begin Code Example ###
import random
random.seed(2) #-- So we can reproduce the sequence for testing.

def wrandom(weights):
'''
Return a randomly selected index of the 'weights' list, using the
values of that list to affect probability of said index being returned.
'''
debug = False
flattened = []
for i, w in enumerate(weights):
if debug: print i, w: , i, w
for k in range(w):
flattened.append(i)
if debug: print flattened: , flattened
rnd = random.randint(0, (len(flattened) - 1))
return flattened[rnd]

# Not test it:
print wrandom([5, 20, 75])
print wrandom([5, 20, 75])
print wrandom([5, 20, 75])

### End Code Example ###

It works and is easy enough to understand, but when the number of list
items gets large, or the weights get heavy, things get ugly.
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] unit testing - Separate methods or group tests together?

2010-12-17 Thread Modulok
List,

When you create unit tests, do you group tests for a given function
together into one unit test method, or do you prefer to have separate
test methods for every assert statement?

Thanks!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Writing to the terminal?

2010-12-12 Thread Modulok
List,

Thanks! I think I got it working now with the help of some suggestions :-)

For more complex stuff, (think blue screens with little white boxes
you press spacebar to activate. Kind of like an OS installer) I would
look into the `curses` module in the standard library?

Thanks!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Writing to the terminal?

2010-12-10 Thread Modulok
List,

Forgive me if I don't describe this well, I'm new to it:

Assume I'm working in a command shell on a terminal. Something like
tcsh on xterm, for example. I have a program which does *something*.
Let's say it counts down from 10. How do I print a value, and then
erase that value, replacing it with another value? Say I had something
like '10' that appears, then wait a second, then the 10 is replaced by
'9'... '8'.. and so forth. The point is, I don't want to print to a
new line, nor do I want the new number to appear next to the previous
number... I just want to change it in place. (If that makes any
sense?) Think of console based progress counters in programs like
fetch or wget, or lame.

How do you do this in Python?
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling Program within Program

2010-12-09 Thread Modulok
Patty,

I didn't read through your code, but to call an external program see
the 'subprocess' module in the standard library:
http://docs.python.org/library/subprocess.html

-Modulok-


On 12/9/10, pa...@cruzio.com pa...@cruzio.com wrote:

 Hello:

 I would like to know how to call a program from within a program and what
 directory I should place one small program file in.  I am running Python
 2.6.6 and Windows 7.

 I have a directory called  C:\Users\StarShip\PyProgs and it has the files
 BreakersCafe.txt and BreakersCafe.py.  This is my primary program running
 fine.

 I have a subdirectory called C:\Users\StarShip\PyProg \PicturesForTesting
 and another subdirectory C:\Users\StarShip\PyProgs\CustomFunctions with
 various program files, functions defined  in them, etc.  which I import in
 my primary program.   For example:

  def Newbanner():
 print \n   Alternate Selections\n

 Now I have the small program below which is fully self-contained and I
 want to execute it from within  BreakersCafe.txt. I would like to use
 raw_input and if statement for simple yes/no asking if they would like to
 see this BeveragesMenu.txt and have it as the last 3-4 lines of the
 main().

 The only directory of these three that has __init__ is
C:\Users\StarShip\PyProgs\CustomFunctions
 and as you can see, the program below is not a function, it has no 'def'
 anything.  I get 'NameError: global name 'BeveragesMenu' is not defined'
 when I run this in IDLE.  I suppose I _could_ make this a function :} but
 it is likely doable to call a program as a program, right?  I am also
 compiling to a .pyw file where applicable.

 Thanks for the help.

 Patty

 
 This is C:\Users\StarShip\PyProgs\BeveragesMenu.txt and BeveragesMenu.py.
 Program file for displaying an image using Tkinter built-in GUI functions.
  open root window, open file descriptor for image, open new window file
 descriptor to manipulate with Tkinter Label library function.

 Pic needs to be displayed as a banner. Uses the compound=top argument to
 do this.

 --  take out the pack()function didn't work, pack()is required

 Uses   import Tkinter

 Program using new breaker's jpg picture; bar choices are not selectable
 


 import Tkinter
 import ImageTk

 rootwindow = Tkinter.Tk()

 fhdl=
 ImageTk.Image.open(C:\Users\StarShip\PyProgs\PicturesForTesting\houseimage.jpg)
 image_var = ImageTk.PhotoImage(fhdl)

 whdl = Tkinter.Label(rootwindow, compound=top, image=image_var,
 text=\n\n!!!WELCOME TO BREAKER'S BREAKFAST BAR!!!\n\n\nBeverage Choices:
 Sparkling Water;  Milk;  Orange Juice;  Apple Juice  *OR*\n\n  **From Our
 Bar**Smoothie;  Breakers Sun Tea;  Chai;  Cafe Mocha;  Latte;
 Mimosa)

 whdl.pack()
 rootwindow.mainloop()

 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] True Random Numbers

2010-11-03 Thread Modulok
On 11/2/10, Crallion cralli...@gmail.com wrote:
 In an attempt to generate true random numbers, I found this python script-
 http://code.google.com/p/truerandom/
 Getting to the point, I get this error when I run my program.

 File /dev/python/absolute/truerandom.py, line 9, in module
 from urllib import urlopen
 ImportError: cannot import name urlopen

 Is urllib and/or urlopen deprecated in 3.1.2 or is it something I forgot to
 do?
 Python is running on OSX 10.6, which I upgraded from the default install to
 3.1.2.

The only 'true' source of entropy is a hardware random number
generator. For cryptographic work you don't need this. All you need is
a seemingly endless unpredictable sequence of bits. For this purpose,
a cryptographically secure pseudo random number generator will do
nicely. Furthermore, if your intent was for encryption, you shouldn't
be getting your entropy over the wire for obvious reasons. (Speed and
security.)

With your stress on 'true' random numbers, I can only assume your
intent is encryption. That said, use the operating system's random
number generator. This will vary from system to system in how it is
implemented, but all systems have one which is suitable for
cryptographic purposes. On *NIX flavors this will be /dev/random. You
can either read from this file directly to get a random stream of
bits, or use the python standard library to interface with it to do
things like get random numbers (as others have pointed out.)

Whether reads to this, or calls which use this, will block, waiting
for a suitable amount of entropy, depends on the system your code runs
on. For example on FreeBSD both '/dev/random' and '/dev/urandom' are
always non-blocking. FreeBSD uses a crypto secure 256-bit pseudo
random number generator based on yarrow. The same is true for Mac OS X
and AIX. On linux '/dev/random' will block if the entropy pool is
exhausted, while '/dev/urandom' will not, but is still considered
cryptographically secure. (And far better than any home brewed
solution.)

Also remember, 'pseudo-random' doesn't mean 'almost random,' it means
deterministic *if you know the initial state*. (This is only true of
some generators though, as some perturb their state with external
sources of entropy on a regular basis.) On python you can get random
numbers through the operating system's '/dev/urandom' (or on Windows,
CryptGenRandom ):

# Python example of getting secure, random numbers using the standard library:
# This works in python 2.4 and greater on most systems:

import random
foo = random.SystemRandom() # Uses /dev/urandom or Windows CryptGenRandom

# Print 10 random numbers:
for i in range(10):
foo.random()


What are you using the random numbers for?
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] unittest testing order...

2010-09-27 Thread Modulok
List,

When using the unittest module, tests are run in alphanumeric order.
What's the suggested way of specifying a test order? Any code examples
would be great!

Thanks
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] unittest testing order...

2010-09-27 Thread Modulok
On 9/27/10, Steven D'Aprano st...@pearwood.info wrote:
 On Tue, 28 Sep 2010 04:03:17 am Modulok wrote:
 List,

 When using the unittest module, tests are run in alphanumeric order.
 What's the suggested way of specifying a test order?

 There isn't one. It shouldn't matter what order the tests run, no test
 should *rely* on another test.

 (Although of course, if one test fails, any tests which assume the
 missing functionality will also fail.)

In an ideal world, I agree. This is possible for pure functional
programming where state is avoided. However, when dealing with object
oriented, imperative programming, state changes cannot be avoided.
Thus if a method requires an object be passed to it, I'd like to
verify that object is being constructed correctly by the object
factory, before verifying that the method which uses said object, is
correct.

Or is there some other way of doing this? I'm new to unittesting.

Thanks!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] quick speed question

2010-09-16 Thread Modulok
This is faster:

if dict['key'] == 'foo':
pass

...But just slightly. (About 9% faster on my machine. This may differ
depending on the implementation, but I doubt it. See the 'timeit'
module.) Whether it's a big deal depends on what you're doing.
Accessing the dict - a million times - with either method took less
than a second. Visually, this makes more sense to me:

if dict['key'] == 'foo':
pass

Regardless, you should be aware that while they look similar, they
differ in their semantics:

# Something to work with:
dic = {'a': Big, 'b': Bigger}

# This is true:
if dic['a'] == Big:
print True

# And this is true:
if Big in dic['a']:
print True

# But this is also true!
if Big in dic['b']:
print True

As far as speed is concerned: Don't worry about it unless has already
become a problem. Premature optimization wastes time you should be
spending solving the actual problem. For example, if you wrote an MP3
player that sorted playlists in 0.1 seconds instead of 0.2
seconds (100% faster!), but you wasted 3 days doing it - you haven't
accomplished much.

When you're done and you find you need a faster solution, optimize
your algorithms. If that still isn't enough, ask somebody smarter than
yourself to look at it. (This list is great for that!) If that too
fails, start think about writing a few critical bits in C, but only as
a last resort.

We should forget about small efficiencies, say about 97% of the time:
premature optimization is the root of all evil -Donald knuth-

-Modulok-

On 9/16/10, C.T. Matsumoto c.t.matsum...@gmail.com wrote:
 Hello Tutors,

 I was just wondering if you have a dictionary key is it faster to do:

 if dict['key'] == 'foo':
  ...

 or is this faster:

 if 'foo' in dict['key']:
  ...

 Or is there any difference and I'm chasing ghosts?

 Thanks,

 T
 --
 C.T. Matsumoto
 Claes de Vrieselaan 60a III
 3021 JR Rotterdam
 The Netherlands

 tel.: +31 (0)6 41 45 08 54
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Advice on math

2010-06-27 Thread Modulok
 Hello, I've enjoying learning python for the first few years, and
 appreciate all the help I have received from this list. I had some
 interest in programming and am very glad to have made python my choice
 of programming language. Since I didn't go to college for computer
 studies, I feel my math is kind of rusty in some areas, and looks like
 improving/regaining math skills would help a lot in programming,
 logic, algorithms, etc.
 Right now I think I need a better understanding of logarithm, arrays
 (matrixes), and even probability. What links would you all recommend
 that would be useful for me to learn these things in a newbie-friendly
 way?



 If you want to code+learn, nothing beats ProjectEuler (
 http://projecteuler.net/ ). However I assume you have basic understanding of
 maths.

Not to hijack the thread, but that's awesome! Only when you solve the
problems and then read the forum thread, do you realize how crude your
own solutions are, compared to some very clever fellows. Far better
than a crossword to keep things stimulated.

-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Data exchange formats...

2010-06-20 Thread Modulok
List,

What's the best format to send data across the wire between processes?

I have some simple 'insensitive' data I need to send from a client, to
a server via a TCP socket. Things like 'count = 10, name=foo' and so
forth. Basic values. I would use something like the 'pickle' module to
pack them up send as encoded strings, which would then be loaded on
the server. It'd be nice, but the server has no authentication.
Therefore:

Warning The pickle module is not intended to be secure against
erroneous or maliciously constructed data. Never unpickle data
received from an untrusted or unauthenticated source.

Currently I'm sending strings and using regular expressions on the
server to pluck out the needed data, but thought there must be
something cleaner, nicer and better. Ideas?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] help

2010-06-17 Thread Modulok
Solution: width times height.


On 6/17/10, KB SU k24...@gmail.com wrote:
 help

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Trouble with sockets...

2010-06-17 Thread Modulok
List,

I'm new to sockets and having trouble. I tried to write a simple
client/server program (see code below). The client would send a string
to the server. The server would echo that back to the client.

PROBLEM:
I can send data to the server, and get data back, but only for the
first call to the 'sendall()' method. If I try to call it in a loop on
the client, to print a count-down, only the first call gets echoed.
Clearly, I'm missing something.

EXAMPLE: (They're on the same physical machine.)
Shell on the server:
modu...@modunix ./socket_server.py
Listening for clients...
Got connection from 192.168.1.1

Shell on the client:
modu...@modunix ./latency_client.py 192.168.1.1 2554
0

What I wanted:
[-]modu...@modunix ./latency_client.py 192.168.1.1 2554
0
1
2


CODE:

# The client program:

import socket
import sys
def main():
'''Send data to a server and receive the data echoed back to us.'''

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect( ('192.168.1.1', 2554) )

for i in range(3):
s.sendall(str(i))
print s.recv(1024)
s.close()

# Execution starts here:
try:
main()
except KeyboardInterrupt:
sys.exit(Aborting.)


# The server program:

import socket
import sys
def main():
'''Listen for a client and echo data back to them.'''

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind( ('192.168.1.1', 2554) )
s.listen(5)

print Listening for clients...
while True:
channel, client = s.accept()
print Got connection from %s % client[0]
message = channel.recv(1024)
channel.send(message)
channel.close()

# Execution starts here:
try:
main()
except KeyboardInterrupt:
sys.exit(Aborting.)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Making pretty web pages from python code examples?

2010-04-14 Thread Modulok
  : Basically, I'm trying to read python code examples from files on
  : disk and generate pretty little web pages from them.

 I think you may want sphinx [0] which is available in PyPI [1].

 It understands reStrucTured text and adds a few Sphinx-specific
 directives/features for pulling the docstrings from your python
 modules.  Much easier than building your own.

Thanks! Looks like just what I'm after.
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Making pretty web pages from python code examples?

2010-04-13 Thread Modulok
Is there an easy way to get a docstring from a python file, without
first importing it?

Basically, I'm trying to read python code examples from files on disk
and generate pretty little web pages from them. I invision the
docstring appearing as the main text on the page, with the rest of the
code in HTML code or pre tags. That way I could just write up a bunch
of python samples, without having to do anything more but upload them.
Maybe something like this exists already? I don't know. I just figured
it would be pretty easy to write, but getting the docstrings without
trying to parse the files was a rut.

Thanks.
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Introduction to modelling with Python

2010-03-28 Thread Modulok
Could you further define 'modeling' in context?

Are you referring to using python in the context of 3D modeling, i.e.
computer aided design? If that be the case, python serves as an
embedded language for many 3D computer graphics programs. Everything
from Maya to Houdini use it as a command interface to automate things.
See the developer's documentation for whatever software you're using.

What kind of modeling?
-Modulok-

On 3/27/10, AG computing.acco...@googlemail.com wrote:
 Hi List

 I apologise in advance for the vagueness of this query, but I am looking
 for a decent modern introduction to modelling using Python.
 Specifically, I want something that is a good introduction (i.e. doesn't
 expect one to already be a maths/ statistics or a programming guru) and
 that has an ecology/ environmental science orientation.  The latter is
 desirable but not essential, as I suspect that once one understands the
 process of data abstraction and the other steps involved in modelling
 processes and scenarios, the thinking and skill sets are likely
 transferable.  However, if my assumption about this is incorrect, please
 let me know.

 If anyone knows of any resource (book or on-line) with a Python bent,
 please let me know.  I am preparing to begin applications to Ph.D.
 programs and most of what I am interested in doing requires some
 knowledge of modelling and Python also seems to be widely accepted as a
 programming language, so I am happy with that as I am in the process of
 teaching myself Python anyway.

 Thanks for any help, advice, etc.

 Cheers

 AG
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Bowing out

2010-03-03 Thread Modulok
 After six years of tutor posts my interest and energy have waned and
 I'm ready to move on to something new. I'm planning to stop reading
 and contributing to the list. I have handed over list moderation
 duties to Alan Gauld and Wesley Chun.

 Thanks to everyone who contributes questions and answers. I learned a
 lot from my participation here.

Kent,

I'm a relative newcomer, but even so, I benefited from you. Thanks for
giving what you could!

Best of luck with your new endeavors. Hope to see you check back in
from time to time.
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Encryption

2010-02-22 Thread Modulok
 I need a simple way to encrypt and decrypt some strings with a key.

Did you have any other requirements? Any specific algorithms or key lengths?

If you need real encryption, you might check out a 3rd party module
named 'PyCrypto'. It offers an implementation of the AES algorithm. A
less eloquent approach - you could also wrap the Unix command
'openssl' with a python process. Whether you can get these libraries
will depend on where you live. Strong encryption is still strictly
controlled in some regions. There are code examples in the 'README'
file of pycrypto. There are probably other AES implementations out
there as well. However, the only FIPS certified library I know of is
openssl.

-Modulok-

On 2/22/10, Shashwat Anand anand.shash...@gmail.com wrote:
 how about using base64? base64.encodestring(s) will do.



 On Tue, Feb 23, 2010 at 2:30 AM, Wayne Werner waynejwer...@gmail.comwrote:

 On Mon, Feb 22, 2010 at 2:50 PM, Antonio Buzzelli anto.buzze...@gmail.com
  wrote:

 Hi everyone!
 I need a simple way to encrypt and decrypt some strings with a key

 someone can help me??


 I'm sure someone can.

 -Wayne

 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] adding more text to a file

2010-01-18 Thread Modulok
If you're using this as an interactive command to help you populate a
database, as you appear to be, don't open the file more than once. As
previously suggested you should also put all your strings together and
then write them to the database in one go.

I don't know if you've thought about this yet, but you'll need a way
to stop when you're done inputing names and ages! Here are two
thoughts you can look into: 1) Check for a special character (or lack
thereof). For example, if the fields are blank you could exit the loop
using the 'break' statement. Or 2) Catching a 'KeyboardInterrupt'
exception using the 'try...except' statements. Without doing it for
you, (I assume this is homework) these are some suggested changes:

out_file = open('persons.txt', 'w')
while True:
name = raw_input(What is the name: )
age = raw_input(What is the age: )
out_file.write(name:%s\nage: %s\n\n (name, age))

# We'll never get this far unless we figure out a way to stop the loop!
out_file.close()


Keep at it and best of luck!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to create memory backed file?

2009-12-27 Thread Modulok
List,

How do I create a file which exists only in memory? (Think diskless.)

I need to create an in-memory file. I need to pass this file, as a
regular file object, to a subprocess. Unfortunately, the 'mmap'
module's file-like object doesn't appear to work quite like a regular
file would. (I simply assume that mmap would be the way to go. Other
suggestions welcome!) That, or I'm doing something terribly wrong. For
example:

import mmap
import sys
from subprocess import Popen, PIPE

fishes = one fish\ntwo fish\nred fish\nblue fish\n

###
# With a real file, this works:
###
fd = open('fish.txt', 'w')
fd.write(fishes)
fd = open('fish.txt', 'r')
proc1 = Popen(['cat'], stdin=fd, stdout=sys.stdout, stderr=sys.stderr)

###
# This doesn't (with mmap file):
###
vfd = mmap.mmap(-1, len(fishes), mmap.MAP_PRIVATE)
vfd.write(fishes)
vfd.seek(0)
proc2 = Popen(['cat'], stdin=vfd.fileno(), stdout=sys.stdout, stderr=sys.stderr)

I just get the following error:

Traceback (most recent call last):
  File stdin, line 1, in module
AttributeError: fileno


I'm using Python 2.5, so I cannot use that slick
'SpooledTemporaryFile' method of the 'tempfile' module. The 'cat' is
just a simple Unix system command for the purpose of illustration.

Thanks!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to create memory backed file?

2009-12-27 Thread Modulok
Kent,

Thanks! I think that'll do it. I don't know what this list would do without you!

-Modulok-

On 12/27/09, Kent Johnson ken...@tds.net wrote:
 On Sun, Dec 27, 2009 at 3:36 AM, Modulok modu...@gmail.com wrote:
 List,

 How do I create a file which exists only in memory? (Think diskless.)

 I need to create an in-memory file. I need to pass this file, as a
 regular file object, to a subprocess. Unfortunately, the 'mmap'
 module's file-like object doesn't appear to work quite like a regular
 file would. (I simply assume that mmap would be the way to go. Other
 suggestions welcome!) That, or I'm doing something terribly wrong.

 How about using a pipe for stdin? This seems to work:

 import sys
 from subprocess import Popen, PIPE

 fishes = one fish\ntwo fish\nred fish\nblue fish\n

 proc1 = Popen(['cat'], stdin=PIPE, stdout=sys.stdout, stderr=sys.stderr)
 proc1.stdin.write(fishes)
 proc1.stdin.close()

 Kent

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] More on unit testing - tests for external data...

2009-12-10 Thread Modulok
So, this, 'test environment', this is just like a directory where I
place my code and associated files to test for the existence (and
non-existence) of various stuff, right? Any real-world examples/case
studies to point to?

It seems like there are a lot of people on this list interested in
getting more familiar with unit testing, but not a whole lot of
non-trivial, python-specific examples being passed around. I can write
a function in a programming 101 class that accepts two arguments and
returns a value by computing the hypotenuse of a triangle (or
whatever). I can then build a unit-test for that making sure it fails
and passes as needed. Cake. But jump into the real-world where many
things are not so trivial, and I'm at a loss for where this
unit-testing business all fits in.

Basically, I'm trying to become a better programmer. (Who isn't?) I'd
like to transition from 'hacky but gets the job done' or 'oh my God it
actually works' to 'eloquent and bulletproof'. Without some kind of a
mentor or vast array of tutorials to lay down the law when I screw up,
or pass on some kind of approval when I get something right -  it's
been frustrating as hell.

Case studies/tutorials anyone?

Thanks!
-Modulok-

On 12/10/09, spir denis.s...@free.fr wrote:
 Wayne Werner waynejwer...@gmail.com dixit:

 On Wed, Dec 9, 2009 at 6:15 PM, Alan Gauld
 alan.ga...@btinternet.comwrote:

 
  Remember, in testing you are not trying to prove it works but rather to
  demonstrate that it doesn't!
 

 So in that way it's a bit like the the scientific method (or exactly
 like)?
 You create a hypothesis and design tests to invalidate your hypothesis...
 and if they fail to invalidate you may have a valid hypothesis. Simply
 replace hypothesis with program and you get the testing procedure?

 -Wayne



 programming is modelizing -- like a scientist's job

 Denis
 

 la vita e estrany

 http://spir.wikidot.com/
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] More on unit testing - tests for external data...

2009-12-09 Thread Modulok
List,

Unit testing functions and methods which rely on passed data is simple
enough. However:

How do I unit test something which relies on external data?

For example, a function which creates a file only if it doesn't exist
on disk, or a unit test for a function which makes an SQL query? If
anyone could point to a few examples of such usage, that would be
great!

Thanks!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python time

2009-11-27 Thread Modulok
 Doesn't time.time return a float?

  import time
  help(time.time)
 Help on built-in function time in module time:

 time(...)
 time() - floating point number

 Return the current time in seconds since the Epoch.
 Fractions of a second may be present if the system clock provides
 them.


  time.time()
 1259288538.576565

 Right?
 -Modulok-

 For sure, but this wasn't my question. I was precisely asking how python
 does that.

Clearly I have a mighty need to consume more coffee. My apologies for
misreading the original post.
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python time

2009-11-26 Thread Modulok
Doesn't time.time return a float?

 import time
 help(time.time)
Help on built-in function time in module time:

time(...)
time() - floating point number

Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.


 time.time()
1259288538.576565

Right?
-Modulok-

On 11/26/09, Kent Johnson ken...@tds.net wrote:
 On Wed, Nov 25, 2009 at 11:11 AM, spir denis.s...@free.fr wrote:
 Hello,

 How does python get the time in microseconds? (In other words, how would I
 get it if python (like some other languages) would provide time in whole
 seconds only?)

 Use the source...in particular, see floattime() in timemodule.c:
 http://svn.python.org/view/python/branches/release31-maint/Modules/timemodule.c?view=markup

 Kent
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Fwd: Help on finding the 1000th prime

2009-11-16 Thread Modulok
Also watch things like letter case on stuff like 'Print' and 'While',
they should instead be 'print' and 'while', (all lowercase).

-Modulok-

On 11/16/09, bob gailer bgai...@gmail.com wrote:

 Here is the code that doesn't work.


 Thanks for posting the code. What doesn't work mean?
 error messages?
 unexpected results?
 or what?

 There are several problems in your code.
  - The candidates you are testing. Walk thru the program and list a few
 of them and see if you can determine that problem.
  - Counting primes as you discover them. Same advice as above.
  - indentation is screwed up. Please use only spaces - no tabs.
 primeCount = 0
 primeCandidate = 2
 While primeCount = 1000:
 isPrime = True
primeCandidate = primeCandidate + 2
for x in range(2, primeCandidate):
if primeCandidate % x == 0:
print primeCandidate, equals, x, *, primeCandidate/x
isPrime = False
 Print primeCandidate
break
 If isPrime:
primeCount = primeCount + 2
 Print primeCandidate



 --
 Bob Gailer
 Chapel Hill NC
 919-636-4239
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] OT: Writing code while tired, counterproductive?

2009-11-14 Thread Modulok
List,

This is kind off topic, but:

Does anyone else find, writing code while tired to be counterproductive?

It just seems like when I push myself to stay up late finishing a
project, I sorely regret it the following day. Granted, Python is a
fairly forgiving language and doesn't take the mental attention that
some others require (like C++ ...or someone else's C++ or someone
else's poorly written C++), but for me, writing code while tired
usually ends up being a bad thing - In any language. But then there's
the guilt of taking the day off and not meeting deadlines. *grumble*
Just wondering if this is a common occurrence among the masses.

Anyone?
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to call a method with a print statement?

2009-11-13 Thread Modulok
List,

 __repr__() is exactly what I was looking for :)

You guys rock! Thank you.
-Modulok-

On 11/12/09, Dave Angel da...@ieee.org wrote:


 Kent Johnson wrote:
 On Thu, Nov 12, 2009 at 6:35 AM, Luke Paireepinart
 rabidpoob...@gmail.com wrote:

 On Thu, Nov 12, 2009 at 5:29 AM, Jeff R. Allen j...@nella.org wrote:

 You are looking for the __str__ method. See
 http://docs.python.org/reference/datamodel.html#object.__str__


 Can't you also implement __repr__?


 Yes, in fact if you are only going to implement one of __str__ and
 __repr__, arguably __repr__ is a better choice. __repr__() is called
 by the interactive interpreter when it displays an object. __str__ is
 called by print, and if you don't define __str__ it will call
 __repr__. So defining only __str__ will not give a custom
 representation unless you print:

 In [1]: class Foo():
...: def __str__(self):
...: return I'm a Foo

 In [2]: f = Foo()

 In [3]: f
 Out[3]: __main__.Foo instance at 0x1433468

 In [4]: print f
 I'm a Foo


 Defining __repr__ will give the custom representation when you just
 give the name of the object:

 In [5]: class Foo2():
...: def __repr__(self):
...: return I'm a Foo2
...:
...:

 In [6]: f2=Foo2()

 In [7]: f2
 Out[7]: I'm a Foo2

 In [8]: print f2
 I'm a Foo2

 Kent


 And one other important place that uses __repr__() is the printing of
 containers.  So if you have a list of Foo2 objects, and you want to just say
 print mylist

 it's better to have __repr__().


 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to call a method with a print statement?

2009-11-12 Thread Modulok
List,

How do I get a print statement to call a class method? I'm using
python 2.5. I did it long ago, but can't remember how, or even where I
learned it from. Something like:

class Foo():
   def __init__(self):
  pass

   def  ***part I can't remember goes here***
  print hello world!

 # Now use it:
bar = Foo()
print bar
hello world! #-- Magic!


If any of this makes sense, any pointers would be great!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Evaluating a string expression

2009-11-05 Thread Modulok
[snip]
 I would like to know how would I evaluate a string expression in python.
 For example, if i say:
 a = 3*2
 I want to do something to evaluate the variable 'a' to give me 6. How
 can I do this?
[/snip]

The eval() function can do this:

   eval(3*2)

WARNING: Long winded security rant below...

Be *very* careful what strings you pass to eval(). It is executing
code! If you're doing this in a controlled environment it's not a
problem. If this is part of a bigger program which is going to be used
by other people, perhaps even online, this is a potentially *huge*
security risk. You will either have to very carefully parse the users
input to control what they can and cannot do, or better, strictly
control what the kernel permits the process to do. This includes what
hardware resources (memory/processor time) the process is allowed.
This way, even if (when) the process is hijacked, the damage will be
very limited.

Such a feat is accomplished by having the program execute as a user
who has very limited permissions. This is something best (only?) done
on UNIX/Linux/BSD flavored systems. This could be done via a setuid
binary, or a *carefully written* root process which immediately
demotes its privilege level upon execution/spawning of children. (Such
a model is employed by programs like apache's httpd server, where one
process is root owned and does nothing but spawn lesser privileged
processes to handle untrusted data.) If this is something you're
interested in, the os module features functions like, 'setuid()',
'setgid()', and notably 'chroot()'. For further security yet, you
might look into isolating a process from the rest of the system, as is
the case with FreeBSD's jails.

These are really big topics and in the end, it really depends on what
'untrusted source' constitutes, and your operating environment.
Writing bulletproof code in regards to security is challenging. It is
a very specialized topic worthy of further study. But in most
situations executing code from an untrusted source is a *really* bad
idea, even with precautions as those outlined in the example URL
provided by one of the other responses.
(http://effbot.org/zone/librarybook-core-eval.htm)

Sorry for all the lecture. I'll shut up now. :p
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] why is os.path.walk so slow?

2009-11-04 Thread Modulok
[snip]
 I need to synchronize the files on my home and office machine and have
 been using someone else's code for this to date but have been
 frustrated by how slow it is in getting the information on files for
 the mounted drive from my office machine...
[/snip]

Not to cut your coding project short, and it may not even be
applicable, but have you looked into rsync? They kind of wrote the
book on efficiency in regards to synchronization of files.

Just a thought.
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Stolen thread: Bottom folk vs. toppers was trouble using 2to3.py

2009-11-03 Thread Modulok
[snip]
 The war between bottom posters and top posters has been long, arduous,
 and most often incredibly silly. There have been written group rules
 mandating one over the other. Oft times these rules have doomed the
 group.


Two words come to mind: Bikeshed color.

 I simply propose that the only requirement to communications here is
 that replies and questions be well formulated, courteous, and reasonably
 intelligent.

Yup.
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generating unique ID

2009-10-29 Thread Modulok
 I'm writing an application which will hold a database of people. Ofcourse,
 people can have the same name, so I want to stock them with an unique ID.

 I've searched and found some things:
 - uuid.uuid4()
 - id(name)
 - os.urandom(n)

 But they seem overkill to me. Well, maybe not id().

 What should I use the best for this? Maybe examples of other programs that
 do something alike?

Use the auto-increment feature of your database database management
backend. (Assuming you're using a database backend like MySQL,
postgresql, etc.) In MySQL your database description would look
something like this (with any other fields  you need):

# MySQL table description:

CREATE TABLE IF NOT EXISTS mytable (
   `uid`BIGINT unsigned NOT NULL auto_increment unique,
   `uname`  CHAR(32) NOT NULL default guest,
PRIMARY KEY (`uid`));


You could use MySQLdb (third party python module) to talk to the MySQL
process with Python. Other database managers have similar abilities.

 os.urandom(n)

Random numbers are random, NOT unique.

If you're using your own backend, like a text file or whatever, stop.
Take the time to learn to use a database manager like postgresql or
MySQL or whatever. They have already solved many of the problems
you're now facing. It will be well worth the time and frustration.

Otherwise, you'll have to parse your database and get the previously
used value and then increment that. However, this solution will fail
if there are multiple processes, or threads accessing the data
concurrently. To solve that problem you'll have to introduce some
manner of mutex to gurantee that only one process has access to the
unique data at any given time. Things get complicated. All of these
problems have already been solved with other database managers. Use
them!

In a pinch, with a low volume database for non-critical data, you
could probably get away with using a Unix epoch style timestamp with
sufficient granularity. But even this is in no way, guaranteed to be
unique. It's just, probably unique. It would look like this:

 import time
 time.time()
1256796357.661967

If it absolutely must be unique, use a database manager that can make
that guarantee.

Best of luck!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to load a dict into a dict subclass?

2009-10-28 Thread Modulok
snip
...
 Assume I have a dict, 'foo'. I also have my own class, 'Bar', which
 subclasses (i.e. is a derived class) of a dict. How do I eloquently
 get foo into an instace of Bar? Example:


 ### BEGIN CODE:
 class Bar(dict):
pass # Act like a dict for now.

 foo = {'a': 100, 'b': 200, 'c': 300} # This could be a function return
 value.
 myvar = Bar()
 # The hacky feeling part:
 for k,v in foo.items(): myvar[k] = v

 ### END CODE

 You can use the built-in function for dictionaries called update.  So

   class Bar(dict):
   pass

   foo = {'a':100, 'b':200, 'c': 300}
   myvar = Bar()
   myvar.update(foo)
   myvar
 {'a': 100, 'c': 300, 'b': 200}
...
/snip

Thanks guys!

Christian, that's just what I was looking for. Thank you!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to load a dict into a dict subclass?

2009-10-27 Thread Modulok
List,

I'm new to the list, (somewhat new to python too). My code feels
hacky. I'd like to know if there is a more eloquent way (more below).
If not, a general thumbs up from more experienced programmers would be
great!

Assume I have a dict, 'foo'. I also have my own class, 'Bar', which
subclasses (i.e. is a derived class) of a dict. How do I eloquently
get foo into an instace of Bar? Example:


### BEGIN CODE:
class Bar(dict):
   pass # Act like a dict for now.

foo = {'a': 100, 'b': 200, 'c': 300} # This could be a function return value.
myvar = Bar()
# The hacky feeling part:
for k,v in foo.items(): myvar[k] = v

### END CODE

Obviously I can put the dict into an instance variable, but then
methods like 'keys()' and such won't work. If that makes any sense...

Thanks guys!
-Modulok-
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor