Re: [Tutor] OT: Drag and Drop GUI IDE ideas

2011-07-28 Thread Adam Bark
Rance Hall  gmail.com> writes:
> We want the students to develop a small app in the process, It could
> be a firefox extension, mobile phone app, or any other type simple
> structure.
> 
> The catch is that the class is for non-programmers to try to get them
> introduced to the field.  We would like to use a gui ide that can
> essentially hide the code from the programmer and connect widgets with
> the gui.
> 
> We want them to be able to look at the code and analyze it.
> 
> We would prefer open source (read: free as in beer) tools.
> 
> Does anyone have any ideas of tools that can do this?
> 
> we are open to any idea, android sdk and gui, ipad sdk and some gui tool, etc.
> 
> Thanks for your time.
> 
> Rance

Hi, this isn't free but seems to tick all your other boxes
http://radicalbreeze.com/ It gives a graphical representation of your program as
well as access to the source code of your application. It creates code for many
different platforms including mobile ones and it's DRM free.
HTH,
Adam.


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


Re: [Tutor] serial device emulator

2011-07-05 Thread Adam Bark
What Chris is getting at is that you'll use some module, eg pyserial, to 
interface with the serial port. So if you write a little module that has 
the same interface then you can pretend you have a serial port attached 
device and then switch over to an actual one without changing anything 
else in your code but the import.


## myserial.py ##
class Serial:
def __init__(self, port=None):
pass
def open(self):
pass
def close():
pass
def read(size=1):
return 'a' * size
def write(data):
return len(data)
#

## foo.py ##
import myserial as serial
#import serial ## Use this in production

port = serial.Serial()
port.open()
print port.write("hello, world")
print port.read(3)


I hope that makes it clearer to you.
Adam.
P.S. none of that code has been tested


On 05/07/11 13:03, Edgar Almonte wrote:

thanks chirs but i think  i don't follow you , can you elaborate more ?

Thanks

On Mon, Jul 4, 2011 at 8:49 PM, Chris Fuller
  wrote:

You don't need to emulate a serial port (since you're writing the code; you'd
have to emulate the port if it was standalone software), only your serial port
library.  Write a class that has the same methods as the serial port library
you're using (you only need the methods you're using or think you might use
later), and fill them in with the appropriate code so it behaves like your real
device.

Cheers

On Monday 04 July 2011, Edgar Almonte wrote:

Hello list need some advice/help with something, i am doing a program
in python that send some command via serial to a device so far so good
, the thing is not have the program so i need make another program
that emulate the behavior of this serial device ( is quiet simple ) to
test my app
i read abou that i can use pseudo terminal in linux but not sure how
attatch the pseudo terminal /dev/pts5 example to a fake_device.py file
or something like that.

maybe this question is not so python but i will appreciate some help.


Thanks
___
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 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 Adam Bark

On 25/05/11 19:54, Modulok wrote:

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."
If he's just planning on making a few passwords I think the period of 
2**19937-1 of the Mersenne twister is plenty large enough not to worry 
about.

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


Re: [Tutor] after(), how do I use it?

2011-04-25 Thread Adam Bark

On 26/04/11 01:36, michael scott wrote:
Hello, I asked for help in another location and it solved my problem, 
but the only problem is I don't fully understand the after function. 
Here is part of the code that was given to me.



def print_label_slowly(self, message):
'''Print a label one character at a time using the event loop'''
t = self.label.cget("text")
t += message[0]
self.label.config(text=t)
if len(message) > 1:
self.after(500, self.print_label_slowly, message[1:])

I understand it, and the gist of how it works, but the self.after... I 
can not find any documentation on it (because after is such a common 
word), so can you guys tell me how it works. Is this a built in 
function (didn't see it on the built in function list)? Does it always 
take 3 arguements? Is this a user made function and I'm just 
overlooking where it was defined at?


The function you have shown there appears to be a class method. 
self.after means you are calling another method of the same function 
that print_label_slowly is a part of.
Do you have the rest of the code? If you're still confused post it and 
hopefully we can clear it up for you.


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


Re: [Tutor] lambda

2011-03-19 Thread Adam Bark

On 19/03/11 14:44, Ajit Deshpande wrote:
I am trying to figure out where lambda functions can be useful. Has 
anyone used them in real world?


From my reading so far, I hear people claim that lambda can be a 
useful replacement for small functions. Most examples  didn't make 
much sense to me. Why would anyone use a one liner anonymous function, 
if you never plan to use it elsewhere? You would then be implementing 
the logic directly in the line, isn't it?. Functions are useful if 
they plan to get called multiple times within your code.


For example:

add_one = lambda x: x + 1

In real world, why would I use a lambda for this. I would simply do:

add_one = x + 1

Can you provide some useful use cases for lambda functions?

~ Ajit Deshpande


Here's one from the python docs, reduce takes a function so technically 
the programmer only uses it once but the program calls it many times. 
Map is another that works similarly. Have a look into functional 
programming as that's the branch of computer science those two functions 
and lambdas tend to come from I believe.

http://docs.python.org/library/functions.html?highlight=lambda#reduce

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


Re: [Tutor] multiple if and or statement

2011-03-14 Thread Adam Bark

On 14/03/11 19:41, Mike Franon wrote:

HI,

I had a question, when running this small snippet of test code:



a = ['test1', 'flag', 'monday']

for i in a:
 if i == 'test1' or 'test2':
print 'true'


It always prints true


$ ./testing.py
true
true
true


I know I am missing something, but in reality it should only print
true once correct?


Any string that isn't blank ie '' is true. In your test you've asked 
whether i == 'test1' is true or 'test2' is true not i == 'test2' is true.
I hope that's not too confusing, I can make it clearer if you're having 
a problem.


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


Re: [Tutor] Concatenating string

2011-02-22 Thread Adam Bark

On 22/02/11 13:46, tee chwee liong wrote:

hi,

>>> bin(0xff0)
''
>>> bin(0xff1)
'0001'
>>> a=bin(0xff0)+bin(0xff1)
>>> a
'0001'
>>> b=0xff0
>>> c=0xff1
>>> d=b+c
>>> d
8161
>>> bin(d)
'1'

question:
1) why is it that a and d values are different? i'm using Python 2.5.
2) how to convert hex to bin in Python 2.5?


thanks
tcl

Hi,

1) As you can see bin() returns a binary representation of the number 
you pass to it as a string. Thus when you do a=bin(0xff0)+bin(0xff1) you 
are concatenating the two strings returned by bin. For d you are 
carrying out the mathematical addition operation on the two numbers 
before converting it to binary.

2) You've already done that several times, just use bin()

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


Re: [Tutor] question regarding regular expression compile

2011-01-12 Thread Adam Bark

On 12/01/11 13:19, Yaniga, Frank wrote:
I am determining a regular expression that can recognize the any of 
the following strings:

MAT file log\20101225 deleted
MAT file billing\20101225 deleted
MAT file util\20101225 deleted
MAT file carrier\20101225 deleted
I begin by creating a regular expression object so that I can reuse it 
in multiple operations:

test = re.compile('MAT file
for log, billing, util, and carrier I use an arbitrary match:
(log|billing|util|carrier)
for 20101225 I use decimal digit with repetition match:
\d{8}
and finish with:
delete')
My question is how do I handle the backslash (NOTE: the match must 
only be a backslash)?


Hi Frank,

There are two things you need to know, the first is that \ is a special 
character in re's, which I think you probably know already. Also they 
are special characters in python strings unless you use raw strings. So 
to look for the backslash in your example you need to use a raw string 
(technically you could use twice as many backslashes to escape the 
python specialness and re but it looks horrible) by starting the string 
with r"your regular expression". Then you need to use two backslashes to 
give you a backslash character. So your re should now look like this:


test = re.compile(r"MAT file (log|billing|util|carrier)\\\d{8} deleted")

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


Re: [Tutor] 'or' in assignment (not if statement)?

2010-12-09 Thread Adam Bark

On 10/12/10 00:51, Alex Hall wrote:

Hi all,
I am reading the source of a project I hope to help with
(http://www.qwitter-client.net). I sometimes see something like:
val=val or 1
I am guessing that val is an int. If val==0, the 'or' kicks in and
val=1, else the or is not needed and val=val. Am I close? Can other
words or symbols be used in contexts where one would not normally
think of them?
Thanks.

   

Hi Alex,

This is one of those times the interactive interpreter comes in handy eg:

In [1]: val=5

In [2]: val=val or 1

In [3]: val
Out[3]: 5

In [4]: val=0

In [5]: val=val or 1

In [6]: val
Out[6]: 1

You are right by the way and I know you can't test every possibility 
but, as you already suspected the outcome, this just reinforces it I think.


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


Re: [Tutor] calling a method within a function

2010-12-07 Thread Adam Bark

On 07/12/10 22:36, John wrote:

Hello,

I have a strange problem with a piece of code I've written. It's a bit
overly complicated to make an example with, but the gist is below. But
in the example below, it works. However, in my example, when I call
the method from within the function, it returns something other than
what I expect. If I call the method outside the function, it behaves
properly???

   
It's hard to tell, from an example that doesn't display the same 
behaviour, what the problem is but it sounds like there must be some 
problem with the way you're calling the method from your function that 
isn't happening otherwise. Can you post the full source somewhere and 
mail a link to the mailing list?

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


Re: [Tutor] role playing game - help needed

2010-12-07 Thread Adam Bark

On 07/12/10 22:10, Al Stern wrote:

Tried to use the documentation but still getting the errors...
The 1st one has to do with the available_points
# set variables
attributes = {"strength": 0, "health": 0, "wisdom": 0, "dexterity": 0}
MAX_POINTS = 30
available_points = MAX_POINTS - attributes.values()
keys = attributes.keys()
values = attributes.values()
this is the error i'm getting...
Traceback (most recent call last):
  File "C:\Users\Public\Documents\My Python 
programs\role_playing_game1.py", line 8, in 

available_points = MAX_POINTS - attributes.values()
TypeError: unsupported operand type(s) for -: 'int' and 'dict_values'
I know using attributes.values here isn't correct but I can't figure 
out how to put the sum of the values into that equation.


Using attributes.values is fine. There is a built in function for 
summing all the values in a sequence, it's called "sum".


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


Re: [Tutor] Pyserial and invalid handle

2010-11-30 Thread Adam Bark

On 01/12/10 01:00, John Smith wrote:


Hi, Walter -

I got pywin32-214.win32-py2.7.exe because I have the Intel i7 (I'm 
guessing that the AMD versions are for the AMD processor). However, 
all of the exe offerings have the same "Python not found in registry" 
problem that started this whole thing.


So, since the only source module available is pywin32-214.zip, I got 
it and installed it. It does not work, maybe because I'm using Python 
2.7 and the zip is for 3.2.


I really appreciate all the time you have put into my problems, 
Walter. Thank you.


Cheers,
John



Actually, AMD 64 is now the standard x86-64. It was originally designed 
by AMD because intel were making their Itanium thing but that didn't go 
so well. Anyway if you're running 64 bit windows that's probably why the 
32-bit python install is having a problem. Download the version Walter 
suggested and you should be good to go.

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


Re: [Tutor] Random Number Question

2010-11-24 Thread Adam Bark

On 24/11/10 22:10, Jeff Goodwin wrote:
Ok, I found the problem, I had saved the file as random.py looks like 
that was a no-no. Its working now that I changed the name.

Thanks!
Jeff

Ah yes always avoid giving your modules names that appear in the 
standard library. It goes wrong, sometimes in unexpected ways.


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


Re: [Tutor] Random Number Question

2010-11-24 Thread Adam Bark

On 24/11/10 21:51, Jeff Goodwin wrote:

Hello,
I'm trying to find a way to use the random.randint function to 
generate a random number, but everytime I run the program it locks up 
IDLE. Here is what I have so far:

import random
def main():
 x = input("Enter a number: ")
 y = input("Enter a different number: ")
 z = random.randint(x,y)
print "The random number between ", x, " and ", y, " is ", z
main()
Can you tell me where I'm going wrong here? When I run the program it 
allows me to enter the numbers for x and y, then freezes.


Thanks!
Jeff


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
   
Your print statement isn't indented. It should print "the random number 
between" and then throw an exception I think. You should either move the 
print statement into the function or have main return x, y, z and print 
the return values of it.


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


Re: [Tutor] Assistance with Psuedocode

2010-11-17 Thread Adam Bark

On 18/11/10 00:49, Alan Gauld wrote:


"Joe Ohmer"  wrote


The following code works well but I don't understand why
the mysteryEffect code block changes the picture.
Doesn’t 64*(r/64) just equal r?


That dependfs on which version of Python you use.
In  earlier versions '/' meant integer division so

(1/64) * 64=> 0 * 64
(120/64) * 64 => 1 * 64
(128/64) * 64 => 2 * 64
(130/64) * 64 => 2 * 64

So only in the case of exact multiples of 64 does it do
what you expect. However, if you have a recent version
of Python (2.6? onwards) '/' means floating point division
so now you get the result you expect (subject to rounding
error)

HTH,

Roughly what I was about to say. 2.6 doesn't do floating point division 
as standard. I think you can import that behaviour.

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


Re: [Tutor] Accessing columns of a CSV file

2010-11-17 Thread Adam Bark

On 17/11/10 13:59, Hanlie Pretorius wrote:

Hi,

I'm reading a CSV file and I want to test the contents of its second
column before I write it to an output file:

   

import csv
time_list=['00:00', '03:00', '06:00','09:00','12:00','15:00','18:00','21:00']
readfile='C8R004_flow.csv'
in_text=open(readfile,'rb')
cr=csv.reader(in_text)
cr
 

<_csv.reader object at 0x7f4dfc3b2360>
   

for row in cr:
 

... print row
['2005/01/31', '21:00:00', '26.508']
['2005/01/31', '21:12:00', '26.508']
['2005/01/31', '21:24:00', '26.508']
['2005/01/31', '21:36:00', '26.508']
['2005/01/31', '21:48:00', '26.508']
['2005/01/31', '22:00:00', '26.508']
['2005/01/31', '22:12:00', '26.508']
['2005/01/31', '22:24:00', '26.508']
['2005/01/31', '22:36:00', '26.508']
['2005/01/31', '22:48:00', '26.508']
['2005/01/31', '23:00:00', '26.508']
['2005/01/31', '23:12:00', '26.508']
['2005/01/31', '23:24:00', '26.508']
['2005/01/31', '23:36:00', '26.508']
['2005/01/31', '23:48:00', '26.508']
   
 

I would like to test the values in the second column to see if they're
in the list I named time_list and, if so, write the whole row to an
output file.

The problem is that I don't know how to access the second column of
values. I tried the direct route:
   

for row in cr:
 

... print cr[1]
...
   
You need to print the 2nd item of row not of the entire file ie "print 
row[1]" not "print cr[1]".


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


Re: [Tutor] While Loops: Coin Flip Game

2010-11-14 Thread Adam Bark

On 14/11/10 22:16, Dawn Samson wrote:

Greetings,

I'm a Python beginner and working my way through Michael Dawson's 
Python Programming for the Absolute Beginner. I'm stuck in a 
particular challenge that asks me to write a program that "flips a 
coin 100 times and then tells you the number of heads and tails." I've 
been trying to work on this challenge for a while now and can't get it 
to work (either it has 100 heads or 100 tails). I've been reworking 
this code many times and currently what I have does not do anything at 
all at IDLE. Please take a look at my code below:


import random

# set the coin
coin = random.randrange(2)
headsCount = 0
tailsCount = 0
count = 0

# the loop
while count <= 100:
coin
if coin == 0:
headsCount += 1
if coin == 1:
tailsCount += 1
count += 1

print "The number of heads was", heads
print "The number of tails was", tails

raw_input("\n\nPress the enter key to exit.")

Thanks,
S. Dawn Samson
You try to print two variables, "heads" and "tails" which don't exist. 
The other replies covered the other main problems.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] if statement

2010-11-02 Thread Adam Bark

On 02/11/10 19:36, christopher.h...@allisontransmission.com wrote:



Glen Clark wrote on 11/02/2010 03:07:18 PM:

in general you should use raw_input instead of input.


> confirmed = int(input("Are you happy with this? (y/n): ")
>

It would appear that Glen is using python 3.x as he used the print 
function so input is correct.


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


Re: [Tutor] if statement

2010-11-02 Thread Adam Bark

On 02/11/10 19:07, Glen Clark wrote:

sorry:

NumItems = int(input("How many Items: "))


Entries = []
for In in range(0,NumItems):
Entries.append("")



for In in range(0,NumItems):
Entries[In]=str(input("Enter name " + str(In+1) + ": "))


for In in range(0,NumItems):
print(Entries[In])

confirmed = int(input("Are you happy with this? (y/n): ")

if confirmed == "y":
for In in range(0,NumItems):
   print(Entries[In] + ": " + str(In))
change = int(input("Which item would you like to change: ")
Entries[change]=str(input("Please enter a nem name: ")
else:
 #do nothing

print(Entries)

   

Ok that's easier, you're missing a closing bracket at the end of the

confirmed = int(input("Are you happy with this? (y/n): ")

line.
I think you might need at least a pass after else as well, although it 
should be fine to leave it out altogether once you've added the ')'.


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


Re: [Tutor] if statement

2010-11-02 Thread Adam Bark

On 02/11/10 19:02, Glen Clark wrote:

  File "/home/glen/workspace/test.py", line 19
 if confirmed == "y":
^
SyntaxError: invalid syntax

Why does this not work??? PyDev says "Expected:else"
   

It's hard to tell without context. Can you send the code around it as well?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Summing up numbers in a file

2010-10-26 Thread Adam Bark

On 26/10/10 21:20, masawudu bature wrote:

How do I sum all occurrences of  a number in a file?
I have a file with a bunch of numbers, each on it's own line:
5
3
11
3
7
3
5
5
11
7
7
...
How do i sum them up so that the output will be ,
5 :  15
3 :   9
11:  22
7 :   21

Assuming you know how to iterate through a file, you could try saving 
the number of occurrences of each number in the file into a dictionary.

Something like:

if num in my_dict:
my_dict[num] += 1
else:
my_dict[num] = 1

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


Re: [Tutor] What is random.triangular() used for

2010-10-24 Thread Adam Bark

On 24/10/10 21:57, Richard D. Moores wrote:

On Sun, Oct 24, 2010 at 13:29, Emile van Sebille  wrote:

   

 From people who would know found at
http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.triangular.html


"""The triangular distribution is often used in ill-defined problems where
the underlying distribution is not known, but some knowledge of the limits
and mode exists. Often it is used in simulations."""
 

Emile,

from the source code link on that page, I got

# Draw values from the distribution and plot the histogram:

import matplotlib.pyplot as plt
h = plt.hist(np.random.triangular(-3, 0, 8, 10), bins=200,
  normed=True)
plt.show()

Which when I run it I get
Traceback (most recent call last):
   File "c:\P26Working\untitled-8.py", line 2, in
 h = plt.hist(np.random.triangular(-3, 0, 8, 10), bins=200, normed=True)
NameError: name 'np' is not defined
Process terminated with an exit code of 1

The import goes OK:

   

import matplotlib.pyplot as plt

 

and apparently I have numpy, if that's relevant:
   

import numpy

 

but where do I get np?

Dick
   
I think he may be using ipython but putting an "import numpy as np" 
should get that code to work.

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


Re: [Tutor] searching for newlines does not work!

2010-10-23 Thread Adam Bark

On 23/10/10 23:03, win...@interchange.ubc.ca wrote:

This is driving me batty!

In the interactive window, I can use string.replace on newlines for 
some strings and not for others.


Here is what work for newlines:

b...@bill-laptop:~$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> test=r"a \n b \n c \n"
>>> test.replace(r"\n","***")
'a *** b *** c ***'

Yay! So far, so good. But now I put in a string with newlines, test2, 
using the triple quote method :


>>> test2="""
... a
... b
... c
... """
>>> test2.replace(r"\n","***")
'\na\nb\nc\n'
>>> test2
'\na\nb\nc\n'

Boo! It does not work. So there here is my question: Why does test 
work but test2 does not? (And: Why me?)


Thanks for any suggestions,

Bill
The problem is your use of 'r' which means raw string. This means that 
rather than /n meaning new line it literally means the character '/' 
followed by the character 'n'.
In your first example you put the characters into the string test and 
replaced the characters.
The second example you have actual newlines and are searching for the 
characters "/n" which don't exist in your string.


HTH,
Adam.

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


Re: [Tutor] What does "TypeError: 'int' object is not iterable"mean?

2010-10-23 Thread Adam Bark

On 23/10/10 13:38, Alan Gauld wrote:


"Steven D'Aprano"  wrote


It would have to be a *very* old version. The use of * as the width
parameter in format strings goes back to the Dark Ages of Python 1.5:
...
I believe this is a virtual copy of string formatting from C, in which
case it probably goes back to the 80s or even the 70s.


This got me wondering so I dug out my copy of the original K&R (1978)
and there is no mention of * in the format specifiers description.
(There is for scanf but there it is a field suppressor)

I don't have an ANSI C version of K&R at home so can't say if it got
added as part of the ANSI C process - around 1990? - but neither
of my ANSI C books mention it either.

So it may not be a part of C after all.

Interesting, I wonder where it did first appear?

Alan G.

It is indeed in the ANSI version of K&R.
"Width or precision or both may be specified as *, in which case the 
value is computed by converting the next argument(s), which must be 
int." (The C Programming Language; B. W. Kernighan, D. M. Ritchie; 1988)

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


Re: [Tutor] Converting from unicode to nonstring

2010-10-14 Thread Adam Bark

On 14/10/10 20:33, David Hutto wrote:

On Thu, Oct 14, 2010 at 3:31 PM, David Hutto  wrote:
   

On Thu, Oct 14, 2010 at 3:24 PM, Adam Bark  wrote:
 

On 14/10/10 20:21, David Hutto wrote:
   

On Thu, Oct 14, 2010 at 2:58 PM, Adam Barkwrote:

 
   

Actually, I needed it to be converted to something without a string
attached to it. See a post above, and it was fixed by eval(),

Thanks though. And I'm sure at some point this morning in a moment of
frustration rather than logic, I tried your approach.


 

What do you mean by "without a string attached to it"?
Also using eval could be dangerous unless you're sure the stuff coming
out
of your dbase is safe.


   

Read the above posts and it should be explanation enough.

 

I did read them and it's really not clear.

   

I needed to have:
self.lines = self.newplot.plot(self.plot)

from the data I brought in I got the following when the variable
above(self.plot) was inserted:

self.lines = self.newplot.plot(u'plot')

So by applying eval:

self.lines = self.newplot.plot(eval(self.plot))

It then inserted the following  when the variable self.plot was used:

self.lines = self.newplot.plot(eval(plot)

no u'stringhere' in the second version with eval around the variable.


I hope that makes it clearer. Otherwise I might have to let you borrow
my Windex to clean the screen.

 

In other words I needed (1,2,3,4) not u'(1,2,3,4)' to be inserted for
variable self.plot
   
In which case the code Sanders sent you is a much more sensible way of 
recovering your data. Evalling the string u'plot' still doesn't make 
much sense to me though. I think I may have been overestimating the 
quality of your code.

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


Re: [Tutor] Converting from unicode to nonstring

2010-10-14 Thread Adam Bark

On 14/10/10 20:21, David Hutto wrote:

On Thu, Oct 14, 2010 at 2:58 PM, Adam Bark  wrote:
   



Actually, I needed it to be converted to something without a string
attached to it. See a post above, and it was fixed by eval(),

Thanks though. And I'm sure at some point this morning in a moment of
frustration rather than logic, I tried your approach.

   

What do you mean by "without a string attached to it"?
Also using eval could be dangerous unless you're sure the stuff coming out
of your dbase is safe.

 

Read the above posts and it should be explanation enough.
   

I did read them and it's really not clear.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting from unicode to nonstring

2010-10-14 Thread Adam Bark

On 14/10/10 19:29, David Hutto wrote:

On Thu, Oct 14, 2010 at 2:19 PM, Sander Sweers  wrote:
   

On 14 October 2010 16:14, David Hutto  wrote:
 

(u'graph1', u'Line', u'222', u'BLUE', u'1,2,3,4', u'True', u'0,5,0,10')

Which is a tuple of unicode strings. From this I
need to place portions of the tuple into other fields,
but not as unicode strings, but literals no ''.

For example if I have the following line:

self.lines = self.newplot.plot([1,2,3,4])
   

So you want convert string u'1,2,3,4' to a list of ints [1,2,3,4]?
Then the below will work.

[int(n) for n in u'1,2,3,4'.replace(',', '')]

 

Actually, I needed it to be converted to something without a string
attached to it. See a post above, and it was fixed by eval(),

Thanks though. And I'm sure at some point this morning in a moment of
frustration rather than logic, I tried your approach.
   

What do you mean by "without a string attached to it"?
Also using eval could be dangerous unless you're sure the stuff coming 
out of your dbase is safe.

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


Re: [Tutor] pickle problem

2010-10-12 Thread Adam Bark

On 12/10/10 18:35, Roelof Wobben wrote:

Hello,

I have this code :

import urllib
import pickle

image = urllib.URLopener()
image.retrieve("http://www.pythonchallenge.com/pc/def/peak.html","banner.p"; )
plaatje = open("banner.p", "rb")
plaatje2 = pickle.load(plaatje)

But it gives this output :

Traceback (most recent call last):
   File "C:\Users\wobben\workspace\oefeningen\src\test2.py", line 7, in
 plaatje2 = pickle.load(plaatje)
   File "C:\Python27\lib\pickle.py", line 1378, in load
 return Unpickler(file).load()
   File "C:\Python27\lib\pickle.py", line 858, in load
 dispatch[key](self)
KeyError: '<'


What does this mean ?
   
It means that it's trying to access a sequence with the key '<' but it's 
not working. It looks like the problem is you're trying to open 
peak.html as a pickle but it is actually an html file.


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


Re: [Tutor] Hiding Superclass Methods

2010-10-11 Thread Adam Bark

On 11/10/10 23:52, Steven D'Aprano wrote:

On Tue, 12 Oct 2010 01:55:10 am Adam Bark wrote:
   

On 11/10/10 15:29, Denis Gomes wrote:
 

Thank you both for your responses.  I do have one other question if
I use the method both of you describe. How do I go about
implementing slicing and indexing for an object in python?  A list
object innately has them and that is really why I wanted to use it.
  I would appreciate it if you can point me to something.
Denis
   

You can use __getslice__, __setslice__ etc. methods. They're detailed
in the list docstrings. Here's an example of using __getslice__
 

__getslice __setslice__ and __delslice__ have been deprecated since
version 2.0, seven versions ago.

http://docs.python.org/reference/datamodel.html#object.__getslice__

You should use __getitem__ __setitem__ and __delitem__, and detect if
your argument is an integer or a slice object, and behave accordingly.

http://docs.python.org/reference/datamodel.html#object.__getitem__

   

Oh right, 2.6 doesn't say anything about it in the docstrings.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Hiding Superclass Methods

2010-10-11 Thread Adam Bark

On 11/10/10 15:29, Denis Gomes wrote:
Thank you both for your responses.  I do have one other question if I 
use the method both of you describe. How do I go about implementing 
slicing and indexing for an object in python?  A list object innately 
has them and that is really why I wanted to use it.  I would 
appreciate it if you can point me to something.

Denis
You can use __getslice__, __setslice__ etc. methods. They're detailed in 
the list docstrings. Here's an example of using __getslice__


>>> dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', 
'__delslice__', '__doc__', '__eq__', '__format__', '__ge__', 
'__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', 
'__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', 
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
'__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', 
'__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 
'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>> print [].__getslice__.__doc__
x.__getslice__(i, j) <==> x[i:j]

   Use of negative indices is not supported.
>>> print [].__setslice__.__doc__
x.__setslice__(i, j, y) <==> x[i:j]=y

   Use  of negative indices is not supported.
>>> class TestSlice(object):
... def __getslice__(self, i, j):
... print i, j
...
>>> t = TestSlice()
>>> t[2:3]
2 3

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


Re: [Tutor] selecting elements from dictionary

2010-09-15 Thread Adam Bark

On 15/09/10 15:31, Hs Hs wrote:

Dear Steven,
Thanks for your help.

however I have a question,

using:

for key, value in xdic.items():
if 1 in value and 2 in value or 3 in value:
print key


also print keys that have values such as [1,2,3].

In cases where there is [1,2,3] and [1,2] also reported.

How can I extract those keys that have values only [1,2] and [1,3] 
exclusively.



>>> xdic = {75796988: [1, 2, 3], 75797478: [1, 2, 3], 75797887:[1,2], 
75797987:[3,1]}

>>> for key, value in xdic.items():
... if 1 in value and 2 in value or 3 in value:
... print key
...
75797987
75796988
75797478
75797887


Here all 4 keys appear. Instead I want to get only 75797887:[1,2] and 
75797987:[3,1]

how can I force this.
If you just have a few specific cases you can use "in" to check whether 
the values you are interested in appear in a specified collection, ie:


>>> xdic = {75796988: [1, 2, 3], 75797478: [1, 2, 3], 75797887:[1,2], 
75797987:[3,1]}

>>> for key, value in xdic.items():
... if value in ([1,2], [2,1], [1,3], [3,1]):
... print key
...
75797987
75797887

HTH


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


Re: [Tutor] How to numerically sort strings that start with numbers?

2010-09-13 Thread Adam Bark

On 14/09/10 02:24, Pete O'Connell wrote:

Hi I don't actaully need the list printed reversed, I need it printed
from smallest number to largest

   

Just sorting gives you the list from smallest to largest.

For example:
#

theList = ["21 trewuuioi","374zxc","13447"]
print sorted(theList)
   

['13447', '21 trewuuioi', '374zxc']
 

#the rabove result is not what I want


If I reverse that I still don't get the items in numerical order. The
result I want is:
   

['21 trewuuioi','374zxc','13447']
 

Before you said you wanted it like this:  ['3zxc','21 trewuuioi','134445']

The order above isn't in any obvious numerical order.
Anyway I think I see where you are coming from. In my previous example I 
forgot to assign the sorted list back to theList. Hopefully the 
following will make this clear.


>>> theList = ["21 trewuuioi","3zxc","134445"]
>>> sorted(theList)
['134445', '21 trewuuioi', '3zxc']
>>> theList
['21 trewuuioi', '3zxc', '134445']
>>> theList = sorted(theList)
>>> theList
['134445', '21 trewuuioi', '3zxc']
>>> theList[::-1]
['3zxc', '21 trewuuioi', '134445']
>>> theList.reverse()
>>> theList
['3zxc', '21 trewuuioi', '134445']

as you can see sorted makes a new list rather than modifying your original.

On Tue, Sep 14, 2010 at 10:41 AM, Adam Bark  wrote:
   

On 14/09/10 01:11, Pete O'Connell wrote:
 

theList = ["21 trewuuioi","3zxc","134445"]
print sorted(theList)

Hi, the result of the sorted list above doesn't print in the order I
want. Is there a straight forward way of getting python to print
['3zxc','21 trewuuioi','134445']
rather than ['134445', '21 trewuuioi', '3zxc']?

Any help would be greatly appreciated
Pete

   

print sorted(theList)[::-1]

as list indices go [start:end:step] what this means is the whole list
starting from the end and working backwards.
You can also have a look at reversed() if you want an iterator or you can
use theList.reverse() if you want to reverse in place ie.

 

l = ["21 trewuuioi","3zxc","134445"]
l.reverse()
print l
   

['134445', '3zxc', '21 trewuuioi']


HTH
___
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] How to numerically sort strings that start with numbers?

2010-09-13 Thread Adam Bark

On 14/09/10 01:11, Pete O'Connell wrote:

theList = ["21 trewuuioi","3zxc","134445"]
print sorted(theList)

Hi, the result of the sorted list above doesn't print in the order I
want. Is there a straight forward way of getting python to print
['3zxc','21 trewuuioi','134445']
rather than ['134445', '21 trewuuioi', '3zxc']?

Any help would be greatly appreciated
Pete
   

print sorted(theList)[::-1]

as list indices go [start:end:step] what this means is the whole list 
starting from the end and working backwards.
You can also have a look at reversed() if you want an iterator or you 
can use theList.reverse() if you want to reverse in place ie.


>>> l = ["21 trewuuioi","3zxc","134445"]
>>> l.reverse()
>>> print l
['134445', '3zxc', '21 trewuuioi']


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


Re: [Tutor] What's the best way to ask forgiveness here?

2010-09-13 Thread Adam Bark

On 13/09/10 20:12, Brian Jones wrote:
Thanks for the replies so far. One thing that's probably relevant: 
once a directory is created, I can expect to write a couple of hundred 
files to it, so doing a 'try os.makedirs' right off the bat strikes me 
as coding for the *least* common case instead of the *most* common 
(which is that the directory exists and the file write succeeds). If 
this were a one-off file write well then things get easier, but 
I'd like to avoid attempting a makedirs 100 times when 99 of those 
times I know it'll give me an error.


brian

On Mon, Sep 13, 2010 at 3:07 PM, Evert Rol > wrote:


> I've been coding Python long enough that 'asking forgiveness
instead of permission' is my first instinct, but the resulting
code is sometimes clumsy, and I wonder if someone can suggest
something I'm missing, or at least validate what's going on here
in some way.
>
> What I'm trying to do is write a file to a directory. However,
the directory may not exist the first time I try to write a file
there, so I'm going to first try to write the file, and if I get
an exception, create the directory (er, *try* to), and *then*
write the file there.

That would work.
Though I would just try to create the error directory first. If
that fails, I check the error message/code in the except clause:
if it indicates the directory already exists, I pass the
exception, otherwise reraise it.
Then I continue with creating the file within the directory I now
am certain of exists.
Note 1: certain is only half: some other process could remove the
directory in the split second between my code creating it and my
code creating the file. If you think that could happen, you'll
need to look at the other ways to do this.
Note 2: the directory can exist, but not have write access to your
process. So between the try-except for creating a directory and
the try-except for creating a file, you may put in a try-except
for chmod. Of course, if you're not the owner, both the chmod and
file creation will fail (I'm assuming some *nix platform here, btw).

> Here's my first shot at the code:
>
> try:
> self.save_file(picfile_fullpath, picdata)
> except IOError as err:
> # directory doesn't exist. Try to create it.

Careful: you're not checking the actually error given by the
exception. There may be more than one reason that the file can't
be created (examples: the permissions mentioned above, or some
file creation limit in a directory).


> try:
> os.makedirs(picfile_fullpath)
> except OSError as oserr:
> logging.error("Can't create file path: %s (%s)"
% (picfile_fullpath, oserr))
> else:
> # Created dir, now write file.
> try:
> self.save_file(picfile_fullpath, picdata)
> except IOError as err:
> logging.error("Bailing. Couldn't save file
%s (%s)" % (picfile_fullpath, err))
> return False
>
> Doesn't this seem less readable than the 'ask permission'
equivalent? I think it does, but in this case asking permission
for every single operation when the dir will only need to be
created a single time (and then may be written to several hundred
times) is pretty wasteful.

One of the things I once read (but I forgot where) on this issue,
is the usual "it depends". It depends whether you except that
often, the directory doesn't exist and the file can't directly be
created. In that case, if may be quicker to ask permission first
(simple if-statement). If you expect that in general, you can
immediately create the file within the directory (so an exception
is unlikely to occur), then use a try-except clause.
But don't take my word for it; I'd be curious what others on this
list say about this.


>
> I suppose I could set some sentinel variable and check for it in
a while loop, but then I need some other scaffolding code to make
sure I don't infinitely loop trying to create the directory, and
probably some other stuff I'm forgetting, so it strikes me as
being just as messy.
>
> Is there a clean sort of pattern to apply in instances like this?

I guess not, though readability of code is an important thing to
consider. In this case, I don't find the correctly unreadable, but
at some point, these things do tend to get out of hand and you're
better off coding it differently (perhaps even using functions).


 Evert

Well surely then you just check the directory first with a try: 
os.makedirs. Then your try: self.savefile for each file.


___
Tutor maillist  -  T

Re: [Tutor] What's the best way to ask forgiveness here?

2010-09-13 Thread Adam Bark

On 13/09/10 19:31, Brian Jones wrote:
I've been coding Python long enough that 'asking forgiveness instead 
of permission' is my first instinct, but the resulting code is 
sometimes clumsy, and I wonder if someone can suggest something I'm 
missing, or at least validate what's going on here in some way.


What I'm trying to do is write a file to a directory. However, the 
directory may not exist the first time I try to write a file there, so 
I'm going to first try to write the file, and if I get an exception, 
create the directory (er, *try* to), and *then* write the file there. 
Here's my first shot at the code:


try:
self.save_file(picfile_fullpath, picdata)
except IOError as err:
# directory doesn't exist. Try to create it.
try:
os.makedirs(picfile_fullpath)
except OSError as oserr:
logging.error("Can't create file path: %s (%s)" % 
(picfile_fullpath, oserr))

else:
# Created dir, now write file.
try:
self.save_file(picfile_fullpath, picdata)
except IOError as err:
logging.error("Bailing. Couldn't save file %s 
(%s)" % (picfile_fullpath, err))

return False

Doesn't this seem less readable than the 'ask permission' equivalent? 
I think it does, but in this case asking permission for every single 
operation when the dir will only need to be created a single time (and 
then may be written to several hundred times) is pretty wasteful.


I suppose I could set some sentinel variable and check for it in a 
while loop, but then I need some other scaffolding code to make sure I 
don't infinitely loop trying to create the directory, and probably 
some other stuff I'm forgetting, so it strikes me as being just as messy.


Is there a clean sort of pattern to apply in instances like this?

Thanks.
brian


How about something like this?

try:
os.makedirs(picfile_fullpath)
self.save_file(picfile_fullpath, picdata)
except IOError, OSError as err:
if type(err) is OSError:
logging.error("Can't create file path: %s (%s)" % 
(picfile_fullpath, oserr))

try:
self.save_file(picfile_fullpath, picdata)
except IOError:
logging.error("Bailing. Couldn't save file %s (%s)" % 
(picfile_fullpath, err))

else:
logging.error("Bailing. Couldn't save file %s (%s)" % 
(picfile_fullpath, err))


This saves you one try except and the else although it adds an if else. 
Either way it's not as far nested.

I just thought up another way that just takes two try excepts:

try:
try:
os.makedirs(picfile_fullpath)
self.save_file(picfile_fullpath, picdata)
except OSError as oserr:
logging.error("Can't create file path: %s (%s)" % 
(picfile_fullpath, oserr))

self.save_file(picfile_fullpath, picdata)
except IOError as err:
logging.error("Bailing. Couldn't save file %s (%s)" % 
(picfile_fullpath, err))

return False

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


Re: [Tutor] Serial communication ...

2010-09-13 Thread Adam Bark

On 13/09/10 16:36, Markus Hubig wrote:

Hi @all!

I'm about to write a class for serial communication on Win32 and Linux 
which
provides a method called "talk" to send something over the serial 
line, wait for
the answer and returns it. My problem is, that I don't know how long 
the answer

will be (ok max 260 bytes but most answers are much smaller).

This is what I have now, please leave some comments:

   1. Will this work on Win32 (with select)?
   2. Should I better use twisted.internet.serialport?
   3. Will self.read(260)block until it reads the full 260 bytes?

class SerialDevice(Serial):

def __init__(self,port):
Serial.__init__(self)
self.port = port
self.baudrate = 57600
self.bytesize = EIGHTBITS
self.parity = PARITY_ODD
self.stopbits = STOPBITS_TWO
self.timeout = 0
self.xonxoff = 0
self.rtscts = 0
self.dsrdtr = 0
self.open()
self.flush()
def _write(self, packet):
fileno = self.fileno()
while True:
readable, writeable, excepts = select( [], [fileno], [], 0.2 )
if fileno in writeable:
time.sleep(0.1)
length = self.write(packet)
break
return length
def _read(self):
fileno = self.fileno()
while True:
readable, writeable, excepts = select( [], [fileno], [], 0.2 )
if fileno in readable:
time.sleep(0.1)
packet = self.read(260)
break
return packet
def talk(self, packet):
self._write(packet)
responce = self._read()
return responce

Thank you, Markus

--
Can't read my mail? Just don't hold it that way!
Ideally you would send a specific ending packet and you read one byte at 
a time until the right sequence comes up. Alternatively you could have 
the first byte as a length indicator. The only other options I can think 
of are fixed length or a specific timeout.

HTH.

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


Re: [Tutor] Lost in the control flow

2010-08-13 Thread Adam Bark

On 11/08/10 18:14, Eduardo Vieira wrote:

On Tue, Aug 10, 2010 at 1:56 PM, Adam Bark  wrote:

   

The problem is you don't call make_dict unless there's a "FUEL SURCHARGE" or
multiple pins. Also you don't add the first pin to mydict["tracking"] unless
there's a "FUEL SURCHARGE".

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

 

Hi, I made these changes, got rid of the functions, and changed some logic:
here is the link: http://pastebin.com/F19vKUjr

Now mydict will be changing, of course with every loop, as the output below:
{'company': 'CITY SIGNS', 'tracking': ['600775301143'], 'id': '1'}
{'city': 'MEDICINE HAT', 'company': 'CITY SIGNS', 'tracking':
['600775301143'], 'id': '1', 'prov': 'AB'}
{'city': 'MEDICINE HAT', 'company': 'TRIMLINE', 'tracking':
['600775301150'], 'id': '2', 'prov': 'AB'}
{'city': 'ROCKY MOUNTAIN HOUSE', 'company': 'TRIMLINE', 'tracking':
['600775301150'], 'id': '2', 'prov': 'AB'}
{'city': 'ROCKY MOUNTAIN HOUSE', 'company': 'TS SIGNS PRINTING&
PROMO', 'tracking': ['600775301168'], 'id': '3', 'prov': 'AB'}
{'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING&  PROMO',
'tracking': ['600775301168'], 'id': '3', 'prov': 'AB'}
{'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING&  PROMO',
'tracking': ['600775301168', '600775301168'], 'id': '3', 'prov': 'AB'}
{'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING&  PROMO',
'tracking': ['600775301168', '600775301168', '600775301176'], 'id':
'3', 'prov': 'AB'}
{'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING&  PROMO',
'tracking': ['600775301168', '600775301168', '600775301176',
'600775301184'], 'id': '3', 'prov': 'AB'}
{'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING&  PROMO',
'tracking': ['600775301168', '600775301168', '600775301176',
'600775301184', '600775301192'], 'id': '3', 'prov': 'AB'}
{'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING&  PROMO',
'tracking': ['600775301168', '600775301168', '600775301176',
'600775301184', '600775301192', '600775301200'], 'id': '3', 'prov':
'AB'}
so I appended everything to a bigdata list and used it to update the
dictionary data_dict

I can't understand why I get only one value:
{'18': {'city': 'ESTEVAN',
 'company': 'BRAKE&  DRIVE SYSTEMS',
 'id': '18',
 'prov': 'SK',
 'tracking': ['600775301515', '600775301515', '600775301523']}}

Regards,

Eduardo
   
It looks to me like you keep overwriting the previous data, you keep 
using mydict. Doing an append does not copy the dictionary it just 
copies a reference to the underlying data structure.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] elif statement

2010-08-10 Thread Adam Bark

On 11/08/10 02:34, Sudarshana Banerjee wrote:
Hi: I am trying to teach myself Python, and am stuck at the 
indentation with the elif statement.


This is what I am trying to type (as copied from the textbook):

x=3
if x==0:
print "x is 0"
elif x&1 ==1:
print "x is a odd number"
elif x&1==0: -- Line 6
print "x is a even number"

If I am combining the if and the print statement, then the elif 
statement is in the next line, and all is well with the world. If 
however, I write the print as a separate statement, I am getting a 
syntax error after I press Enter after keying the first elif statement.


>>> x=3
>>> if x==0:
print x
elif x==2:


Here you have indented the elif statement but it should be at the same 
level as the if:

>>> x=3
>>> if x==0:
... print x
... elif x==2:
... print "something else"
...
>>>



SyntaxError: invalid syntax

Again:
>>> x=3
>>> if x==2: print x
elif x&1 == 1: print 'x is odd'
>>> elif x&1 ==0: print 'x is even'
SyntaxError: invalid syntax


I'm not sure what's going on here but the second elif is being 
interpreted separate to the rest of the if statement hence a SyntaxError:

>>> elif x&1 == 0: print "x is even"
  File "", line 1
elif x&1 == 0: print "x is even"
   ^
SyntaxError: invalid syntax

This works:
>>> if x==2: print x
... elif x&1 == 1: print 'x is odd'
... elif x&1 ==0: print 'x is even'
...
x is odd




If I am pressing two Enters, the code executes; so I have a elif 
without a if, and again, a syntax error. What am I not doing right?


Thank you.

Sudarshana.

HTH,
Adam.


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


Re: [Tutor] Lost in the control flow

2010-08-10 Thread Adam Bark

On 10/08/10 20:39, Eduardo Vieira wrote:

Hello, list! I'm trying to parse a text file. I'm getting confuse with
my strategy, and flags or how to use a sequence of ifs or elifs,
continue, etc. Anyhow, after several experiments this is close to what
I'd like to get, except, I can't find a way to include all the pin
numbers (12 number sequence):

Here is my code:
http://pastebin.com/1ps6WdF4

The example file is this:
http://pastebin.com/1MZmE4d3


Basically, as a initial step, I'd like to transform this:
17   600775301465  CAREYON SIGNS&  GRAPHICS  EXP  5
  93.00   $0.00  $ 26.77

RED DEER AB T4N1L2
FUEL SURCHARGE:2.10


   GST/HST:1.44



  600775301465  18.60

  600775301473  18.60

  600775301481  18.60


into this. View the code and file for details, please:
{'city': 'AB', 'company': 'CAREYON SIGNS&  GRAPHICS', 'tracking':
['600775301465', '600775301473', '600775301481',  ], 'id': '17'}


The way the code is working now I only get this:
{'city': 'AB', 'company': 'CAREYON SIGNS&  GRAPHICS', 'tracking':
['600775301465', '600775301465'], 'id': '17'}, and a only the ones
that have multiple pin numbers.

I'd appreciate your help. Thanks.

Eduardo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor
   
The problem is you don't call make_dict unless there's a "FUEL 
SURCHARGE" or multiple pins. Also you don't add the first pin to 
mydict["tracking"] unless there's a "FUEL SURCHARGE".


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


Re: [Tutor] "x and y" means "if x is false, then x, else y"??

2010-07-22 Thread Adam Bark
On 6 July 2010 02:05, Lie Ryan  wrote:

> On 07/05/10 22:23, Adam Bark wrote:
>
> >
> > I should add that this is how something like:
> >
> > if x != y:
> > do_something()
> >
> > works, if expects a True or False (this isn't always true but works for
> > comparison operators expressions such as this).
> >
>
>  "if" expects an expression that can be converted to True or False
> by calling its __bool__()/__nonzero__(); in case of missing
> __bool__/__nonzero__, then the object is considered True. 
>
>
Well put, I couldn't decide how to phrase it without adding confusion but
you hit the nail on the head.
Cheers,
Adam.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Path?

2010-07-15 Thread Adam Bark
On 15 July 2010 17:21, Jim Byrnes  wrote:

> Adam Bark wrote:
>
>> On 14 July 2010 17:41, Jim Byrnes  wrote:
>>
>>  Adam Bark wrote:
>>>
>>>  On 14 July 2010 02:53, Jim Byrnes   wrote:
>>>>
>>>>  Adam Bark wrote:
>>>>
>>>>>
>>>>> 
>>>>>
>>>>>
>>>>>  If I use the terminal to start the program it has no problem using the
>>>>>
>>>>>   file.  There are multiple files in multiple directories so I was
>>>>>>
>>>>>>>  looking
>>>>>>>>> for
>>>>>>>>> a way to just double click them and have them run.  If it turns out
>>>>>>>>> that
>>>>>>>>> I
>>>>>>>>> must make changes to or for each of the files it will be easier to
>>>>>>>>> just
>>>>>>>>> keep
>>>>>>>>> using the terminal.  I've only been using Ubuntu for a few months
>>>>>>>>> so
>>>>>>>>> I
>>>>>>>>> was
>>>>>>>>> surprised that the program could not see a file that is in the same
>>>>>>>>> directory.
>>>>>>>>>
>>>>>>>>> Regards,  Jim
>>>>>>>>>
>>>>>>>>>
>>>>>>>>>
>>>>>>>>>  The problem is ubuntu doesn't run the script from the directory
>>>>>>>> it's
>>>>>>>> in
>>>>>>>> so
>>>>>>>> it's looking for wxPython.jpg somewhere else.
>>>>>>>>
>>>>>>>>
>>>>>>>>  OK, I mistakenly thought that double-clicking on file in Nautilus
>>>>>>>> would
>>>>>>>>
>>>>>>>>  take care of the path info.
>>>>>>>
>>>>>>> In my reply above I also mentioned that I tried by dropping it on a
>>>>>>> Launcher on the top panel and that the command the launcher uses is
>>>>>>> usr/bin/python2.6.  Is there a way that the command can be changed so
>>>>>>> that
>>>>>>> it will look in the same directory the python script is in for any
>>>>>>> file
>>>>>>> it
>>>>>>> needs?
>>>>>>>
>>>>>>> Thanks,  Jim
>>>>>>>
>>>>>>>
>>>>>>>
>>>>>> Not sure if you got my previous email but you could try writing the
>>>>>> bash
>>>>>> script I posted (with the $1 line to get the path) and setting that as
>>>>>> your
>>>>>> launcher, I think it should work.
>>>>>>
>>>>>> Let me know if you didn't get it or it doesn't work.
>>>>>>
>>>>>> HTH,
>>>>>> Adam.
>>>>>>
>>>>>>
>>>>>>  I got it, got sidetracked and then forgot to look at it again.
>>>>>>  Thanks
>>>>>>
>>>>> for
>>>>> reminding me.  Your idea works, but with one little downside.  The
>>>>> directories I am working with are chapters in a book.  So as I move
>>>>> from
>>>>> chapter to chapter I will need to change the bash script, but this
>>>>> seems
>>>>> to
>>>>> be less typing than using the terminal.
>>>>>
>>>>>
>>>>> Thanks,  Jim
>>>>>
>>>>>
>>>>>  Ok cool, glad it works. It might be possible to get the path so you
>>>> don't
>>>> have to set it each time, try this:
>>>>
>>>> #!/bin/bash
>>>> IFS="/"
>>>> path=($1)
>>>> cd $(path[0:#path[*]])
>>>> python $1
>>>>
>>>>
>>>> # Warning, I'm not exactly a competent bash programmer so this may not
>>>> work
>>>> :-p
>>>>
>>>> Let me know if you need a hand to fix it,
>>>>
>>>> HTH,
>>>> Adam.
>>>>
>>>>
>>>>  I tried the new bash code but when I dropped a file on the launcher it
>>> just
>>> flashed an gave no output.  So I tried running the bash script
>>> (name=runpython) in a terminal and got this error:
>>>
>>> /home/jfb/runpython: line 4: path[0:#path[*]]: command not found
>>> Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
>>> [GCC 4.4.3] on linux2
>>> Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>>
>>>>>>
>>> I know even less about bash than you do, so I don't where to start to
>>> debug
>>> this.
>>>
>>>
>>> Thanks,  Jim
>>>
>>> Ok then, this time it's tested and not just improvised, here we go:
>>>
>>
>> #!/bin/bash
>>
>> script=$1 # Full path for calling the script later
>> orig_IFS=$IFS # This is to reset IFS so that "script" is correct
>> (otherwise
>> has spaces instead of /)
>> IFS="/"
>> path=( $1 )
>> IFS=$orig_IFS
>> last_ind=${#pa...@]} # Works out the length of path
>> let "last_ind -= 1" # Sets last_ind to index of script name
>> len_path=${pa...@]:0:last_ind} # Gets the path without the script name
>> let "len_path=${#len_path[0]} + 1" # This gives the length of the script
>> string upto just before the last /
>> cd ${scri...@]:0:len_path} # cds to the path
>> python script
>>
>>
>> As pretty much my first non-trivial bash script it's probably horrible but
>> it seems to work.
>>
>> HTH,
>> Adam.
>>
>>
> There must be something different in our setups because it did not work for
> me.  If I run it from a terminal I get:
>
> j...@jfb-ubuntu64:~$ /home/jfb/runpython_test bitmap_button.py
> /home/jfb/runpython_test: line 12: cd: b: No such file or directory
> python: can't open file 'script': [Errno 2] No such file or directory
> j...@jfb-ubuntu64:~$
>
> Thanks  Jim
>
>
Oh cock, I missed a $ sign it should be "python $script". Seems to complain
about the path as well though, not sure about that one, I'll get back to you
later.

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


Re: [Tutor] Path?

2010-07-14 Thread Adam Bark
On 14 July 2010 17:41, Jim Byrnes  wrote:

> Adam Bark wrote:
>
>> On 14 July 2010 02:53, Jim Byrnes  wrote:
>>
>>  Adam Bark wrote:
>>>
>>> 
>>>
>>>
>>>  If I use the terminal to start the program it has no problem using the
>>>
>>>>  file.  There are multiple files in multiple directories so I was
>>>>>>> looking
>>>>>>> for
>>>>>>> a way to just double click them and have them run.  If it turns out
>>>>>>> that
>>>>>>> I
>>>>>>> must make changes to or for each of the files it will be easier to
>>>>>>> just
>>>>>>> keep
>>>>>>> using the terminal.  I've only been using Ubuntu for a few months so
>>>>>>> I
>>>>>>> was
>>>>>>> surprised that the program could not see a file that is in the same
>>>>>>> directory.
>>>>>>>
>>>>>>> Regards,  Jim
>>>>>>>
>>>>>>>
>>>>>>>
>>>>>> The problem is ubuntu doesn't run the script from the directory it's
>>>>>> in
>>>>>> so
>>>>>> it's looking for wxPython.jpg somewhere else.
>>>>>>
>>>>>>
>>>>>>  OK, I mistakenly thought that double-clicking on file in Nautilus
>>>>>> would
>>>>>>
>>>>> take care of the path info.
>>>>>
>>>>> In my reply above I also mentioned that I tried by dropping it on a
>>>>> Launcher on the top panel and that the command the launcher uses is
>>>>> usr/bin/python2.6.  Is there a way that the command can be changed so
>>>>> that
>>>>> it will look in the same directory the python script is in for any file
>>>>> it
>>>>> needs?
>>>>>
>>>>> Thanks,  Jim
>>>>>
>>>>>
>>>>
>>>> Not sure if you got my previous email but you could try writing the bash
>>>> script I posted (with the $1 line to get the path) and setting that as
>>>> your
>>>> launcher, I think it should work.
>>>>
>>>> Let me know if you didn't get it or it doesn't work.
>>>>
>>>> HTH,
>>>> Adam.
>>>>
>>>>
>>>>  I got it, got sidetracked and then forgot to look at it again.  Thanks
>>> for
>>> reminding me.  Your idea works, but with one little downside.  The
>>> directories I am working with are chapters in a book.  So as I move from
>>> chapter to chapter I will need to change the bash script, but this seems
>>> to
>>> be less typing than using the terminal.
>>>
>>>
>>> Thanks,  Jim
>>>
>>>
>> Ok cool, glad it works. It might be possible to get the path so you don't
>> have to set it each time, try this:
>>
>> #!/bin/bash
>> IFS="/"
>> path=($1)
>> cd $(path[0:#path[*]])
>> python $1
>>
>>
>> # Warning, I'm not exactly a competent bash programmer so this may not
>> work
>> :-p
>>
>> Let me know if you need a hand to fix it,
>>
>> HTH,
>> Adam.
>>
>>
> I tried the new bash code but when I dropped a file on the launcher it just
> flashed an gave no output.  So I tried running the bash script
> (name=runpython) in a terminal and got this error:
>
> /home/jfb/runpython: line 4: path[0:#path[*]]: command not found
> Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
> [GCC 4.4.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>>
>
> I know even less about bash than you do, so I don't where to start to debug
> this.
>
>
> Thanks,  Jim
>
> Ok then, this time it's tested and not just improvised, here we go:

#!/bin/bash

script=$1 # Full path for calling the script later
orig_IFS=$IFS # This is to reset IFS so that "script" is correct (otherwise
has spaces instead of /)
IFS="/"
path=( $1 )
IFS=$orig_IFS
last_ind=${#pa...@]} # Works out the length of path
let "last_ind -= 1" # Sets last_ind to index of script name
len_path=${pa...@]:0:last_ind} # Gets the path without the script name
let "len_path=${#len_path[0]} + 1" # This gives the length of the script
string upto just before the last /
cd ${scri...@]:0:len_path} # cds to the path
python script


As pretty much my first non-trivial bash script it's probably horrible but
it seems to work.

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


Re: [Tutor] Path?

2010-07-14 Thread Adam Bark
On 14 July 2010 02:53, Jim Byrnes  wrote:

> Adam Bark wrote:
>
> 
>
>
>  If I use the terminal to start the program it has no problem using the
>>>>> file.  There are multiple files in multiple directories so I was
>>>>> looking
>>>>> for
>>>>> a way to just double click them and have them run.  If it turns out
>>>>> that
>>>>> I
>>>>> must make changes to or for each of the files it will be easier to just
>>>>> keep
>>>>> using the terminal.  I've only been using Ubuntu for a few months so I
>>>>> was
>>>>> surprised that the program could not see a file that is in the same
>>>>> directory.
>>>>>
>>>>> Regards,  Jim
>>>>>
>>>>>
>>>>
>>>> The problem is ubuntu doesn't run the script from the directory it's in
>>>> so
>>>> it's looking for wxPython.jpg somewhere else.
>>>>
>>>>
>>>>  OK, I mistakenly thought that double-clicking on file in Nautilus would
>>> take care of the path info.
>>>
>>> In my reply above I also mentioned that I tried by dropping it on a
>>> Launcher on the top panel and that the command the launcher uses is
>>> usr/bin/python2.6.  Is there a way that the command can be changed so
>>> that
>>> it will look in the same directory the python script is in for any file
>>> it
>>> needs?
>>>
>>> Thanks,  Jim
>>>
>>
>>
>> Not sure if you got my previous email but you could try writing the bash
>> script I posted (with the $1 line to get the path) and setting that as
>> your
>> launcher, I think it should work.
>>
>> Let me know if you didn't get it or it doesn't work.
>>
>> HTH,
>> Adam.
>>
>>
> I got it, got sidetracked and then forgot to look at it again.  Thanks for
> reminding me.  Your idea works, but with one little downside.  The
> directories I am working with are chapters in a book.  So as I move from
> chapter to chapter I will need to change the bash script, but this seems to
> be less typing than using the terminal.
>
>
> Thanks,  Jim
>

Ok cool, glad it works. It might be possible to get the path so you don't
have to set it each time, try this:

 #!/bin/bash

IFS="/"
path=($1)
cd $(path[0:#path[*]])
python $1


# Warning, I'm not exactly a competent bash programmer so this may not work
:-p

Let me know if you need a hand to fix it,

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


Re: [Tutor] Path?

2010-07-13 Thread Adam Bark
On 13 July 2010 23:27, Jim Byrnes  wrote:

> Adam Bark wrote:
>
>> On 13 July 2010 14:43, Jim Byrnes  wrote:
>>
>>  Steven D'Aprano wrote:
>>>
>>> My apologizes to Steven and the list, when I replied originally I messed
>>> up
>>> and sent it to him privately which was not my intention.
>>>
>>>
>>>
>>>  On Mon, 12 Jul 2010 03:42:28 am Jim Byrnes wrote:
>>>>
>>>>> I am running Ubuntu.  I downloaded the source code examples for a
>>>>> book I purchased.  Some of the examples load image files located in
>>>>> the same directory as the program.  If I go to the current directory
>>>>> in the terminal the program can use the image files.  However, if I
>>>>> use a launcher or the filemanager it pops up an error dialog saying
>>>>> the file does not exist even though it is in the same directory.
>>>>>
>>>>> The program simply uses the files name.  Is there a way without
>>>>> editing the source and inserting the full path to run the program
>>>>> from a launcher or the filemanager and allow it to see files in the
>>>>> current directory?
>>>>>
>>>>
>>>> What file manager are you using? Nautilus? Konqueror? Something else?
>>>>
>>>
>>> Nautilus. I have it configured to run files with the extension .py when
>>> they are double clicked.
>>>
>>>
>>>  What do you mean, "use a launcher"? Use a launcher to do what? What sort
>>>> of launcher?
>>>>
>>>
>>> It runs programs and sits on the panel at the top of my Ubuntu desktop.
>>>  The command it uses is usr/bin/python2.6.  These are wxPython examples I
>>> am
>>> working with.
>>>
>>>
>>>  What pops up an error dialog? The launcher?
>>>>
>>>
>>> I am assuming Python. The title bar of the dialog says Python2 Error, the
>>> message is   Can't load image from file 'wxPython.jpg': file does not
>>> exist.
>>>
>>>
>>>  Which file does it claim doesn't exist? Python? The Python script? The
>>>> image file? What is the exact error message it gives?
>>>>
>>>
>>> See above.  The line that triggers the error is:  image =
>>> wx.Image('wxPython.jpg', wx.BITMAP_TYPE_JPEG)
>>>
>>>
>>>  There's probably a way to tell the launcher which working directory to
>>>> use, but of course that depends on the answers to the above questions.
>>>>
>>>>
>>> If I use the terminal to start the program it has no problem using the
>>> file.  There are multiple files in multiple directories so I was looking
>>> for
>>> a way to just double click them and have them run.  If it turns out that
>>> I
>>> must make changes to or for each of the files it will be easier to just
>>> keep
>>> using the terminal.  I've only been using Ubuntu for a few months so I
>>> was
>>> surprised that the program could not see a file that is in the same
>>> directory.
>>>
>>> Regards,  Jim
>>>
>>
>>
>> The problem is ubuntu doesn't run the script from the directory it's in so
>> it's looking for wxPython.jpg somewhere else.
>>
>>
> OK, I mistakenly thought that double-clicking on file in Nautilus would
> take care of the path info.
>
> In my reply above I also mentioned that I tried by dropping it on a
> Launcher on the top panel and that the command the launcher uses is
> usr/bin/python2.6.  Is there a way that the command can be changed so that
> it will look in the same directory the python script is in for any file it
> needs?
>
> Thanks,  Jim


Not sure if you got my previous email but you could try writing the bash
script I posted (with the $1 line to get the path) and setting that as your
launcher, I think it should work.

Let me know if you didn't get it or it doesn't work.

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


Re: [Tutor] Path?

2010-07-13 Thread Adam Bark
On 13 July 2010 14:43, Jim Byrnes  wrote:

> Steven D'Aprano wrote:
>
> My apologizes to Steven and the list, when I replied originally I messed up
> and sent it to him privately which was not my intention.
>
>
>
> > On Mon, 12 Jul 2010 03:42:28 am Jim Byrnes wrote:
> >> I am running Ubuntu.  I downloaded the source code examples for a
> >> book I purchased.  Some of the examples load image files located in
> >> the same directory as the program.  If I go to the current directory
> >> in the terminal the program can use the image files.  However, if I
> >> use a launcher or the filemanager it pops up an error dialog saying
> >> the file does not exist even though it is in the same directory.
> >>
> >> The program simply uses the files name.  Is there a way without
> >> editing the source and inserting the full path to run the program
> >> from a launcher or the filemanager and allow it to see files in the
> >> current directory?
> >
> > What file manager are you using? Nautilus? Konqueror? Something else?
>
> Nautilus. I have it configured to run files with the extension .py when
> they are double clicked.
>
>
> > What do you mean, "use a launcher"? Use a launcher to do what? What sort
> > of launcher?
>
> It runs programs and sits on the panel at the top of my Ubuntu desktop.
>  The command it uses is usr/bin/python2.6.  These are wxPython examples I am
> working with.
>
>
> > What pops up an error dialog? The launcher?
>
> I am assuming Python. The title bar of the dialog says Python2 Error, the
> message is   Can't load image from file 'wxPython.jpg': file does not exist.
>
>
> > Which file does it claim doesn't exist? Python? The Python script? The
> > image file? What is the exact error message it gives?
>
> See above.  The line that triggers the error is:  image =
> wx.Image('wxPython.jpg', wx.BITMAP_TYPE_JPEG)
>
>
> > There's probably a way to tell the launcher which working directory to
> > use, but of course that depends on the answers to the above questions.
> >
>
> If I use the terminal to start the program it has no problem using the
> file.  There are multiple files in multiple directories so I was looking for
> a way to just double click them and have them run.  If it turns out that I
> must make changes to or for each of the files it will be easier to just keep
> using the terminal.  I've only been using Ubuntu for a few months so I was
> surprised that the program could not see a file that is in the same
> directory.
>
> Regards,  Jim


The problem is ubuntu doesn't run the script from the directory it's in so
it's looking for wxPython.jpg somewhere else.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Documentation Clarification

2010-07-12 Thread Adam Bark
On 12 July 2010 15:49, Huy Ton That  wrote:

> This is going to sound silly, but I realized there are some areas within
> the documentation that do not make absolute sense to me.
>
> e.g.
>
> compile(source, filename, mode[, flags[, dont_inherit]])
>
> I see within this built in function, the first argument can be what they
> define as source, the second argument as the filename and the third as the
> mode.
>
> But what confuses me is sometimes I see a bracket, above as [, flags[,
> dont_inherit]]. Is this an optional argument like flags=dont_inherit?
>
> Just not grokking it correctly and I can't seem to track down where the
> documentation formatting is defined within the python.org documentation...
>
>
You're about right really, it's a keyword argument which means it will have
a default so you can specify it or leave the default by ignoring it.

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


Re: [Tutor] Path?

2010-07-11 Thread Adam Bark

On 11/07/10 18:42, Jim Byrnes wrote:
I am running Ubuntu.  I downloaded the source code examples for a book 
I purchased.  Some of the examples load image files located in the 
same directory as the program.  If I go to the current directory in 
the terminal the program can use the image files.  However, if I use a 
launcher or the filemanager it pops up an error dialog saying the file 
does not exist even though it is in the same directory.


The program simply uses the files name.  Is there a way without 
editing the source and inserting the full path to run the program from 
a launcher or the filemanager and allow it to see files in the current 
directory?


Thanks,  Jim

Maybe create a bash script to call the python code something like:

#!/bin/bash

cd /directory/the/scripts/are/in
python script_name

HTH,
Adam.

PS if you want to use the same script for any python script you could 
change the last line to:


python $1

and call the bash script with the python script as the first argument
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Function returns 'None'

2010-07-11 Thread Adam Bark

On 11/07/10 14:59, Dominik Danter wrote:

Hello

As en exercise I wrote the following function:


def recursfac(x,carryover=1):
print 'x:',x,'carryover:', carryover
if x > 1:
carryover *= x
recursfac(x-1, carryover)
else:
return carryover

print recursfac(3)

Very much to my surprise I get the following output:

x: 3 carryover: 1
x: 2 carryover: 3
x: 1 carryover: 6
None

Where did I go wrong?

Kind regards
Dominik Danter


I made a diagram to try to explain

recursfac(3)
recursfac(2, 3) <|
recursfac(1, 6)  _|

As you can see recursfac(1,6) returns it's value (carryover) to 
recursfac(2, 3) which ignores it and completes it's execution ie 
returning None to your original call which then prints out that return 
value.

I hope that's clear.

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


Re: [Tutor] newbie to gui programming

2010-07-06 Thread Adam Bark
On 6 July 2010 18:09, Payal  wrote:

> Hi all,
> Some background before the actual query.
> A friend of mine, an electronics engineer has a
> small co. He had a computer engg. with him who used to design GUI
> front-ends
> for his products in Visual Basic. These apps used to take data from
> serial port, store it on disk put and show it in excel also plot graphs.
> Now the engg has left. So my friend has asked me to help him out till
> he finds a replacement. I don't know a word of electronics and know Python
> to
> extend of understanding almost 90% of "Learning Python" and 70-75% of
> "Core Python programming" books.
> Now my real query, do you think it is possible for me to try my hand at
> gui programming?


Of course you can, it depends on how complex the GUI has to be on how far
you'll get most likely.


> There seems to be many ways to do gui programming in
> Python namely wxpython, tkinter, gtk, qt etc. Which is the easiest and
> nice looking one and works on both windows and Linux?


Any of those toolkits are available on windows and linux, as to the nicest
looking, that's up to you and your friend to decide. wxPython does a good
job of blending in with other applications on the same system though.
Tkinter comes with python which may swing it for you.


> The interfaces
> will be used by other electronics enggs. so they do not expect real
> swell gui, but it should be bearable and more importantly easy for me to
> learn, cos' I have a day time job and I am doing this just as a help and
> eagerness to learn.
> Looking  for advice.
>
>
Once you've picked your toolkit you'll probably want to get on the relevant
mailing list to get some help.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "x and y" means "if x is false, then x, else y"??

2010-07-05 Thread Adam Bark
On 5 July 2010 13:21, Adam Bark  wrote:

> On 5 July 2010 12:53, Richard D. Moores  wrote:
>
>> On Mon, Jul 5, 2010 at 04:09, Stefan Behnel  wrote:
>> > Richard D. Moores, 05.07.2010 11:37:
>> >>
>> >> I keep getting hung up over the meaning of "the return
>> >> value" of an expression. I am of course familiar with values returned
>> >> by a function, but don't quite grasp what the return value of, say,
>> >> the y of "x and y" might mean.
>> >
>> > Think of a different expression, like "1+1". Here, the return value (or
>> > maybe a better wording would be the result value) is 2.
>> >
>> >
>> >> Also, you distinguish between a return value of True and and the value
>> >> of y being such (say 5, and not 0) that it makes y true (but not
>> >> True). So another  thing I need to know is the difference between True
>> >> and true.  Also between False and false. And why the difference is
>> >> important.
>> >
>> > "True" is the value "True" in Python, which is a singleton. You can test
>> for
>> > it by using
>> >
>> >x is True
>>
>> Ah. But could you give me an x that would satisfy that? I can think of
>>
>> >>> (5 > 4) is True
>> True
>>
>> But how can (5 > 4) be an x? Could you show me some code where it could
>> be?
>>
>> >>> x = (5 > 4)
>> >>> x
>> True
>> >>> x is True
>> True
>>
>> So it can! That surprised me.  I was expecting   "x = (5 > 4)"  to be
>> absurd -- raise an exception? Still seems pretty weird.
>>
>
> Greater than (>) works like the mathematical operators in returning a
> value, it just happens that for comparison operators (>, <, ==, !=) the
> values can only be True or False.
>
> HTH,
> Adam.
>

I should add that this is how something like:

if x != y:
do_something()

works, if expects a True or False (this isn't always true but works for
comparison operators expressions such as this).
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] "x and y" means "if x is false, then x, else y"??

2010-07-05 Thread Adam Bark
On 5 July 2010 12:53, Richard D. Moores  wrote:

> On Mon, Jul 5, 2010 at 04:09, Stefan Behnel  wrote:
> > Richard D. Moores, 05.07.2010 11:37:
> >>
> >> I keep getting hung up over the meaning of "the return
> >> value" of an expression. I am of course familiar with values returned
> >> by a function, but don't quite grasp what the return value of, say,
> >> the y of "x and y" might mean.
> >
> > Think of a different expression, like "1+1". Here, the return value (or
> > maybe a better wording would be the result value) is 2.
> >
> >
> >> Also, you distinguish between a return value of True and and the value
> >> of y being such (say 5, and not 0) that it makes y true (but not
> >> True). So another  thing I need to know is the difference between True
> >> and true.  Also between False and false. And why the difference is
> >> important.
> >
> > "True" is the value "True" in Python, which is a singleton. You can test
> for
> > it by using
> >
> >x is True
>
> Ah. But could you give me an x that would satisfy that? I can think of
>
> >>> (5 > 4) is True
> True
>
> But how can (5 > 4) be an x? Could you show me some code where it could be?
>
> >>> x = (5 > 4)
> >>> x
> True
> >>> x is True
> True
>
> So it can! That surprised me.  I was expecting   "x = (5 > 4)"  to be
> absurd -- raise an exception? Still seems pretty weird.
>

Greater than (>) works like the mathematical operators in returning a value,
it just happens that for comparison operators (>, <, ==, !=) the values can
only be True or False.

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


Re: [Tutor] What is super for?

2010-06-28 Thread Adam Bark
On 28 June 2010 17:15, Adam Bark  wrote:

> I can't figure out how super(C, self).__init__() is any better than
> C.__init__(self), is there a preference? Does super do something special?
>
> Thanks.
>

Whoops I should really think about these things for a minute first, you
don't have to know the superclass in advance is presumably the idea?
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] What is super for?

2010-06-28 Thread Adam Bark
I can't figure out how super(C, self).__init__() is any better than
C.__init__(self), is there a preference? Does super do something special?

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


Re: [Tutor] capturing error msg in exception

2010-06-28 Thread Adam Bark
On 28 June 2010 00:27, Steven D'Aprano  wrote:

> On Mon, 28 Jun 2010 03:12:39 am Adam Bark wrote:
>
> > I think the 'as' syntax is only available in Python 3.x
>
> You think wrong. It is available from Python 2.6 onwards.
>

I know, I corrected myself after Steve Willoughby pointed it out.


>
>
> > Question marks go at the end of the sentence where you would normally
> > put a full stop if it wasn't a question.
>
> That's a terribly unhelpful answer given the context of Payal's
> question. I'm sure he knows the grammatical rules for questions in
> ordinary English sentences, but he's asking specifically about a
> particular form of sentence where you have a question consisting of two
> or more alternatives or examples separated as paragraphs:
>
> Well it was a terribly unclear question, I just answered what I thought he
was asking.


> [example]
> Hello, which is better, a lambda:
>
> (1) lambda x: x+1
>
> or a function definition:
>
> (2) def f(x):
>return x+1?
> [end example]
>
> It is very reasonable to ask where to put the question mark in examples
> like this. Unfortunately there is no good answer. If you put it on the
> same line as the second example, as shown, certainly isn't correct
> because it makes the question mark part of the example. It's
> *especially* dangerous in a programming context, because it leads to a
> syntax error.
>
> Putting it on a line on it's own after the example looks silly.
> Re-writing the question to avoid the problem is often awkward, but can
> be done:
>
> [rewritten example]
> Hello, which of these two are better?
>
> (1) lambda x: x+1
>
> (2) def f(x):
>return x+1
> [end rewritten example]
>
> Since there is no One Right Answer, you can do whichever seems best in
> context.
>
I'm sure this "work it out yourself" answer is much more helpful.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] capturing error msg in exception

2010-06-27 Thread Adam Bark
On 27 June 2010 18:22, Steve Willoughby  wrote:

> On 27-Jun-10 10:12, Adam Bark wrote:
>
>> On 27 June 2010 17:47, Payal >
>
> c. What is the correct Python of writing,
>>except  as e: print 'Msg : ' , e# Capturing all exceptions
>>
>
> Since exceptions are (should be?) subclasses of Exception, you can do:
>
> except Exception as e:
>
>
>  I think the 'as' syntax is only available in Python 3.x
>>
>
> It's in Python 2 as well.  At least I see it in 2.6.4, probably earlier too
> (but I'm not sure ATM how early it showed up).
>
>
Ah yeah sorry I got confused, it's the comma version that is gone from 3.x
isn't it? I assume that means 'as' is the preferred syntax.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] capturing error msg in exception

2010-06-27 Thread Adam Bark
On 27 June 2010 17:47, Payal  wrote:

> Hi,
> Again a few queries regarding exceptions,
>
> a. What is the difference between,
>
> except ZeroDivisionError as e: print 'Msg : ' , e
> except ZeroDivisionError ,e: print 'Msg : ' , e
>
> Both show,
> Msg :  integer division or modulo by zero
>
> b. What is portable and correct way of writing,
>
> except (NameError, ZeroDivisionError) as e: print 'Msg : ' , e
>
> c. What is the correct Python of writing,
> except  as e: print 'Msg : ' , e# Capturing all exceptions
>
> Thanks a lot for the help in advance.
> With warm regards,
> -Payal
> --
>
> p.s. I am always confused where does one put the "?" when I am framing the
> questions like I have done above (a, b and c)?
> This is completely OT query for native english speaking people :-)
>
>
I think the 'as' syntax is only available in Python 3.x


Question marks go at the end of the sentence where you would normally put a
full stop if it wasn't a question.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Repeat function until...

2010-06-23 Thread Adam Bark
On 23 June 2010 13:29, Nethirlon .  wrote:

> Hello everyone,
>
> I'm new at programming with python and have a question about how I can
> solve my problem the correct way. Please forgive my grammar, English
> is not my primary language.
>
> I'm looking for a way to repeat my function every 30 seconds.
>
> As an example I have written a ping function. But I would like this
> function to repeat itself every 30 seconds, without stopping until I
> give it a STOP command (if such a thing exists.)
>
> Code:
> import os, sys
>
> def check(host):
>try:
>output = os.popen('ping -ns 1 %s' % host).read()
>alive = output.find('Reply from')
>print alive
>if alive is -1:
>print '%s \t\t DOWN ' % host
>else:
>print '%s \t\t OK' % host
>except OSError, e:
>print e
>sys.exit()
>
> check('www.google.com')
>
> Let me know if anything is unclear or if there are other
> recommendations about doing some parts different.
>
> Kind regards,
> Nethirlon
>

You should probably take a look at the time module
http://docs.python.org/library/time.html for waiting (maybe time.sleep)

If you want to call a function an unspecified number of times you probably
want a while loop:

while True:
pass

loops infinitely unless you quit the program though, to leave the loop you
will need to use "break", you will probably want an if statement and change
the value of some variable when you want to stop calling the function and
break out of the loop.

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


Re: [Tutor] New to this

2010-06-20 Thread Adam Bark
On 20 June 2010 19:38, Neil Thorman  wrote:

> I'm picking this up as a hobby really, not having done any programming
> since Acorn I'm pretty much starting form scratch (and even back in the
> BASIC day I never really got to grips with files).
> This is from Alan Gauld's Learning to Program: Handling Files.
> http://www.freenetpages.co.uk/hp/alan.gauld/
>
> Can I just check I'm getting
> it?
>
>
> *Menu.txt contains*
>
> *Spam & Eggs*
> *Spam & Chips*
> *Spam & Spam*
>
> >>>inp = file("menu.txt", "r")
> *What is inp? What does it now contain?*
> *The following creates a list;*
>

inp is a file object.


> *
> *
> *
> >>>print inp.readlines()
> ['spam & eggs\n', 'spam & chips\n', 'spam & spam']
>
> *
>

readlines is a method of inp. It's basically a function that works
specifically on that object, in this case it reads each line from the file
and puts it into a list and then returns it; the shell then prints it out.


> *
> but if I do it again I get:
> >>> print inp.readlines()
> []
>
> *
>

At this point you have reached the end of the file so there are no more
lines to read, if you just want one line at a time then you should use
inp.read()


> *
> I'm baffled, why is inp now empty?
> *
>

inp isn't really empty it's still a file object there is just no data left
to read.


> *
>
> Many thanks
>
> Neil
>
> ps. I'm working in the IDLE Python Shell.
> *
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting audio samples from 16-bit signed int to float?

2010-06-20 Thread Adam Bark
On 20 June 2010 23:52, Joe Veldhuis  wrote:

> Hello all. I'm writing a program that needs to capture audio from a
> soundcard and run FFTs to determine peak frequency for further processing.
> The soundcard's native capture format is 16-bit little-endian signed integer
> samples (values 0-65535), and of course the FFT function requires
> floating-point values (-1.0 - +1.0).
>
> So, what is the most efficient way to do the necessary conversion? I'm
> using the pyalsaaudio module to access the soundcard, if it matters.
>
> -Joe Veldhuis
>

Not sure it's the best way but the most obvious to me would be divide by
32767.5 (ie half 65535) and minus 1 puts you into the right range:

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


[Tutor] Strange range and round behaviour

2010-06-07 Thread Adam Bark
Just out of curiosity does anyone know why you get a deprecation warning if
you pass a float to range but if you use round, which returns a float, there
is no warning?

Python 2.6.4 (r264:75708, Oct 26 2009, 08:23:19) [MSC v.1500 32 bit (Intel)]
on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> range(2.0)
__main__:1: DeprecationWarning: integer argument expected, got float
[0, 1]
>>> range(round(2.0))
[0, 1]
>>> round(2.0)
2.0
>>> round(2.0, 0)
2.0
>>> round.__doc__
'round(number[, ndigits]) -> floating point number\n\nRound a number to a
given
precision in decimal digits (default 0 digits).\nThis always returns a
floating
point number.  Precision may be negative.'
>>>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unable to run a simple Hello.py in WinXP

2010-05-17 Thread Adam Bark
On 18 May 2010 01:30, Sivapathasuntha Aruliah <
sivapathasuntha.arul...@amkor.com> wrote:

>
>
>
>
>
>  *Adam Bark *
>
>
> *05/18/2010 01:21 AM*
>   To
> Sivapathasuntha Aruliah/S1/a...@amkor
> cc
> tutor@python.org
> Subject
> Re: [Tutor] Unable to run a simple Hello.py in WinXP
>
>
>
>
>
>
>
>
> On 17 May 2010 09:05, Sivapathasuntha Aruliah <*
> sivapathasuntha.arul...@amkor.com* >
> wrote:
>
> Hi
> If possible please run the following two lines after *saving it as a py
> file on WINXP* and check whether it runs smooythly. *When I run I  get
> error. *I use Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500
> 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license()" for more information. However
> when I give the following command on Python shell print("Hello", "World!")
> it neately prints *Hello World!*
>
> #! /usr/bin/env python3
>
> print("Hello", "World!")
>
>
>
> Regards,
> Siva
>
> Hi, are you sure you got your python path correct? Are you running 64bit
> windows by any chance?
> Hi Adam
> I also suspected it could be 64 bit but from IDLE gui which I used it shows
> the followings which confirms 32 bit?  So please if you have WINXP bit32
> please try to run and show me what command including paths you used to get a
> successful run.
>
> "Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "copyright", "credits" or "license()" for more information.
> >>> "
>

Sorry I haven't got winXP. The 32 bit on the command line just tells you
what python was built for. You need to check your system (in Control Panel)
to find out what build of windows you are running.
<>___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Unable to run a simple Hello.py in WinXP

2010-05-17 Thread Adam Bark
On 17 May 2010 09:05, Sivapathasuntha Aruliah <
sivapathasuntha.arul...@amkor.com> wrote:

>
> Hi
> If possible please run the following two lines after *saving it as a py
> file on WINXP* and check whether it runs smooythly. *When I run I  get
> error. *I use Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500
> 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license()" for more information. However
> when I give the following command on Python shell print("Hello", "World!")
> it neately prints *Hello World!*
>
> #! /usr/bin/env python3
>
> print("Hello", "World!")
>
>
>
> Regards,
> Siva
>

Hi, are you sure you got your python path correct? Are you running 64bit
windows by any chance?
<>___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reading binary file on windows and linux

2010-05-09 Thread Adam Bark
On 9 May 2010 18:33, Jan Jansen  wrote:

> Hello,
>
> I've got some trouble reading binary files with struct.unpack on windows.
> According to the documentation of the binary file's content, at the
> beginning there're some simple bytes (labeled as 'UChar: 8-bit unsigned
> byte'). Within those bytes there's a sequence to check the file's sanity.
> The sequence is (in ascii C-Notation):
> " "
> "\n"
> "\r"
> "\n"
> " "
> I've downloaded the file from the same website from two machines. One is a
> Windows 7 64-Bit, the other one is a virtual Linux machine. Now the trouble
> is while on linux everything is fine, on windows the carriage return does
> not appear when reading the file with struct.unpack.
>
> The file sizes on Linux and Windows are exaktly the same, and also my
> script determines the file sizes correctly on both plattforms (according to
> the OS). When I open the file on Windows in an editor and display the
> whitespaces, the linefeed and cariage-return are shown a expected.
>
> The code I'm using to check the first 80 bytes of the file is:
>
> import struct
> import sys
>
> with open(sys.argv[1]) as source:
> size = struct.calcsize("80B")
> raw_data = struct.unpack("80B", source.read(size))
> for i, data in enumerate(raw_data):
> print i, data, chr(data)
> source.seek(0, 2)
> print source.tell()
>
>
> Any suggestions are highly appreciated.
>
> Cheers,
>
> Jan
>

I'd guess that it's because newline in windows is /r/n and in linux it's
just /n. If you read the file as binary rather than text then it should work
the same on both platforms ie use:
open(sys.argv[1], "rb")

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


Re: [Tutor] Is wxPython (development) dead?

2010-01-28 Thread Adam Bark
On 27 January 2010 13:57, Neven Goršić  wrote:

> Since May of 2009 there has not been any update and now web page is not
> available any more ...
>
The website is back up now. I guess there was a server issue of some sort.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] smtp project

2010-01-18 Thread Adam Bark
2010/1/17 Kirk Z Bailey 

> I am writing a script that will send an email message. This will run in a
> windows XP box. The box does not have a smtp server, so the script must
> crete not merely a smtp client to talk to a MTA, it must BE one for the
> duration of sending the message- then shut off, we don't need no bloody
> op0en relays here!
>
> I am RTFM and having some heavy sledding, can I get an Elmer on this?


This isn't quite what you're after but I wrote some code a while ago to find
the changes to a wiki in the day from an update RSS feed and then send an
email with these changes to a mailing list via a googlemail account. Anyway
there should be some useul code in it
http://cubesat.wikidot.com/wiki-change-emailer
HTH
Adam.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] for loop issue

2009-10-09 Thread Adam Bark
2009/10/9 Stefan Lesicnik 

Hi,
>
> This feels like a strange issue, so i hope I formulate this so its
> understandable.
>
> I have some objects. Each object has associated values. I am looping
> through these objects, working with a value and printing out the
> value.
> The issue in this case is that i need to check if the one value
> superseeds the other, and in that case, not print it out. I think the
> problem is that when you are in the loop, you dont know about the
> other object that you havent processed yet, and when you are
> processing that object, you dont know about the previous one?  (not
> 100% sure if this assumption is correct)
>
> eg of my data  (im comparing ubuntu -> debian security fixes and the
> data comes from https://edge.launchpad.net/ubuntu/+source/openswan)
> You can see what i have so far here -
> http://people.ubuntu.com/~stefanlsd/synclist.html
>
> The Jaunty Jackalope  (current stable release)
> Show details 1:2.4.12+dfsg-1.3+lenny2build0.9.04.1  updates, security
> (universe)  two days ago
> Show details 1:2.4.12+dfsg-1.3  release (universe)  49 weeks ago
>
> In the above case, the first loop goes through
> 1:2.4.12+dfsg-1.3+lenny2build0.9.04.1. At this point i need it to stop
> without checking the next entry 1:2.4.12+dfsg-1.3 as the former
> superseeds it.
> I understand that I can use a break to exit the loop, but i run a
> whole bunch of things after this check, so i dont want to break out of
> it.
>
> Is this possible what i'm doing? or have i architected the loop wrong
> so i 'should' be able to break out of it.
>
> Thanks in advance!
>
> stefan
>
>
> snippet of code below if its of any use...
>
>
> for app in apps:
>print('app in apps: %s' % app)
>for item in series:
>print('item in series: %s' % item)
>debian_series = item[0]
>debian_fullversion = item[2]
>print('debian_series: %s' % debian_series)
>print('debian_fullversion: %s' % debian_fullversion)
>
>debian_version =
> re.sub('\+?(etch|lenny|sarge|squeeze|woody)[0-9]+$', '',
> debian_fullversion)
>print('debian_version: %s' % debian_version)
>
>main_archive =
> launchpad.distributions['ubuntu'].main_archive
>#TODO - May be able to use a version check in the
> publishedsource to increase speed of checking
>publishedsource =
> main_archive.getPublishedSources(source_name = app,
> status='Published', exact_match=True)
>
>for source in publishedsource:
>
>if source.distro_series.active:
>print source.distro_series.name,
> source.source_package_version
>ubuntu_fullversion = source.source_package_version
>print('ubuntu fullversion before: %s' %
> ubuntu_fullversion)
>ubuntu_version =
> re.sub('build0.[0-9]+.[0-9][0-9].[0-9]+$', '', ubuntu_fullversion)
>#ubuntu_version =
> re.sub('\+?(etch|lenny|sarge|squeeze|woody)[0-9]+$', '',
> ubuntu_version)
>print('ubuntu version after: %s' % ubuntu_version)
>#ubuntu_target = ('%subuntu/+source/%s') %
> (launchpad._root_uri,app)
>
>if debian_fullversion == ubuntu_version:
>continue
>
>if debian_version in ubuntu_fullversion:
>ubuntu_component = source.component_name
>ubuntu_series = source.distro_series.name
>ubuntu_pocket = source.pocket
>print('ubuntu_pocket: %s' % ubuntu_pocket)
>print('debian version: %s' % debian_version)
>
>#If pocket is Security, no need to check further
>if ubuntu_pocket == 'Security' or
> ubuntu_pocket == 'Updates':
>print('Not Found version in: %s.
> Continue' % ubuntu_pocket)
>break
>
>if debian_version == ubuntu_version:
>matchtype = 'Sync Match'
>else:
>matchtype = 'MoM Match'
>
>ubuntu_changelog = ' href=http://changelogs.ubuntu.com/changelogs/pool/' + ubuntu_component
> + '/' + app[:1] + '/' + app + '/' + app + '_' + ubuntu_version +
> '/changelog>Ubuntu Changelog'
>debian_changelog = ' href=http://packages.debian.org/changelogs/pool/' + 'main' + '/' +
> app[:1] + '/' + app + '/' + app + '_' + debian_fullversion +
> '/changelog>Debian Changelog'
>
>print('cve: %s' % cve)
>for cveitem in cve:
>cvestatus, url = cvechec

Re: [Tutor] Memory usage (Lizhi Yang)

2009-10-08 Thread Adam Bark
2009/10/8 Lizhi Yang 

> Hi Adam,
>
> One more question, if I want to implement algorithms and load the huge
> amount of data using C++, but using Python as the glue language to
> implement other functionality such as Gui and txt processing, you
> think Boost.python is better or SWIG is better? Have not tried yet,
> just need to make decision first, thanks.
>
> On Thu, Oct 8, 2009 at 9:19 AM, Lizhi Yang  wrote:
> > Hi Adam,
> >
> > Thank you so much for your help. I will do a test, and will let you
> > know the result.
> >
> > On Thu, Oct 8, 2009 at 9:15 AM, Adam Bark  wrote:
> >> 2009/10/8 Lizhi Yang 
> >>>
> >>> Below you see my original post.
> >>>
> >>> 1: Say I use boost.python.
> >>> 2: For example, I allocate a big array with integers using C++
> >>> function (4 bytes for each int in C++, but 12 bytes in python), and I
> >>> use boost.python to call those C++ functions. How is the memory
> >>> allocation for that array then?
> >>
> >> If the data is setup in C++ using native types then it will use 4 bytes
> per
> >> int. I believe boost just creates a wrapper so you can call the C++
> function
> >> as if it were a python function it then does all the conversion
> internally
> >> and will return some python type data.
> >> HTH
> >
>

Hi Lizhi, I don't really have much experience with either, personally, and I
just realised I didn't reply-all my original response so I'm CC'ing this
back to the list, hopefully you'll get a useful response there.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] power of 2.718282

2009-01-13 Thread Adam Bark
According to a quick interactive session and the timeit module it's quicker
to do 2.71828**10 than using math.exp, I'm guessing cos of the function
call.
>>> t=timeit.Timer("2.718282**10")
>>> t.repeat()
[0.073765993118286133, 0.066617012023925781, 0.06807398796081543]

>>> t=timeit.Timer("math.exp(10)", "import math")
>>> t.repeat()
[0.42525100708007812, 0.43169903755187988, 0.4239799976348877]

>>> t=timeit.Timer("exp(10)", "from math import exp")
>>> t.repeat()
[0.36061406135559082, 0.36182284355163574, 0.35887718200683594]

2009/1/13 culpritNr1 

>
> Thanks Marc and Kent and all. math.exp() is what I was looking for.
>
> culpritNr1
>
>
> --
> View this message in context:
> http://www.nabble.com/power-of-2.718282-tp21441385p21441787.html
> Sent from the Python - tutor mailing list archive at Nabble.com.
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A question about how python handles numbers larger than it's 32 bit limit

2008-09-23 Thread Adam Bark
2008/9/23 John Toliver <[EMAIL PROTECTED]>

> Greetings,
>
> The book I have says when you anticipate that you will be working with
> numbers larger than what python can handle, you place an "L" after the
> number to signal python to treat it as a large number.  Does this
> "treating" of the number only mean that Python won't try to represent
> the number internally as a 32bit integer?  Python still appears to be
> representing the number only with an L behind it so what is happening to
> the number then.  Is the L behind the number telling python to handle
> this large number in HEX instead which would fit into the 32 bit limit?
>
> thanks in advance,
>
> John T


The L stands for long integer and means that it will usually use twice the
space of a regular integer so in this case 64bits.
HTH
Adam.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Interactive physics simulation over web

2008-04-04 Thread Adam Bark
On 04/04/2008, Brain Stormer <[EMAIL PROTECTED]> wrote:
>
> I am working on a physics simulation and would like to publish it on the
> web.  The simulation requires input fields, mouse action (picking points in
> a display pane) and movie like feature with play, pause, skip forward and
> skip backward.  I was wondering if this can be done using Python and a
> Python web tool kit like Django.  I can see that this can be done using
> Java/Java Script but don't feel like re-familiarizing myself to Java.  I
> looked into the Python web programming 
> pagebut it didn't answer my 
> questions.  My goal is keep this simulation
> completely written in Python.


I think you can use Jython in a Java applet, that might be what you're
looking for.
HTH,
Adam.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Required method to make foo(*Vector(0,0,0)) work.

2007-12-18 Thread Adam Bark
On 19/12/2007, John Fouhy <[EMAIL PROTECTED]> wrote:
>
> On 19/12/2007, Adam Bark <[EMAIL PROTECTED]> wrote:
> > I want to be able to get the values for my vector class but I don't know
> > what method you need to get the * thing to work ie how to make it a
> sequence
> > i think. Anybody know how to do this?
> > Thanks in advance.
>
> If you're confused about python's *args / **kwargs syntax, this post I
> wrote a while ago might help:
> http://mail.python.org/pipermail/tutor/2007-April/053725.html
>
> Otherwise, as Kent says, we need more information.
>
> --
> John.
>

Sorry I wasn't quite sure how to explain it it's a vector class i've written
myself.
I've worked it out now, I was using a vector as part of a quaternion and
wanted to
be able to pass a vector or individual numbers so it seemed the easiest way
to be
able to use the *sequence syntax. Apparently you have to have to have a
__getitem__ method for it to work.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Required method to make foo(*Vector(0,0,0)) work.

2007-12-18 Thread Adam Bark
I want to be able to get the values for my vector class but I don't know
what method you need to get the * thing to work ie how to make it a sequence
i think. Anybody know how to do this?
Thanks in advance.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Top Programming Languages of 2013

2007-10-07 Thread Adam Bark
On 07/10/2007, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
>
> Alan Gauld wrote:
> > "Dick Moores" <[EMAIL PROTECTED]> wrote
> >
> >> 
> >>
> >
> > Interesting, but I'm not sure what the criteria for "top" is.
> > Is it a measure of power, popularity, usage?
> >
> > Scary that HTML/CSS should be so high though
> > given its not a programming language at all!
> >
> > Alan G.
> >
>
> Besides all that, we are programmers not fashion models. Who cares which
> is the "top" language, leave that for the "top models" and such. Our
> trade is code, not fashion.


It appears from the original survey page that it is the most popular by
employer
demand so it probably does matter if you want a job in that sort of area
http://www.redcanary.ca/view/top-10-programming
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] evaluating AND

2007-09-13 Thread Adam Bark
On 13/09/2007, Terry Carroll <[EMAIL PROTECTED]> wrote:
>
> On Thu, 13 Sep 2007, Orest Kozyar wrote:
>
> > Given a variable x that can either be None or a tuple of two floats [i.e
> .
> > (0.32, 4.2)], which syntax is considered most appropriate under Python
> > coding standards?
> >
> > if x and x[0] > 0:
> >   pass
> >
> > =OR=
> >
> > if x:
> >   if x[0] > 0:
> >   pass
>
> I would like either one if instead of "if x" you used "if x is not None";
> that seems a lot easier to me to read.  It's a bit jarring to see the same
> variable used in one expression as both a boolean and a list/tuple.
>
> Besides, suppose somehow x got set to zero.  It would pass without error,
> something you wouldn't want to have happen.  Even if you've set things up
> so that it couldn't happen, it's not obvious from looking at this code
> that it couldn't happen.
>
> If you really want to test for x being non-None, test for x being
> non-None.


The problem is what if it's an empty list or tuple? It would pass but have
not value
whereas if x would work fine.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Losing theexpressiveness ofC'sfor-statement?/RESENDwith example

2007-08-10 Thread Adam Bark
On 10/08/07, Alan Gauld <[EMAIL PROTECTED]> wrote:

> > full-fledged lambdas...
>
> I'm with you there but I've been waiting long enough to have
> given up. In fact I think we are more likely to lose lambdas
> altogether than see an improved version!


Guido said he's keeping lambdas in Python 3000, I think pretty much as is
http://www.artima.com/weblogs/viewpost.jsp?thread=208549
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Roman to digital (pseudocode)

2007-03-08 Thread Adam Bark

On 08/03/07, Alan Gilfoy <[EMAIL PROTECTED]> wrote:


This, I heard, is more difficult than digital-to-Roman, since you have
to "read" the subtractive cases, with a smaller numeral placed before
a larger numeral, without simply adding all the numerals' values up

I'm going to use a raw_input prompt to ask the user which Roman
numeral he/she wants to convert. How do I "screen" for inputs that
have characters besides "I", "V", "X", "L", "C", "D", or "M"?

Second Python question:

I know there's a way to "find out" the name of the first item in a list
(ListName[0]), but is there a way to find out the first character of a
string?

Also, is there a way to "ask" Python what characters are before and
after the character in the string that you're asking about?

For example, usign the sample string "MCMXVII" (1917):

How would you ask Python:
"What's the 3rd character in this string?" (returns "M")
"What's before that character?" (returns "C")

Pseudocode time:

If character Y is "M":
and the character before character Y is "C",
add 900 to digital_result
and remove that "C" and that "M" from the string.
#How would you do *that*?

and the character before character Y is another "M", or if character Y
is the first character in the string,
add 1000 to digital_result
and remove that "M" from the string.



you can index a string just like a list:

roman_numeral = "MCMXVII"
roman_numeral[2]

'M'

roman_numeral[2-1]

'C'

HTH
Adam
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Send binary/hex data to a TCP socket

2007-01-24 Thread Adam Bark

On 25/01/07, Tod Haren <[EMAIL PROTECTED]> wrote:


I need to send a server at the other end of a socket a 36 byte
"frame", where each byte represents a specific field in the custom
data structure.(If there are any Ham operators reading this, I'm
talking about the AGW Packet Engine)

The documentation for the server says to initialize each field to a
binary zero(0x00).  How do I get a binary zero in Python?  The next
step is to send this all to the server and subsequently receive a
similarly formated frame.

A very basic frame looks something like this(modified from documentation):

|00 00 00 00 4D 00 00 00 00 00 00 00 00 00 00 00 |M...
|00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |
|00 00 00 00 |

My problem is that hex(0) return '0x0' and hex(ord('M')) returns
'0x4d'.  If I concatonate these all together then the socket receives
109 bytes instead of 36.  The documentation examples are in C++, so
they are little help to me.  The examples make use of the MoveMemory
function for building the frames, but I'm clueless what that does.

Pseudo code for the frame above:

  l = []
  for i in xrange(36):
l.append(hex(0))

  l[4]=hex(ord('M'))

  d=''
  d=d.join(l)  #I need some other data type to send besides a string!
  sock.send(d)  #send the 36 bytes to the socket

Any pointers or references would be greatly appreciated.



This should do what you need:
http://docs.python.org/lib/module-struct.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Psyco Puzzle

2007-01-12 Thread Adam Bark

On 11/01/07, Danny Yoo <[EMAIL PROTECTED]> wrote:




> Sometimes psyco speeds up a script by a factor of 10, and sometimes
> it makes no difference at all. Here's a case where I fully expected
> it to make a difference:
> . Whether using psyco
> or not, this takes about 13 seconds on my computer. Why no difference?

Psyco implements a Just-In-Time optimization approach, so I suspect that
it does its analysis of a function only after that function has been run
at least once --- otherwise, it has no run-time information on which it
can use to analyze.

In the code above, the code we want to optimize is fact().  However,
fact() is only called one time in the whole program.  To test this
hypothesis, it might be interesting to see if "priming" fact up will help.

#
if __name__ == '__main__':
 printFact(5)## just to prime the function up
 timeStart = time.time()
 printFact(2)
 timeEnd = time.time()
 print "Time was %.4g seconds" % (timeEnd - timeStart)
#



Furthermore, the magnitude of the numbers in the fact() code quickly get
into bignum range, where psyco's optimizations probably won't be so
effective.  In contrast, the primes code you have all deal with integers
in the range of 32 bits.



I tested this myself and it looks like bignum is probably the slowdown here
without psyco:
2! = 1.81e+77337
Time was 7.58 seconds
with psyco no priming:
2! = 1.81e+77337
Time was 7.55 seconds
with psyco and priming:
5! = 1.20e+002
2! = 1.81e+77337
Time was 7.591 seconds

there seems to be no difference with psyco or without even if you run the
function first.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python dictionaries

2007-01-05 Thread Adam Bark

On 05/01/07, Raven Of Night Raven Of Night <[EMAIL PROTECTED]> wrote:


Hi, there was this two step program I was working on but i can only
complete
the first step.

- - Write a Who's Your Daddy? program that lets the user enter the name of
the male and produces the name of his father. Allow the user to add,
replace, and delete father son pairs. The program should also allow the
user
to get a list of all son, fathers, or father son pairs.

I made a dictionary:
family = { "Wane Wilright" : "Dan Wilright",
   "Michal Zheng" : "Tsu Zheng",
   "Art Core" : "Vandalee Core",
   "John Wane" : "Calvin Wane" }

and was able to complete the rest of the program.


Then I was asked to improve the program:
- - Improve the Who's Your Daddy program by adding a choice that lets the
user enter a name and get back a grandfather. Your program should still
use
one dictionary of son-father pairs. Make sure to include several
generatios
in your dictionary so that a match can be found.

I don't understand, dictionarys only allow two elements so how can you
include several generations in the dictinoary... could you perhaps put a
dictinoary inside a dictionary? I don't understand how you would do the
second part.



Hopefully this will make sense to you as I don't want to give the whole game
away.
A grandfather is just a father's father. If you don't get it still then I'll
make it a bit
more obvious.
HTH,
Adam.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Game server login encryption

2006-12-25 Thread Adam Bark

Thanks a lot Bob that looks like a plan. Carlos I think the major problem
with the SSL sockets is the lack of certificate checking which, I suspect,
make it vulnerable to several exploits. Thanks anyway.
Adam.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Infinite Loops (and threads)

2006-12-24 Thread Adam Bark

On 24/12/06, Luke Paireepinart <[EMAIL PROTECTED]> wrote:


Kent Johnson wrote:
> Jonathan McManus wrote:
>
>> Hi all,
>>
>> Just a quick question, really. Is there any good way to have an
infinite
>> loop in a program, without said infinite loop eating up the CPU? I've
>> tried the trick of adding a pause (time.sleep(0.01)) somewhere in the
>> loop, and this appears to have worked on a basic infinite loop, but
this
>> doesn't appear to work for two separate infinite loops (in threads).
>>
>
> You would have to put a sleep in each thread.
>
> Why are you using infinite loops? Are you implementing some kind of
> polling loop? Often there are better alternatives, either an event
> notification or some kind of lock. If you post some details of why you
> want to do this we may be able to help you find a better way.
>
> Kent
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
Kent et. al.,

I'm writing something that has to do with sockets.
I need to recv any incoming packets from the socket.
I will have potentially hundreds of separate sockets open in a single
application.
I was just going to create a thread for each, so I could receive from
them separately.

Alternately, I figured I could read from each socket in sequence if I
could get the recv method to not block until it gets input,
so I tried this,

#code 
self.conn.setblocking(False)
info = self.conn.recv(8000)#this should read everything.
# code

where conn is connected to another computer already,
and I get the following error:

(Verbatim except for line 3, changed to hide username/password)
Traceback (most recent call last):
  File "C:\Python Scripts\AIM Connection Server\toc2.py", line 199, in ?
toc.login('---username---','---password---')
  File "C:\Python Scripts\AIM Connection Server\toc2.py", line 116, in
login
print self.getFlap()
  File "C:\Python Scripts\AIM Connection Server\toc2.py", line 93, in
getFlap
info = self.conn.recv(8000)#this should read everything.
error: (10035, 'The socket operation could not complete without blocking')

Do I misunderstand what blocking is?
It seems to me that blocking would mainly apply to inputs.
(My understanding is that 'blocking' means when you call 'recv' it will
return '' if it didn't receive anything.)

I'd appreciate any links that I could read up on, or any advice on how
to make socket inputs with event notification, as Kent mentioned earlier.

Basically, as Kent said, I have a polling loop, and I am not sure what
the alternative is to threads.

Thanks,
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



Well I've been doing some networking stuff in stackless myself recently and
I would probably do something like this:

import select
import stackless
import socket

def get_data(sock):
   sock.setblocking(0)
   poller = select.poll()
   poller.register(sock, select.POLLIN)
   while True:
   if poller.poll(0):
   sock.recv(1024)
   stackless.schedule()

stackless.tasklet(get_data)(socket.socket(socket.AF_INET, socket.SOCK_DGRAM
))
stackless.run()

stackless thread things are really low on resources so you can run tens of
thousands without too much trouble.
HTH,
Adam.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Game server login encryption

2006-12-24 Thread Adam Bark

I'm currently writing a networked game and I'm about to write a proper
implementation of the logon server. I would prefer to have some sort of
encryption but would like some opinions. The way I see it either I can take
a hash of some data eg. username, password, port and ip and check the hash
against one generated on the server. Alternatively I could use twisted conch
tunneling through ssh. I anybody has any opinions on either of these ideas
or anything else that might be useful, fire away.
Cheers,
Adam.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about exception handling

2006-12-17 Thread Adam Bark

On 17/12/06, Asrarahmed Kadri <[EMAIL PROTECTED]> wrote:



Hi Folks,

Is it possible to catch exception raised in module A to be caught in
module B.

If yes, then please let me know how to do it.



You can easily test this yourself. First right a quick module, something
like this will do:

def exception_test():
   raise Exception

then start an interpreter and do the following


import your_module
try:

... your_module.exception_test()
... except:
... print "Caught it!"
...

HTH,
Adam
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] cylinder texture map?

2006-10-12 Thread Adam Bark
On 12/10/06, Danny Yoo <[EMAIL PROTECTED]> wrote:
On Thu, 12 Oct 2006, Michael Shulman wrote:> I'd like to make a scrolling background for a game I'm working on.  I> was thinking, since it's all in orthographic view, that a horizontal> cylinder which rotates with a texture would simulate this very well.
I have to admit I'm clueless about programming games.  You might want toask a game developer forum for better advice.  There's also a few linkson: 
http://pyopengl.sourceforge.net/documentation/to several OpenGL tutorials, including: http://nehe.gamedev.net/
pygame.org and there mailing list might be helpful as well. The only thing I can think of for this is to use something like blender with an exact replica of the 3d object you plan to map to, unwrap it and make a uv mapping, ie you cut the 3d object up so it's flat draw the texture on then it fits perfectly when you apply it to the original object.
HTH
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Run a cmd program

2005-08-09 Thread Adam Bark
>>> import commands
>>> commands.getoutput("uptime AUTO-SRV-001 /s /d:04/01/2005")

that should do itOn 8/9/05, Øyvind <[EMAIL PROTECTED]> wrote:
Hello.I need to run a program(http://www.microsoft.com/ntserver/nts/downloads/management/uptime/default.asp)thru Python. It is normally run such as "uptime AUTO-SRV-001 /s
/d:04/01/2005" in the command prompt. Is it possible to run a alreadycompiled exe file in Python and thereafter get the result out? Whatmodule/command should I look for to run another program? Googling have
only given me results about how to run Python..Thanks in advance.--This email has been scanned for viruses & spam by Decna as - www.decna.noDenne e-posten er sjekket for virus & spam av Decna as - 
www.decna.no___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Deleting an entry from a dictionary

2005-08-03 Thread Adam Bark
Oh yeah using del is better. I was typing as Danny sent his reply so I didn't realise untill after I had sent that.On 8/3/05, Smith, Jeff <
[EMAIL PROTECTED]> wrote:






Although that works, I kinda prefer
    del meals['breakfast']
since 
that explicitly indicates what is going on.
 
Speaking of which, I note that there is a pop for lists but no 
shift.  Is there a Python idiom for this or is it just
val = mylist.shift() 
=>    (val, mylist) = 
(mylist[0], mylist[1:])
which 
seems a little clumsy.
 
Jeff
 
 
 

-Original Message-From: 
tutor-bounces+jsmith=[EMAIL PROTECTED] 
[mailto:[EMAIL PROTECTED]] On Behalf Of Adam 
BarkSent: Tuesday, August 02, 2005 5:17 PMTo: Greg 
LindstromCc: tutor@python.orgSubject: Re: [Tutor] Deleting 
an entry from a dictionary
meals.pop(key) will do 
  it.Example:>>> meals = {}>>> meals['breakfast'] 
  = 'slimfast'>>> meals['lunch'] = 'slimfast'>>> 
  meals['dinner'] = 'something sensible'>>> meals{'lunch': 
  'slimfast', 'breakfast': 'slimfast', 'dinner': 'something 
  sensible'}>>> 
  meals.pop("breakfast")'slimfast'>>> meals{'lunch': 
  'slimfast', 'dinner': 'something sensible'}
  On 8/2/05, Greg 
  Lindstrom <[EMAIL PROTECTED] 
  > wrote:
  Hello-This 
must be simple, but for the life of me I can't figure out how to delete 
an entry from a dictionary.  For example,meals = 
{}meals['breakfast'] = 'slimfast'meals['lunch'] = 
'slimfast'meals['dinner'] = 'something sensible'How do I 
eliminate 'lunch' from the dictionary so that I only have 'breakfast' 
and 
'dinner'?Thanks!--greg___Tutor 
maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Deleting an entry from a dictionary

2005-08-02 Thread Adam Bark
meals.pop(key) will do it.
Example:
>>> meals = {}
>>> meals['breakfast'] = 'slimfast'
>>> meals['lunch'] = 'slimfast'
>>> meals['dinner'] = 'something sensible'
>>> meals
{'lunch': 'slimfast', 'breakfast': 'slimfast', 'dinner': 'something sensible'}
>>> meals.pop("breakfast")
'slimfast'
>>> meals
{'lunch': 'slimfast', 'dinner': 'something sensible'}On 8/2/05, Greg Lindstrom <[EMAIL PROTECTED]
> wrote:Hello-This must be simple, but for the life of me I can't figure out how to
delete an entry from a dictionary.  For example,meals = {}meals['breakfast'] = 'slimfast'meals['lunch'] = 'slimfast'meals['dinner'] = 'something sensible'How do I eliminate 'lunch' from the dictionary so that I only have
'breakfast' and 'dinner'?Thanks!--greg___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I've run into a jam on the exercise on file I/O

2005-08-01 Thread Adam Bark
No sorry scratch that last one I was being stupid. The key is a string
but max_points is a list so the list index max_points[x] is effectively
looking for max_points[student].

def save_grades(students,filename):
    out_file = 
open(filename, "w")
    for x in 
students.keys():
    
out_file.write(x+","+max_points[x]+"\n")    
out_file.closeOn 8/1/05, Adam Bark <[EMAIL PROTECTED]> wrote:
>>> max_points = [25,25,50,25,100]
>>> assignments = ['hw ch 1','hw ch 2','quiz   ','hw ch 3','test']
>>> students = {'#Max':max_points}
>>> students
{'#Max': [25, 25, 50, 25, 100]}

The problem is the key in students is a list not an integer.On 8/1/05, Nathan Pinno <
[EMAIL PROTECTED]
> wrote:






Hey all,
I've seem to run into a jam while working on the exercise on file 
I/O.
Here's the error:
Filename to save: university.txtTraceback (most recent call 
last):  File "D:\Python22\grades.py", line 99, in 
?    save_grades(students,filename)  File 
"D:\Python22\grades.py", line 51, in save_grades    
out_file.write(x+","+max_points[x]+"\n")TypeError: sequence index must be 
integer
 
And the code:
max_points = [25,25,50,25,100]assignments = ['hw ch 1','hw ch 
2','quiz   ','hw ch 3','test']students = {'#Max':max_points}
 
def print_menu():    print "1. Add 
student"    print "2. Remove student"    
print "3. Print grades"    print "4. Record 
grade"    print "5. Load Grades"    print 
"6. Save Grades"    print "9. Exit"
 
def print_all_grades():    print 
'\t',    for i in 
range(len(assignments)):    print 
assignments[1],'\t',    print    keys = 
students.keys()    keys.sort()    for x in 
keys:    print 
x,'\t',    grades = 
students[x]    
print_grades(grades)
 
def print_grades(grades):    for i in 
range(len(grades)):    print 
grades[i],'\t\t',    print
 
def choice():    return int(raw_input("Menu Choice: 
"))
 
def school():    return raw_input("Student: ")
 
def load_grades(students,filename):    in_file = 
open(filename, "r")    while 
1:    in_line = 
in_file.readline()    if in_line == 
"":    
break    in_line = 
in_line[:-1]    [students,max_points] 
= string.split(in_line,",")    
max_points[students] = grade    in_file.close()
 
def save_grades(students,filename):    out_file = 
open(filename, "w")    for x in 
students.keys():    
out_file.write(x+","+max_points[x]+"\n")    
out_file.close
 
print "Grade Tracking Program."while 1:    
print_menu()    menu_choice = choice()    
if menu_choice == 1:    print "Add 
student"    name = 
school()    students[name] = 
[0]*len(max_points)    elif menu_choice == 
2:    print "Remove 
student"    name = 
school()    if 
students.has_key(name):    
del students[name]    
else:    
print "Student: ",name," not found."    elif menu_choice == 
3:    print_all_grades()
 
    elif menu_choice == 
4:    print "Record 
Grade"    name = 
school()    if 
students.has_key(name):    
grades = 
students[name]    
print "Type in the number of the grade to 
record"    
print "Type in a 0 (zero) to 
exit"    for 
i in 
range(len(assignments)):    
print i+1,' 
',assignments[i],'\t',    
print    
print_grades(grades)    
which = 
1234    while 
which != 
-1:    
which = int(raw_input("Change which Grade: 
"))    
which = 
which-1    
if 0 <= which < 
len(grades):    
grade = int(raw_input("Grade: 
"))    
grades[which] = 
grade    
elif which != 
-1:    
print "Invalid Grade 
Number"    
else:    
print "Student not found"    elif menu_choice == 
5:    filename = raw_input("Filename 
to load: ")    
load_grades(students,filename)    elif menu_choice == 
6:    filename = raw_input("Filename 
to save: ")    
save_grades(students,filename)    elif menu_choice == 
9:    break    
else:    print "That's not a 
choice!"print "Goodbye."
What's the problem, and how is it fixed?
 
Thanks,
Nathan Pinno,Crew, Camrose McDonalds and owner/operator of 
Woffee

___Tutor maillist  -  Tutor@python.org

http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I've run into a jam on the exercise on file I/O

2005-08-01 Thread Adam Bark
>>> max_points = [25,25,50,25,100]
>>> assignments = ['hw ch 1','hw ch 2','quiz   ','hw ch 3','test']
>>> students = {'#Max':max_points}
>>> students
{'#Max': [25, 25, 50, 25, 100]}

The problem is the key in students is a list not an integer.On 8/1/05, Nathan Pinno <[EMAIL PROTECTED]
> wrote:






Hey all,
I've seem to run into a jam while working on the exercise on file 
I/O.
Here's the error:
Filename to save: university.txtTraceback (most recent call 
last):  File "D:\Python22\grades.py", line 99, in 
?    save_grades(students,filename)  File 
"D:\Python22\grades.py", line 51, in save_grades    
out_file.write(x+","+max_points[x]+"\n")TypeError: sequence index must be 
integer
 
And the code:
max_points = [25,25,50,25,100]assignments = ['hw ch 1','hw ch 
2','quiz   ','hw ch 3','test']students = {'#Max':max_points}
 
def print_menu():    print "1. Add 
student"    print "2. Remove student"    
print "3. Print grades"    print "4. Record 
grade"    print "5. Load Grades"    print 
"6. Save Grades"    print "9. Exit"
 
def print_all_grades():    print 
'\t',    for i in 
range(len(assignments)):    print 
assignments[1],'\t',    print    keys = 
students.keys()    keys.sort()    for x in 
keys:    print 
x,'\t',    grades = 
students[x]    
print_grades(grades)
 
def print_grades(grades):    for i in 
range(len(grades)):    print 
grades[i],'\t\t',    print
 
def choice():    return int(raw_input("Menu Choice: 
"))
 
def school():    return raw_input("Student: ")
 
def load_grades(students,filename):    in_file = 
open(filename, "r")    while 
1:    in_line = 
in_file.readline()    if in_line == 
"":    
break    in_line = 
in_line[:-1]    [students,max_points] 
= string.split(in_line,",")    
max_points[students] = grade    in_file.close()
 
def save_grades(students,filename):    out_file = 
open(filename, "w")    for x in 
students.keys():    
out_file.write(x+","+max_points[x]+"\n")    
out_file.close
 
print "Grade Tracking Program."while 1:    
print_menu()    menu_choice = choice()    
if menu_choice == 1:    print "Add 
student"    name = 
school()    students[name] = 
[0]*len(max_points)    elif menu_choice == 
2:    print "Remove 
student"    name = 
school()    if 
students.has_key(name):    
del students[name]    
else:    
print "Student: ",name," not found."    elif menu_choice == 
3:    print_all_grades()
 
    elif menu_choice == 
4:    print "Record 
Grade"    name = 
school()    if 
students.has_key(name):    
grades = 
students[name]    
print "Type in the number of the grade to 
record"    
print "Type in a 0 (zero) to 
exit"    for 
i in 
range(len(assignments)):    
print i+1,' 
',assignments[i],'\t',    
print    
print_grades(grades)    
which = 
1234    while 
which != 
-1:    
which = int(raw_input("Change which Grade: 
"))    
which = 
which-1    
if 0 <= which < 
len(grades):    
grade = int(raw_input("Grade: 
"))    
grades[which] = 
grade    
elif which != 
-1:    
print "Invalid Grade 
Number"    
else:    
print "Student not found"    elif menu_choice == 
5:    filename = raw_input("Filename 
to load: ")    
load_grades(students,filename)    elif menu_choice == 
6:    filename = raw_input("Filename 
to save: ")    
save_grades(students,filename)    elif menu_choice == 
9:    break    
else:    print "That's not a 
choice!"print "Goodbye."
What's the problem, and how is it fixed?
 
Thanks,
Nathan Pinno,Crew, Camrose McDonalds and owner/operator of 
Woffee

___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Socket Programming

2005-08-01 Thread Adam Bark
Hi Joe you can use 1 and just send 'Hi!' as long as something else
isn't likely to be sent at the same time. It will just read what is in
that socket when you call it so if something else that you don't want
is there just behind what you're after then you could end up with that
as well.On 8/1/05, Joseph Quigley <[EMAIL PROTECTED]> wrote:
Hi,Ok. But what if I wanted to send a 1 mb message? Could I leave.recv(1) in and send 'Hi!' as well or would I have to change it?Thanks,JQAdam Bark wrote:> You have to put in how many bytes of data you want to recieve in
> clientsocket.recv() eg. clientsocket.recv(1024) for 1kB.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Socket Programming

2005-08-01 Thread Adam Bark
You have to put in how many bytes of data you want to recieve in clientsocket.recv() eg. clientsocket.recv(1024) for 1kB.On 7/31/05, Joseph Quigley <
[EMAIL PROTECTED]> wrote:Hi Dan,
Danny Yoo wrote:>##>clientsocket.recv()>##>>should work better.>>Ok well I tried your examples but they didn't work. I still get:TypeError: recv() takes at least 1 argument (0 given)
How can I fix this?___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How do I make Python draw?

2005-07-27 Thread Adam Bark
Hey luke what kind of game is it? Can I have a look when at your source as well?
Cheers.
AdamOn 7/27/05, luke <[EMAIL PROTECTED]> wrote:
> Thanks. Will ask if I have any more questions. Maybe I won't have to go to> Visual Basic to write my games. Maybe Python will do the trick.Oh my god.Don't ever compare Python to Basic on a python mailing list.
You'll get eaten alive ;-)Seriously though,If you take the time to learn PyGame, it's about the easiest andbest way to write a game in any language (from scratch that is.)I highly recommend it.
In fact I'm writing a PyGame game right now.If you're interested in seeing the source at some point,Just ask.Although I won't send it just yet because it has no drawing code ATM.Just game logic.Hope ThAt HeLPs.
Don't ever resort to Visual Basic.If you think something would be easier in VB then ask usand we will tell you how to do it in Python.VB is not a good language to learn because itis the complete opposite of every other programming language.
I really can't think of a reason to use VB over Python, C++ or Java.___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Please Help: Hacking

2005-07-22 Thread Adam Bark
How to become a hackerOn 7/17/05, Suranga Sarukkali <
[EMAIL PROTECTED]> wrote:






Python's Great fro Hacking Right? Please tell me more like 
when you tell it to a College Student (That tell's What I'm) 
and since I Sort of new to Programming in Python it's going be 
easy if done so. Please reply to me at your earliest convenience and by the way 
General Hacking Education will be Cool since the only hacking I've done is on a 
Hacking Simulation Game I downloaded yeas ago from http://g1.acid-play.com/download/a599b964/Hackerv1.zip
 witch 
got all the tools like Password Crackers Inbuilt to Simulate Hacking Large 
Company's and making cash from it. You can privately email me on [EMAIL PROTECTED] 
 
I've been on the Mailing List some time and It's Great! Thanks 
for the People Developed it. 

___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] use gzip with large files

2005-07-19 Thread Adam Bark
If you use something like this:

for line in file.readlines():

then line is a string to the next newline and it automatically detects
the EOF and the same with file.readline() but that will give you one
character at a time.On 7/19/05, frank h. <[EMAIL PROTECTED]> wrote:
hello allI am trying to write a script in python that parses a gzipped logfilethe unzipped logfiles can be very large (>2GB)basically the statementsfile = gzip.GzipFile(logfile)data = ""
()for line in data.striplines():would do what I want, but this is not feasible becasue the gzip filesare so huge.So I do file.readline() in a for loop, but have no idea how long to
continue, because I dont know how many lines the files contain. How doI check for end of file when using readline() ?simply put it in a while loop and enclose it with try: except: ?what would be the best (fastest) approach to deal with such large gzip
files in python?thanks___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Catching OLE error

2005-07-14 Thread Adam Bark
I just noticed you put OLEError before the colon you should have
except:
    OLEError
    print "ole"

if that doesn't work you could just get rid of the OLEError bit and all errors will be ignored.On 7/14/05, Bernard Lebel <
[EMAIL PROTECTED]> wrote:Very well.#INFO : < NewRenderShot > importAnimation> :: Import action for character ""...
#ERROR : 2000 - Argument 0 (Source) is invalid#ERROR : 2001-ANIM-ApplyAction - Argument 0 is invalid - [line 3543 inD:\Software\Softimage\XSI_4.2\Application\DSScripts\action.vbs]#ERROR : 21000-ANIM-ImportAction - Traceback (most recent call last):
# File "

[Tutor] Catching OLE error

2005-07-14 Thread Adam Bark
Can you send me the output for an OLE error? The correct syntax should be included in the error message like this:

Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'

TypeError would be the exception so you would have:

try: None + "foo"
except: TypeErrorOn 7/14/05, Bernard Lebel <
[EMAIL PROTECTED]> wrote:
Hello,A simple question: what is the syntax in a try/except for the OLE error?Let say you want to catch OLE error:try: print stuffexcept OLEError: print 'ole'Now the problem is that I just can't seem to find anything how the
exact grammar of this error! I have looked in the Pythondocumentation, as well as the pywin32 documentation, I have tried manydifferent ways of typing it, I googled around, but yet I just can'tfind it.

ThanksBernard___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Another newbie question from Nathan.

2005-07-10 Thread Adam Bark
If I understand your problem correctly all you need to do is use the name of the function to call it ie:

def func():
    print "hello world"

func()

would give the output

"hello world"On 7/10/05, Nathan Pinno <[EMAIL PROTECTED]> wrote:
  Hi all,  How do I make Python get a def? Is it the "get" function, or somethingelse? I need to know so that I can get a def for that computerMasterMind(tm) game that I'm writing.  BTW, I took your advice, and wrote some definitions for my Giant
Calculator program. Might make the code easier to read, but harder tocodebecause I have to keep going to the top to read the menu. Not that fun,butnecessary for a smooth program, I guess.  Nathan Pinno
  "Steven D'Aprano" <[EMAIL PROTECTED]> wrote in messagenews:[EMAIL PROTECTED]  > On Sat, 02 Jul 2005 00:25:00 -0600, Nathan Pinno wrote:
  >>   Hi all.  >>   How do I make the computer generate 4 random numbers for theguess? Iwant  >> to know because I'm writing a computer program in Python like thegame  >> MasterMind.
  > First you get the computer to generate one random number. Then youdo it  > again three more times.  > If you only need to do it once, you could do it this way:  > import random  # you need this at the top of your program
  > x0 = random.random()  > x1 = random.random()  > x2 = random.random()  > x3 = random.random()  > But if you need to do it more than once, best to create a functionthat  > returns four random numbers in one go.
  > def four_random():  >"""Returns a list of four random numbers."""  >L = []  # start with an empty list  >for i in range(4):  >L.append
(random.random())  >return L  > and use it this way:  > rand_nums = four_random()  > # rand_nums is a list of four numbers  > print rand_nums[0]  # prints the first random number
  > print rand_nums[3]  # prints the last one  > or like this:  > alpha, beta, gamma, delta = four_random()  > # four names for four separate numbers  > Steven.  > 
http://mail.python.org/mailman/listinfo/python-list___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A more Pythonic way to do this

2005-06-30 Thread Adam Bark
Good, good. I probably wouldn't have been able to help you if it was
something so simple but that screws up your program and makes it hard
to find out just what is going on. Anyway good look with anymore
tidying on that you might be doing. Any chance of a copy?

AdamOn 7/1/05, D. Hartley <[EMAIL PROTECTED]> wrote:
. it was a paren.I was so worried that I just wasn't figuring it all out, that I hadtried to write elegant code and wasnt understanding the fundamentals,and the only reason it didnt work was because I left out a paren.
I actually laughed until I cried.Thanks for that.  And yes, it works now ;) it's lovely.~DeniseOn 6/30/05, Adam Bark <[EMAIL PROTECTED]> wrote:
> Here's the problem -->> enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30),> level)>>
1,2  
12> 1  0> you've put a braket after +30 which ends the Enemy call. The numbering is +1> for opening braket -1 for closing so 0 is the end of the Enemy call if you> understand this.
>>> On 6/30/05, D. Hartley <[EMAIL PROTECTED]> wrote:> >> > Hey guys!> >> > I have a 'quest,' and at first glance this email looks long, but the
> > problem is probably not as complex as the length implies.  Please bear> > with me, if I could get some advice on this particular problem, it> > would go along way toward helping me be a better Python programmer.
> >> > Some of you might remember, a few months ago, I was working on a space> > invaders game for a birthday present.  One of the functions I really> > wanted to add to the game was to change the enemy "ships" at each new
> > level. Because of my deadline and my newness to Python, I did this in> > an extremely ugly way.  To give you an idea:> >> > the original main loop called:> > enemyship_sprites = createEnemies(screen, enemy_speed)
> >> > createEnemies looks like this:> >> > def createEnemies(screen, speed):> >enemyship_sprites = EnemySprites(speed)> >for rows in xrange(5):> >for cols in xrange(8):
> >enemyship_sprites.add(Enemy((cols*60)+20,> (rows*40)+30), level)> >enemyship_sprites.draw(screen)> >return enemyship_sprites> >> > It creates an instance of EnemySprites (my holder class) which
> > contains code for when the ships hit bottom, when to update them, etc.> > It also calls "Enemy()", which looks like this:> >> > class Enemy(pygame.sprite.Sprite):> >def __init__(self, startx, starty):
> >pygame.sprite.Sprite.__init__(self)> >if level == 1:>
>self.image,
self.rect = load_image('salad_ship.bmp', -1)> >self.rect.centerx = startx> >self.rect.centery = starty> >def update(self, direction, go_down):> >jump = 40 # how much the enemies move to the right/left on
> > each jump> >if go_down:> ># if a ship is moving down on this round,> ># it doesn't move on the x-axys> >self.rect.move_ip((0, 5))
> >else:> ># move a ship in the x-axys.>
>#
if direction=1, it moves to the right; -1 to the left> >self.rect.move_ip((jump * direction, 0))> ># maybe it's time for a shot? :)> ># the chances are 1/30> >dice = 
random.randint (0,30)> >global enemy_shot_sprites> >if dice == 1:> >shot = EnemyShot(self.rect.midtop)> >enemy_shot_sprites.add(shot)> >
> >> > Now, get ready for one of the uglier things you've probably seen lately> (!!):> >> > Since I can only access the variable "level" from within the main> > loop, for some reason I thought I couldnt use it in my class
> > definitions (which of course come before and are outside of the> > mainloop).  So within the main loop, I did:> >>
>if
level == 1:>
>enemyship_sprites
= createEnemies1(screen,> enemy_speed)>
>elif
level == 2:>
>enemyship_sprites
= createEnemies2(screen,> enemy_speed)>
>elif
level == 3:>
>enemyship_sprites
= createEnemies3(screen,> enemy_speed)>
>elif
level == 4:>
>enemyship_sprites
= createEnemies4(screen,> enemy_speed)>
>elif
level == 5:>
>enemyship_sprites
= createEnemies5(screen,> enemy_speed)>
>elif
level == 6:

Re: [Tutor] A more Pythonic way to do this

2005-06-30 Thread Adam Bark
Here's the problem --> enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30), level)
   
1,2  
1   
2   
1  0
you've put a braket after +30 which ends the Enemy call. The numbering
is +1 for opening braket -1 for closing so 0 is the end of the Enemy
call if you understand this.On 6/30/05, D. Hartley <[EMAIL PROTECTED]> wrote:
Hey guys!I have a 'quest,' and at first glance this email looks long, but theproblem is probably not as complex as the length implies.  Please bearwith me, if I could get some advice on this particular problem, it
would go along way toward helping me be a better Python programmer.Some of you might remember, a few months ago, I was working on a spaceinvaders game for a birthday present.  One of the functions I really
wanted to add to the game was to change the enemy "ships" at each newlevel. Because of my deadline and my newness to Python, I did this inan extremely ugly way.  To give you an idea:the original main loop called:
enemyship_sprites = createEnemies(screen, enemy_speed)createEnemies looks like this:def createEnemies(screen, speed):   enemyship_sprites = EnemySprites(speed)   for rows in xrange(5):   for cols in xrange(8):
   enemyship_sprites.add(Enemy((cols*60)+20, (rows*40)+30), level)   enemyship_sprites.draw(screen)   return enemyship_spritesIt creates an instance of EnemySprites (my holder class) whichcontains code for when the ships hit bottom, when to update them, etc.
 It also calls "Enemy()", which looks like this:class Enemy(pygame.sprite.Sprite):   def __init__(self, startx, starty):   pygame.sprite.Sprite.__init__(self)   if level == 1:
   self.image, self.rect = load_image('salad_ship.bmp', -1)   self.rect.centerx = startx   self.rect.centery = starty   def update(self, direction, go_down):   jump = 40 # how much the enemies move to the right/left on
each jump   if go_down:   # if a ship is moving down on this round,   # it doesn't move on the x-axys   self.rect.move_ip((0, 5))   else:   # move a ship in the x-axys.
   # if direction=1, it moves to the right; -1 to the left   self.rect.move_ip((jump * direction, 0))   # maybe it's time for a shot? :)   # the chances are 1/30   dice = random.randint
(0,30)   global enemy_shot_sprites   if dice == 1:   shot = EnemyShot(self.rect.midtop)   enemy_shot_sprites.add(shot)Now, get ready for one of the uglier things you've probably seen lately (!!):
Since I can only access the variable "level" from within the mainloop, for some reason I thought I couldnt use it in my classdefinitions (which of course come before and are outside of themainloop).  So within the main loop, I did:
   if level == 1:  
enemyship_sprites = createEnemies1(screen, enemy_speed)   elif level == 2:  
enemyship_sprites = createEnemies2(screen, enemy_speed)   elif level == 3:  
enemyship_sprites = createEnemies3(screen, enemy_speed)   elif level == 4:  
enemyship_sprites = createEnemies4(screen, enemy_speed)   elif level == 5:  
enemyship_sprites = createEnemies5(screen, enemy_speed)   elif level == 6:  
enemyship_sprites = createEnemies6(screen, enemy_speed)   elif level == 7:  
enemyship_sprites = createEnemies7(screen, enemy_speed)   elif level == 8:  
enemyship_sprites = createEnemies8(screen, enemy_speed)   else:  
enemyship_sprites = createEnemies9(screen, enemy_speed)And yes, I created 9 different createEnemies, all pretty much carboncopies of each other except that they called Enemy1, Enemy2, Enemy3,etc.  And then (you guessed it), I created 9 different Enemy
functions, too, so that each one could have its own (different)bitmap.Now... this is just ridiculous.To my credit, I did actually know that at the time. But the day beforethe birthday, I figured if I could make it work somehow, I would, and
I'd make it prettier later.  Now just happens to be that later ;)So now that I've got a little more Python experience under my belt(not much, but a little), it occurred to me that when I callcreateEnemies in the mainloop, I could pass in an argument 'level'.
mainloop now starting off with:enemyship_sprites = createEnemies(screen, enemy_speed, level)level is one of my main loop variables, so it'll know what i'm talkingabout and can take that variable and pass it in when it calls
createEnemies. (Btw, please forgive me if I mix up terms like argumentand variable or use them in the wrong places, I'm still getting usedto them!)  In any case, then I changed my createEnemies to look like
this:def crea

[Tutor] wxPython shaped window

2005-06-30 Thread Adam Bark
On 6/26/05, Adam Cripps <[EMAIL PROTECTED]> wrote:


On 6/25/05, Adam Bark <[EMAIL PROTECTED]> wrote:> Thanks for the info Adam I just seem to be having a problem with the panel
> size it greys out nearly all the image. Ideally I would like to make the
> panel transparent but I can't work out how to do that.>>> On 6/25/05, Adam Cripps <
[EMAIL PROTECTED]> wrote:> > On 6/25/05, Adam Bark <
[EMAIL PROTECTED] > wrote:> > > Is it possible to put controls into a shaped window in wxPython. I have
> > > tried putting a button on the demo and it becomes the exact size and
> shape> > > of the window. Also when I tried to bind it to an action it wouldn't> even> > > start.> > >> > >  Adam> > >> >> > I'm working through something similar myself at the moment.
> >> > Try adding a wx.Panel to the frame and then the button to the panel.> > You can position them through pos parameter, but it should default to> > the top left of the panel and have a good size if you use
> > button.SetSize(button.GetBestSize())> >> > HTH> >> > AdamAdam - how much code do you have? Why not post it either here or thewxpython-users list (to which I'm also subscribed) and we can take a
look.Adam--http://www.monkeez.orgPGP key: 0x7111B833

I tried posting to the wxpython-users list but I'm not sure it worked nobody replied anyway.
Here's my test script:

import wx

class Frame(wx.Frame):
    def __init__(self):
    wx.Frame.__init__(self, None, -1, "Shaped Window",
style =
  
wx.FRAME_SHAPED

| wx.SIMPLE_BORDER

| wx.FRAME_NO_TASKBAR

| wx.STAY_ON_TOP

)
    self.hasShape = False
    self.delta = (0,0)
    
    self.Bind(wx.EVT_PAINT, self.OnPaint)
    self.Bind(wx.EVT_MOTION, self.OnMouseMove)
    
    self.bkground = wx.Bitmap("/home/adam/bkgrnd.gif", wx.BITMAP_TYPE_GIF)
    w, h = self.bkground.GetWidth(), self.bkground.GetHeight()
    self.SetClientSize((w, h))
    self.Bind(wx.EVT_WINDOW_CREATE, self.SetWindowShape)
    panel = Panel(self, w, h)
    panel.Show()
    dc = wx.ClientDC(self)
    dc.DrawBitmap(self.bkground, 0,0, True)
    
    def SetWindowShape(self, evt):
    # Use the bitmap's mask to determine the region
    r = wx.RegionFromBitmap(self.bkground)
    self.hasShape = self.SetShape(r)
    
    def OnPaint(self, event):
    dc = wx.PaintDC(self)
    dc.DrawBitmap(self.bkground, 0,0, True)
    
    def OnMouseMove(self, evt):
    if evt.Dragging() and evt.LeftIsDown():
    x, y = self.ClientToScreen(evt.GetPosition())
    fp = (x - self.delta[0], y - self.delta[1])
    self.Move(fp)

class Panel(wx.Panel):
    def __init__(self, parent, width, height):
    wx.Panel.__init__(self, parent, -1, size=(width, height))

    button = wx.Button(self, -1, "hello")
    button.SetSize(button.GetBestSize())
    self.SetSize((width, height))
    #print dir(self)
    
if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = Frame()
    frame.Show()
    app.MainLoop()

Thanks.
Adam.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  1   2   >