[Tutor] Conway's game of life

2019-02-21 Thread Phil
Thank you for reading this.

It's been quite some time since I've attempted any programming and since
I've recently discovered PySimpleGUI I thought I'd have a go at programming
Conway's game of life. Unfortunately, I've been stuck trying to resolve a
logic error for the past couple of weeks using the IDLE debugger and a host
of print statements. I can see where the error occurs but I cannot see why.

The error occurs at the point of the third generation which results in a
fixed pattern of cells rather that a looping pattern. It's always the third
generation no matter what the initial pattern is. The error seems to be in
the area where the rules are applied.

Can a kind person spend a couple of minutes to find what is most likely an
obvious error?

import sys
import PySimpleGUI as sg
import time
import numpy

layout = [[sg.Graph(canvas_size=(400, 400),
   graph_bottom_left=(0,20),
   graph_top_right=(20,0),
   background_color='white',
   key='graph')],]

window = sg.Window('The game of life',
grab_anywhere=True).Layout(layout).Finalize()

graph = window.FindElement('graph')

board_size = 8#20

dead = 0
live = 1

#board = [[dead] * board_size for i in range(board_size)]
#next_board = [[dead] * board_size for i in range(board_size)]

board = numpy.zeros(board_size * board_size, dtype='i').reshape(board_size,
board_size)
#board = numpy.zeros((board_size, board_size))

#next_board = numpy.zeros((board_size, board_size))
next_board = numpy.zeros(board_size * board_size,
dtype='i').reshape(board_size, board_size)


'''
seed board[y][x] NOT board[x][y]
'''

board [1][1] = dead
board [1][2] = live
board [1][3] = dead

board [2][1] = dead
board [2][2] = dead
board [2][3] = live

board [3][1] = live
board [3][2] = live
board [3][3] = live

def display():
event, values = window.Read(timeout = 0)

for y in range(board_size):
for x in range(board_size):

if (board[x][y]) == 0:
graph.DrawCircle((y,x), 5, line_color='white',
fill_color='red')#'white')

else:
graph.DrawCircle((y,x), 5, line_color='black',
fill_color='black')

window.Refresh()

time.sleep(2)

def count_live_neighbours(x, y):
live_neighbours = 0

debug_cell = board[x][y]

for i in range(-1, 2):
for j in range(-1, 2):
live_neighbours += board[x + i][y + j]

#don't count the cell at x = 0 and y = 0
live_neighbours -= board[x][y]

return live_neighbours

#display initial board
display()

while True:
#clear next_board
#next_board.fill(0)

for x in range(1, board_size - 1):
for y in range(1, board_size - 1):

live_neighbours = count_live_neighbours(x, y)

'''
Any live cell with fewer than two live neighbors dies, as if by
underpopulation.
Any live cell with two or three live neighbors lives on to the next
generation.
Any live cell with more than three live neighbors dies, as if by
overpopulation.
Any dead cell with exactly three live neighbors becomes a live cell, as if
by reproduction.

'''
if board[x][y] == 1 and live_neighbours <  2:
next_board[x][y] = 0

elif board[x][y] == 1 and live_neighbours >  3:
next_board[x][y] = 0

elif board[x][y] == 0 and live_neighbours == 3:
next_board[x][y] = 1

elif board[x][y] == 1 and (live_neighbours == 2 or
live_neighbours == 3):
next_board[x][y] = 1

#else:
#next_board[x][y] = board[x][y]

board = next_board

display()





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


Re: [Tutor] Converting a string to a byte array

2017-09-25 Thread Phil

On 26/09/17 07:02, Cameron Simpson wrote:


Just to this. If your serial file handle is a normal buffered one, you 
may also need to call .flush(). When you run from the command line as 
"python3 mycode.py" is done automatically at programme exit. In the IDE, 
the programme has not exited, so your bytes may be lurking in the 
buffer, unsent.


Thank you Cameron, that sounds like a logical explanation. I'll try it.

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


Re: [Tutor] Converting a string to a byte array

2017-09-24 Thread Phil

On 25/09/17 07:26, Cameron Simpson wrote:
Thank you Cameron and Peter for your replies.

I don't understand why this works from the pyqt IDE but not when run 
from the console. I suppose the IDE is adding the correct encoding.


I'm guessing the IDE is python 2 and not doing any encoding at all. In 
python 2 str _is_ effectively bytes and if you stay in ASCII you just 
get away with it.




No, the IDE is Eric and as far as I know it's python3 only. Just for 
interest I amended my code to use what you provided and tried it under 
IDLE. There aren't any errors but but my Arduino is not responding. 
However, if I enter python3 mycode.py then it works perfectly. I'm sure 
there's an explanation for this. I have thoney, another python IDE, on a 
raspberrypi I'll try that later and see what the result is. Anyway, it 
works from Eric and from the command prompt.



So you need to know what your serial device expects. ASCII only?


As it turns out, it doesn't matter if the data is ASCII or UTF-8.


  mytext = "Fred"
  mytext = mytext + "\n"
  mybytes = mytext.encode('utf-8')
  ser.write(mybytes)

Notice that I've appended the newline _before_ converting to bytes,


Thank you for the code and the explanation, it's greatly appreciated.

It's all a bit of an anticlimax really. Now that it works I don't know 
what to do with it. Like so many of my projects.


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


[Tutor] Converting a string to a byte array

2017-09-24 Thread Phil

Thank you for reading this.

The following code sends "Fred" to my serial connected device without 
any problems.


import serial

ser = serial.Serial('/dev/ttyACM0',9600)
ser.write(b'Fred\n')


I'm trying to do the same under pyqt but I'm having trouble converting a 
string to a byte array. This works correctly from the pyqt IDE but not 
from the console. python3 mycode.py generates "typeError: string 
argument without an encoding"


It's very likely that my method of converting a string to a byte array 
is incorrect. This is my attempt:


mytext = "Fred"
mybytes = bytes(mytext)
byte = byte + '\n'
ser.write(mybytes)

I don't understand why this works from the pyqt IDE but not when run 
from the console. I suppose the IDE is adding the correct encoding. I 
suspect utf8 is involved somewhere.


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


Re: [Tutor] Tkinter + frame + grid question

2017-05-15 Thread Phil
On Mon, 15 May 2017 16:14:48 +0200
Peter Otten <__pete...@web.de> wrote:

Thank you Peter, Alan and Abdur-Rahmaan for your replies.

After a night's sleep I'm now well on the way to beautifying a Lotto checking 
program that I wrote a couple of years ago. The need for and the use of frames 
is now clearer to me now, plus I now see why I should include the use of 
columnconfigure and sticky.

I knew about tix but hadn't investigated it until now. I'll have to play with 
it.

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


[Tutor] Tkinter + frame + grid question

2017-05-15 Thread Phil
Thank you for reading this.

I'd like to place a red frame in the centre of the main window.

I've discovered two ways to achieve this using place() and pack(padx, pady). 
Grid() does not give the desired result.

Next I'd like to place some widgets on the frame. Again place() does what I 
want and pack() almost does except the red frame is the size of the padding. It 
now seems to me that this is the way it's supposed to work. I'd like to use 
grid(), but so far, all that I can achieve is to place widgets on the main 
window and not the frame. The frame does not display if I use grid().

I've spent hours on this and an Internet search has not helped at all. However, 
I did learn that grid() and pack() are not compatible, could this be the 
problem? Perhaps I have to let go of the familiar grid() method and use pack() 
instead? Place() does exactly what I want but it's a bit cumbersome to use. The 
more I think about it, the more I think pack() is the go.

Still, I'd like to know, what's the best method?

The following is a summary of what I've tried:

from tkinter import *

class App:

def __init__(self, master):
master.geometry('400x400+50+50')
frame = Frame(master, width = 300, height = 300, bg = 'red')

frame.pack(pady = 50)
#frame.place(x = 50, y = 50)


Entry(frame).place(x = 100, y = 100, anchor = CENTER)
#Entry(frame).pack(padx = 20, pady = 20)
#Entry(frame).grid(row = 10, column = 1)

#Entry2 = Entry
#Entry2(frame).grid(row = 20, column = 1)


root = Tk()
app = App(root)
root.mainloop()

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


Re: [Tutor] Another set question

2017-05-01 Thread Phil
On Sun, 30 Apr 2017 15:58:13 +0100
Alan Gauld via Tutor <tutor@python.org> wrote:

> I would probably combine both such that for each cell you
> have a tuple containing the given number and the set of
> candidates. In some cases the number may be a sentinel
> (such as -1) to indicate no number yet, and for some
> cells the set will be empty.
> 
> But by always having both available your data handling
> becomes consistent, you always know that you get a tuple
> and you know can easily test the sentinel to see3 if
> the value is set or not. And you never need to
> test types.


Thank you again Alan,

During the intervening period between when my question appeared on the mailing 
list, plus our time zone difference, I had come to almost the same conclusion. 
All numbers are now sets, the likely candidates and the given numbers. No more 
fooling around with different types, they're all sets. I now have a working 
solution.

Many of the methods have very similar code to each other and I'm currently 
working on making the code simpler and less confusing. After that I'll give 
programming a rest for awhile.

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


Re: [Tutor] Another set question

2017-04-29 Thread Phil
On Sat, 29 Apr 2017 20:27:17 +1000
Ben Finney <ben+pyt...@benfinney.id.au> wrote:

> Why is the data in such a state that you can't decide how to use it
> until you know whether it is a set versus a string? Can the data be
> handled differently? We'll need to know what you're trying to achieve,
> to answer properly.

Thank you Ben. A rethink of the problem during the 20 hours since I posted my 
most recent question has led to a solution.

I'm rewriting a C++ program that I wrote 15 years ago to solve sudoko puzzles. 
I'm having some difficulty with the translation in part because of my poorly 
documented code and because Python does some things differently. I've abandoned 
my original translation attempt and have started afresh which is probably a 
good idea. It took me months to solve come up with a working solution in C++ 
whereas I almost have a working solution in Python in a little over a week.

The strings are the given numbers while the sets are the likely candidates.

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


Re: [Tutor] Another set question

2017-04-29 Thread Phil
On Fri, 28 Apr 2017 19:42:36 -0700
"Martin A. Brown" <mar...@linux-ip.net> wrote:

> 
> Hello and greetings Phil,
> 
> >> I'm trying to implement a conditional branch based on a variable
> >> type.
> >
> >This is often (not always) a mistake, in Python. So the question
> >needs to be asked: What makes you think that condition is a
> >requirement?
> >
> >So, I suspect you will need to explain better what larger problem you
> >are trying to solve, and re-consider whether the condition you're
> >trying to test is actually going to help that purpose.

Thank you Ben and Martin for your detailed replies. I was debating whether or 
not to post my question at all because it looked vague, even to me.

This a simplified version of what I had in mind:

alist = [1,2,9,6]

alist[2] = set({4})

for i in range(4):
if i is a set:
do this

1, 2 and 6 are given numbers and the set containing 4 is what I want to operate 
on.

My alternative method that I mentioned in my previous question compares each 
alist[i] number to another list of given numbers. If alist[i] does not appear 
in the given number list then it must be a set. At this point of the program 
I'm only interested in sets that have only have one member. Sets with more than 
one member are dealt with later.

I'm nearly certain that this is the method that I should continue to pursue, 
unless someone can offer a cleverer solution.

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


[Tutor] Another set question

2017-04-28 Thread Phil
I'm trying to implement a conditional branch based on a variable type.
For example, if c is a character and s is a set with only one member.

c = "9"
s ={9}

if type(c) == a string:
do this
else:
do that

An alternative that I've attempted is to test if a set contains one member 
based on len(). However, I then cannot tell if len() is referring to a single 
character or a single set with one member. So I'm back to square one.

A for loop is indexing mixed lists of characters (one character per list) and 
lists that a set with one member. I'm only interested in the sets and want to 
ignore the character lists.

I have come up with a method that will probably work but it's become quite 
messy with multiple compare statements. Something simple and less prone to 
cause headaches would be better.
 
-- 
Regards,
Phil
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Sets question

2017-04-27 Thread Phil
On Thu, 27 Apr 2017 11:49:55 +0200
Peter Otten <__pete...@web.de> wrote:


> I'd like to bring to your attention the discard() method
> 
> >>> s = {1, 2, 3}
> >>> s.discard(int(v))
> >>> s
> {2, 3}
> 
> which allows you to avoid building the throwaway single-entry set.

Thank you Peter. I have been using the remove() method which, by the look of 
it, may do the same thing as discard(). I'll have a play and see.

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


Re: [Tutor] Sets question

2017-04-26 Thread Phil
On Thu, 27 Apr 2017 01:58:39 +
eryk sun <eryk...@gmail.com> wrote:


> That exception indicates you probably used set(int(num)) instead of
> either {int(num)} or set([int(num)]).

Thank you Eryl, you are correct. Problem solved.

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


Re: [Tutor] Sets question

2017-04-26 Thread Phil
On Wed, 26 Apr 2017 18:56:40 -0600
Mats Wichmann <m...@wichmann.us> wrote:

> On 04/26/2017 06:33 PM, Phil wrote:
> > Another question I'm afraid.
> > 
> > If I want to remove 1 from a set then this is the answer:
> > 
> > set([1,2,3]) - set([1])
> > 
> > I had this method working perfectly until I made a change to cure
> > another bug.
> > 
> > So, I have a set represented in the debugger as {1,2,3} and again I
> > want to remove the one. Only this time the one set is represented
> > as {'1'} and, of course {'1'} is not in the set {1,2,3}.
> > 
> > Ideally, I would like {'1'} to become {1}. Try as I may, I have not
> > discovered how to remove the '' marks. How do I achieve that?
> > 
> 
> A little confused... why not just create it the way you want it? How
> do you end up with {'1'} ?

Thank you for your quick replies Mats and erky.

I use .get() to retrieve a number from an entry box, which looks like {1} (no 
'' marks). If I then turn this number into a set then the result is {'1'}.

num = self.entry_grid[row][col].get()
self.solution[row][col] = set([num])

As I say, my project worked perfectly with just {1} until I discovered a bug 
further on in the code. Perhaps I should go back to my original version and the 
fix the bug in some other way?

I did try {int(num)} but that resulted in an error that said something along 
the lines of int not being iterable. I'll have another look at that idea.

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


[Tutor] Sets question

2017-04-26 Thread Phil
Another question I'm afraid.

If I want to remove 1 from a set then this is the answer:

set([1,2,3]) - set([1])

I had this method working perfectly until I made a change to cure another bug.

So, I have a set represented in the debugger as {1,2,3} and again I want to 
remove the one. Only this time the one set is represented as {'1'} and, of 
course {'1'} is not in the set {1,2,3}.

Ideally, I would like {'1'} to become {1}. Try as I may, I have not discovered 
how to remove the '' marks. How do I achieve that?

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


Re: [Tutor] Tkinter layout question

2017-04-26 Thread Phil
On Tue, 25 Apr 2017 23:27:05 +0100
Alan Gauld via Tutor <tutor@python.org> wrote:


> Your messages come into the moderation queue, I'm
> not sure why because the moderation flag is not
> set on your account(it is automatically for new
> members).
> 
> I'll have a closer look next eek when I get back.

Thanks Alan, maybe the reason that I'm in the moderation queue is because I'm 
on the bounces list. I'm on six different bounces lists but I'm still receiving 
e-mail so I suppose there isn't a real problem.

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


Re: [Tutor] Tkinter layout question

2017-04-24 Thread Phil
On Mon, 24 Apr 2017 20:02:32 +0100
Alan Gauld via Tutor <tutor@python.org> wrote:

> On 24/04/17 01:50, Phil wrote:
> > On Mon, 24 Apr 2017 09:24:55 +1000
> > Phil <phil_...@bigpond.com> wrote:
> >
> >> On Sun, 23 Apr 2017 09:39:54 +0200
> >> Sibylle Koczian <nulla.epist...@web.de> wrote:
> >>
> >>> Am 20.04.2017 um 14:43 schrieb Alan Gauld via Tutor:
> >>>> Its not too bad you can map the large 9x9 table to the smaller
> >>>> units using divmod()
> >>>>
> >>>> So the 7th element becomes
> >>>> divmod(7) -> 2,1
> >>>>
> >>>
> >>> Should be divmod(7, 3), shouldn't it?
> 
> Yes, of course, sorry about that!
> The 3 of course is the number of items per cell (3x3)
> 
> > Say I want the 7th cell in the first line of a 9 x 9 grid,
>  > that would be x = 7, y = 1.
> 
> But you want it mapped to a cell/item pair...
> 
> divmod(7,3) -> 2,1
> 
> 
> The 3rd cell, 2nd item which is wrong for the item part.
> So you need to use:
> 
> 2, 1-1

Thank you Alan, problem solved. All this horsing around with adding and 
subtracting 1 had initially led to a mass of confusing code hence the posting 
of my second message on this subject. Don't bother with that message, it's 
complete nonsense.

By the way, I notice that my messages to this list, and not other's, can take 
up to four hours (sometimes longer) to appear, is that normal? I'm on a bounces 
list, is that the reason? Probably not since I'm on several bounces lists.

Anyway, enjoy your holiday.

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


Re: [Tutor] Tkinter layout question

2017-04-24 Thread Phil
On Sun, 23 Apr 2017 11:28:51 +0200
Peter Otten <__pete...@web.de> wrote:

> Consider the function make_a_cake(). If you use it
> 
> eat_a_piece_of(make_a_cake())
> eat_a_piece_of(make_a_cake())
> 
> that's short for
> 
> one_cake = make_a_cake()
> eat_a_piece_of(one_cake)
> 
> another_cake = make_a_cake()
> eat_a_piece_of(another_cake)
> 
> i. e. you had two pieces of cake, one piece of each of two cakes.
> 
> If you write
> 
> cake = make_a_cake()
> eat_a_piece_of(cake)
> eat_a_piece_of(cake)
> 
> you have still eaten two pieces of cake but both are taken from the
> same cake.
> 
> Likewise when you write
> 
> root = tk.Tk()
> first_table = DisplayTable(root)
> second_table = DisplayTable(root)
> 
> both tables share the same instance of the Tk class.
>  
> > Also I found that root.mainloop() isn't necessary in that the
> > result is the same with or without. Perhaps it serves some other
> > purpose?
> 
> Try running it from the command line, not in idle. In every tkinter
> program there must be a main loop to respond to events.

Thank you again Peter for taking the time to answer my question.

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


Re: [Tutor] Tkinter layout question

2017-04-23 Thread Phil
On Mon, 24 Apr 2017 09:24:55 +1000
Phil <phil_...@bigpond.com> wrote:

> On Sun, 23 Apr 2017 09:39:54 +0200
> Sibylle Koczian <nulla.epist...@web.de> wrote:
> 
> > Am 20.04.2017 um 14:43 schrieb Alan Gauld via Tutor:
> > > Its not too bad you can map the large 9x9 table to the smaller
> > > units using divmod()
> > >
> > > So the 7th element becomes
> > > divmod(7) -> 2,1
> > >
> > 
> > Should be divmod(7, 3), shouldn't it?
> 
> Thanks Sibylle, I eventually stumbled upon the answer using my usual
> trial-and-error method. The 3, as in the number of cells, was the key.

Actually, that's not correct either.

Say I want the 7th cell in the first line of a 9 x 9 grid, that would be x = 7, 
y = 1. divmod(7,1) = 2,1 or the first cell in grid 3. So far so good.

Another example, x = 4, y = 3. divmod(4,3) = 1,1. What I need here is grid 2 x 
= 1 and y = 3.

Further complications are, arrays, or lists in Python, start a 0 and divmod may 
not be the answer because divide by 0 is not possible. Making adjustments for 
these two possibilities has resulted in complicated code that does give the 
desired result. Of course, I may have misunderstood the intention of Alan's 
mapping method.

So, what I need is a function to map from a 9 x 9 grid to a cell in a 3 x 3 
grid.

My feeble simplified attempt is as follows:

def map_cell(x,y):
return divmod(x,y)

while(True):
x,y = input().split(" ")
print (map_cell(int(x), int(y)))

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


Re: [Tutor] Tkinter layout question

2017-04-23 Thread Phil
On Sun, 23 Apr 2017 09:39:54 +0200
Sibylle Koczian <nulla.epist...@web.de> wrote:

> Am 20.04.2017 um 14:43 schrieb Alan Gauld via Tutor:
> > Its not too bad you can map the large 9x9 table to the smaller units
> > using divmod()
> >
> > So the 7th element becomes
> > divmod(7) -> 2,1
> >
> 
> Should be divmod(7, 3), shouldn't it?

Thanks Sibylle, I eventually stumbled upon the answer using my usual 
trial-and-error method. The 3, as in the number of cells, was the key.

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


Re: [Tutor] Tkinter layout question

2017-04-23 Thread Phil
On Sun, 23 Apr 2017 09:52:16 +0200
Peter Otten <__pete...@web.de> wrote:

> If you wrote the above with Buttons instead of DisplayTables you'd
> encounter the same behaviour. The problem is that you call
> tkinter.Tk() twice (which is generally a recipe for disaster; if you
> want multiple windows use tkinter.Toplevel() for all but the first
> one). 
> 
> Once you have fixed that you should be OK:
> 
> import tkinter as tk
> import table_class
> 
> root = tk.Tk()
> 
> tab = table_class.DisplayTable(root,
> ["Left","middle","Right"],
> [[1,2,1],
> [3,4,3],
> [5,6,5]],
> datacolor='blue',
> cellcolor='yellow',
> gridcolor='red',
> hdcolor='black')
> 
> second_tab = table_class.DisplayTable(root,
> ["Left","middle","Right"],
> [[1,2,1],
> [3,4,3],
> [5,6,5]],
> datacolor='blue',
> cellcolor='green',
> gridcolor='red',
> hdcolor='black')
> 
> tab.pack(side=tk.LEFT)
> second_tab.pack()
> 
> root.mainloop()

Thank you again Peter. Of course your changes worked but at the moment I'm not 
sure why.

if root = tk.Tk() then why isn't table_class.DisplayTable(root, the same as 
table_class.DisplayTable(tk.Tk(),. Obviously it isn't but I don't know why.

Also I found that root.mainloop() isn't necessary in that the result is the 
same with or without. Perhaps it serves some other purpose?

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


Re: [Tutor] Tkinter layout question

2017-04-22 Thread Phil
On Thu, 20 Apr 2017 13:43:07 +0100
Alan Gauld via Tutor <tutor@python.org> wrote:

> If still confused drop a question here.

I hope I'm not over doing the questions here. I'm only posting after hours of 
experimenting and Internet searching.

How do I create multiple instances of the table on the one frame? I think the 
table class as presented is not capable of that. If I create multiple instances 
like this then, of course, I end up with two instances of the same frame.

import tkinter as tk
import table_class

tab = table_class.DisplayTable(tk.Tk(),
["Left","middle","Right"],
[[1,2,1],
[3,4,3],
[5,6,5]],
datacolor='blue',
cellcolor='yellow',
gridcolor='red',
hdcolor='black')


second_tab = table_class.DisplayTable(tk.Tk(),
["Left","middle","Right"],
[[1,2,1],
[3,4,3],
[5,6,5]],
datacolor='blue',
cellcolor='green',
gridcolor='red',
hdcolor='black')

second_tab.pack(side = tk.LEFT)
tab.pack()

I've tried different pack options including packing onto the parent frame.

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


Re: [Tutor] Tkinter layout question

2017-04-22 Thread Phil
On Sat, 22 Apr 2017 10:37:19 +0200
Peter Otten <__pete...@web.de> wrote:

> That's unnecessary. The code protected by 'if __name__ == "__main__"'
> is not executed when the module is imported. In fact that's the very
> purpose of this idiom.

> 
> "Best practice" is to avoid star imports which bind every name from 
> table_class that does not start with "_", including 'tk' to the same
> name in the importing module.
> 

Thank you Petter for explaining these points, most helpful.

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


Re: [Tutor] Tkinter layout question

2017-04-21 Thread Phil
On Thu, 20 Apr 2017 13:43:07 +0100
Alan Gauld via Tutor <tutor@python.org> wrote:

> If still confused drop a question here.

Maybe not totally confused, more a question of best practice.

Using your example table class, I commented out all from, and including, "if 
__name__ == "__main__":" down and saved the file as table_class.py. I then 
created test.py as follows:

from table_class import *

top = tk.Tk()

tab = DisplayTable(top,
["Left","middle","Right"],
[[1,2,1],
[3,4,3],
[5,6,5]],
datacolor='blue',
cellcolor='yellow',
gridcolor='red',
hdcolor='black')

tab.pack()

Two questions:
I can see where tk comes from but I'm unsure of the origin of Tk() other than a 
reference to tkinter.
Have I used you table class correctly? It works, of course, but it doesn't look 
correct.

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


Re: [Tutor] Tkinter layout question

2017-04-20 Thread Phil
On Thu, 20 Apr 2017 09:27:27 +0100
Alan Gauld via Tutor <tutor@python.org> wrote:

> Eek! that's a recipe for premature baldness!

Baldness is not a problem, however, slowing the onset of dementia is the aim of 
this project.

> So, for a Suduko grid put 3x3 Entry boxes into a Frame.
> Then put 3x3 such frames into another frame.

OK, so I'll go back to my original idea and use edit boxes. A grid of 9 x 9 
edit boxes does actually work and it makes it easy to keep track of the digits. 
The first digit is [0,0], the first digit on the second line is [1,0] etc. Nine 
3 x 3 boxes could add some complication to digit tracking.

> Don't try to reinvent all of that yourself, it will
> result in tears. (Think about how you will control
> cursor movement, deletions, selections etc etc)

I did actually get my canvas version to the point where I could enter digits 
into the cells but I had to enter them in sequence so that the logic part of 
the program knew where the digits were. It was all becoming somewhat 
complicated.

Thank you for the table example. I'm not sure what "tab = DisplayTable" does at 
the moment, I'll have to run it to find out.

Thank you for your detailed answer, more food for though.

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


Re: [Tutor] Tkinter layout question - solved

2017-04-20 Thread Phil
On Wed, 19 Apr 2017 22:21:28 -0500

Just to save people answering this question unnecessarily I have solved the 
immediate problem. I can now enter a digit at the mouse coordinates. Some 
refinement is still necessary.

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


Re: [Tutor] Tkinter layout question

2017-04-20 Thread Phil
On Wed, 19 Apr 2017 22:21:28 -0500
boB Stepp <robertvst...@gmail.com> wrote:

Thank you Bob and Palm for your replies. They have given me something more tto 
think about.
ideas
> I don't know (now) how to solve your challenges below.  But if I were
> trying to figure this out, I would try to find more complex tkinter
> example applications

I have searched the Internet for hours looking for a game example. Most 
examples demonstrate the use of specific widgets including the canvas and 
frames but not in a class context. Putting the pieces together is difficult but 
I will persevere.

A reference book full of examples is the obvious way to go I suppose. However, 
it is difficult me to manage paper books because the space they take up and 
their weight. I do have one general Python e-book but following the few 
examples is tedious to the nth degree because the text of the examples is so 
small that I need a magnifying glass to read them.

Anyway, maybe I can justify one book, I'll give it some thought. The massive 
tome by Lutz comes to mind.

I'll give your keyboard entry suggestion some more thought.

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


[Tutor] Tkinter layout question

2017-04-19 Thread Phil
I'm looking for ideas here.

A working solution for my sudoku solver is a 9 x 9 grid of entry boxes but it 
looks a bit basic. So I created a 9 x 9 grid on a canvas which looks much 
better. I can display digits in the centre of the squares but entering the 
digits from the keyboard seems to be beyond me. I experimented with entering a 
digit at the mouse location but it all seems to be too complicated. Perhaps 
someone can offer a repetitively simple solution?

A second experiment involved the earlier grid of entry boxes but with a space 
between every third row and column. This seems to be more achievable, 
eventually.

Something along these lines:

for i in range(9):
if i % 4 == 0:
place a blank text label
else:
place an entry box

So, how might I enter digits into a grid on a canvas or how could I create a 
space between a grid entry boxes?

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


Re: [Tutor] Tkinter and canvas question

2017-04-18 Thread Phil
On Mon, 17 Apr 2017 22:57:41 -0500
boB Stepp <robertvst...@gmail.com> wrote:

> I have yet to do much class writing with tkinter, but if I am
> understanding things correctly, in your Sudoku class where you
> instantiate a Canvas instance, you assign it to the name "the_canvas".
> This will be local to the __init__ method's namespace.  I think you
> need to precede each of those "the_canvas" with "self." to get
> "self.the_canvas".  This way your solve method will be able to access
> it.

Thank you Bob. I was fixated on the error being elsewhere and didn't think 
about the_canvas being just another attribute of the class. It seem obvious now 
that I've been shown.

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


[Tutor] Tkinter and canvas question

2017-04-17 Thread Phil
Thank you for reading this.

How do I reference the_canvas from my solve() method? Despite hours of 
searching I haven't been able to solve this or find a similar example. All that 
I've gained is a headache.

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__
return self.func(*args)
  File "/home/pi/sudoku.py", line 64, in solve
self.the_canvas.create_text(20,20,text="5")
AttributeError: 'Sudoku' object has no attribute 'the_canvas'

from tkinter import *

class Sudoku(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent

parent.title("Sudoku solver")

#create canvas
the_canvas = Canvas(width = 300, height = 300)  
   
the_canvas.pack(side = TOP, anchor = NW, padx = 10, pady = 10)

#create grid

#create solve button
solve_button = Button(the_canvas, text = "Solve", command = self.solve,
anchor = W)
solve_button.configure(width = 5, activebackground = "#33B5E5",
relief = FLAT)
solve_button.pack(side = TOP)
solve_button_window = the_canvas.create_window(250, 250, anchor=NW, 
window=solve_button)

def solve(self):
print("solve called")
self.the_canvas.create_text(20,20,text="5")


def main():
root = Tk()
app = Sudoku(root)
app.mainloop()

if __name__ == '__main__':
main()


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


Re: [Tutor] Tkinter entry box text changed event

2017-04-10 Thread Phil
On Mon, 10 Apr 2017 19:40:01 +0100
Alan Gauld via Tutor <tutor@python.org> wrote:

> You want two parameters
> self becaiuse its a method of a class so must have a self
> event which is the event passsed by the GUI
> So:
> 
> def my_method(self, event):
> print("method called with ",event)
> 
> 
> > I must be close, surely.
> 
> A comma instead of a dot...
> 
Thank you so much for your patience Alan.

I woke during the early hours thinking about the requirement for two parameters 
and realised that my other methods only have self as a single parameter and 
wondered if "event" was the other parameter. I hadn't though of printing the 
event. 

Take no notice of this message's posting time, I started my Raspberry Pi before 
the modem had established an Internet connection. It's pre sunrise here.

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


Re: [Tutor] Tkinter entry box text changed event

2017-04-10 Thread Phil
On Mon, 10 Apr 2017 09:31:10 +0200
Peter Otten <__pete...@web.de> wrote:

> entry.bind("", bye)

Thank you Peter and Alan,

I had tried key-press but that caused the error message shown bellow which made 
me think that I was not on the correct track. So in desperation, after hours of 
frustration, I tried StringVar() because I'd seen that in a Stack overflow 
answer.

Adapting Peter's example I have:

self.numbers[i].bind("", self.my_method)

def my_method(self.event):
print("method called")

(self.event) is a syntax error and if I leave off "self", this is the result:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__
return self.func(*args)
TypeError: my_method() takes 1 positional argument but 2 were given

I must be close, surely.

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


[Tutor] Tkinter entry box text changed event

2017-04-09 Thread Phil
Again, thank you for reading this.

I would like a function to be called when I enter text and then tab to the next 
entry box. I've been trying to follow the answers to similar questions in Stack 
Overflow but I've become hopelessly confused because of the different answers 
given to seemingly the same question.

I have created a row of entry boxes and a matching function like this:

for i in range(8):
self.numbers[i]= Entry(master, width=4, justify=CENTER, foreground="gray")
self.numbers[i].grid(row=16, column=i)
self.numbers[i].bind('StringVar()', self.my_function)

def my_function(event):
print("function called")

The function is not called and I know that the binding of the function to the 
entry boxes is not the correct method. What am I missing?

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


Re: [Tutor] Tkinter class question

2017-04-08 Thread Phil
On Sat, 08 Apr 2017 09:12:17 +0200
Peter Otten <__pete...@web.de> wrote:

Thank you yet again Peter.

I realised what the answer is after taking a break for a couple of hours, 
however, I didn't know about:

> ...
> self.check_button = Button(
> master,
> text="Check",
> command=self.check_2_2  # note there's no () -- the bound
> method # is not invoked
> )
> ...
> 

My working method uses the () but I will remove them and see what difference it 
makes.

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


Re: [Tutor] Tkinter class question - solved

2017-04-08 Thread Phil
On Sat, 8 Apr 2017 02:00:38 +1000

This is one of those times where I wish I could delete a sent message.

After a bit more thought I now realise that I just need to use self to 
reference e[][] in my check function.

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


Re: [Tutor] Tkinter class question - refinement

2017-04-07 Thread Phil
On Sat, 8 Apr 2017 02:00:38 +1000
Phil <phil_...@bigpond.com> wrote:

If I define "e" lists before the class then everything works as I had expected, 
however, I don't that's technically correct. Or is it?

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


[Tutor] Tkinter class question

2017-04-07 Thread Phil
Thank you for reading this.

I've progressed a little further but I'm now having a problem knowing when to 
use the "self" reference. In the following code, the function "ckeck" is called 
without the need to press the "check" button. This didn't occur before I 
sprinkled "selfs" into the code and added "array" to the "ckeck" function. I 
found that I needed "self" to point "array" to my list array "e" and I think 
that is where the fault is. 

from tkinter import *

class TestGUI:
def __init__(self, master):
self.master = master
master.title("Testing")

num_rows = 6
num_cols = 3

self.e = [[None] * num_cols for _ in range(num_rows)]

for i in range(num_rows):
for j in range(num_cols):
self.e[i][j] = Entry(master, width=4, justify=CENTER, 
foreground="gray")
self.e[i][j].grid(row=i, column=j)
self.e[i][j].insert(0,"6")

self.check_button = Button(master, text="Check", 
command=self.check(self.e))
self.check_button.grid(row=7, column=7)

def check(self, array):
    print("checked")
array[2][2].insert(0, "4")

root = Tk()
my_gui = TestGUI(root)
root.mainloop()


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


Re: [Tutor] Tkinter grid question

2017-04-07 Thread Phil
On Fri, 07 Apr 2017 10:01:21 +0200
Peter Otten <__pete...@web.de> wrote:

> > e = [None] * 6 , [None] * 2
> 
> In the above line you are creating a 2-tuple consisting of two lists:
> 
> >>> [None]*6, [None]*2
> ([None, None, None, None, None, None], [None, None])
> 
> What you want is a list of lists
> [
> [None, None],
> [None, None],
> ...
> ]
> 
> You can create such a list with
> 
> >>> [[None] * 2 for _ in range(6)]
> [[None, None], [None, None], [None, None], [None, None], [None,
> None], [None, None]]
> 

Thank you Peter, that makes sense.

What I'm trying to do is convert a sudoku solver that I wrote using C++ and the 
QT library in 2005. As well as coming to grips with Tkinter I'm having trouble 
following my C++ code.

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


Re: [Tutor] Tkinter grid question

2017-04-07 Thread Phil
On Fri, 7 Apr 2017 10:08:40 +0100
Alan Gauld via Tutor <tutor@python.org> wrote:

> Peter has already answered the problem but I'd like
> to point out how he used the interactive prompt >>> to
> demonstrate what was going wrong.

Thank you Alan. The >>> prompt, print() and Duckduckgo do get a good workout. 
In this case I become confused because had expected [][] to be the same as a C 
two dimensional array.

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


[Tutor] Tkinter grid question

2017-04-07 Thread Phil
Thank you for reading this.

This is my first attempt at using Tkinter and I've quickly run into a problem.

If e is a one dimensional list then all is OK and I can delete and insert 
entries. The problem comes about when the list is made two dimensional, as 
follows:

from tkinter import *

master = Tk()

e = [None] * 6 , [None] * 2

for i in range(6):
for j in range(2):
e[i][j] = Entry(master, width=5)
e[i][j].grid(row=i, column=j)
e[i][j].insert(0,"6")

mainloop( )

Traceback (most recent call last):
  File "/home/pi/tkinter_example.py", line 50, in 
e[i][j] = Entry(master, width=5)
IndexError: tuple index out of range

I can see that the problem occurs when i is greater than 1 which makes me think 
that my method of attempting to create a two denominational array of edit boxes 
is wrong.

I've search for an example but haven't turned up anything. Where had I failed?

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


Re: [Tutor] UDP client

2017-02-27 Thread Phil

On 26/02/17 19:41, Peter Otten wrote:


Try

buf.decode("utf-8")


Thank you once again Peter.

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


Re: [Tutor] UDP client

2017-02-26 Thread Phil

On 26/02/17 18:42, Alan Gauld via Tutor wrote:

On 26/02/17 06:44, Phil wrote:


s.connect((host, 1210))
data = "GET_LIST"


This is a string, you need to use bytes.

data = bytes("GET_LIST",'utf8')



Thank you Peter and Alan for your response.

Converting "data" to bytes worked, of course. Now I have to, I think, do 
the opposite to the received data.


while 1:
buf = s.recv(2048)
if not len(buf):
break
print("Received: %s" % buf)

This prints the correct result like this:

b'ABC\DEF\ETC\n' n/

Instead of:

ABC
DEF
ETC

I tried str.decode(buf) but doesn't seem to be the answer.

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


[Tutor] UDP client

2017-02-25 Thread Phil

Thank you for reading this.

As an exercise, and for no other purpose, I'm trying to convert some C++ 
code that I put together 17 years ago. I'm very rusty and hours of 
Internet searches have made me more confused that I was to start with.


The following works under Python2 but not under Python3.

import socket

host = "127.0.0.1"
#host = "localhost"

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

s.connect((host, 1210))

data = "GET_LIST"

s.sendall(data)

#s.sendto(data, (host, 1210))

s.shutdown(1)

while 1:
buf = s.recv(2048)
if not len(buf):
break
#print "Received: %s" % buf

According to the Python3 wiki sendto() should work under Python3 but I 
get this error:


Traceback (most recent call last):
  File "/home/phil/Python/predict_client1.py", line 12, in 
s.sendall(data)
TypeError: a bytes-like object is required, not 'str'

The same error is received if I use sendall(data).

So, is this reasonable UDP client code and what have I overlooked to get 
this to work under Python3?


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


Re: [Tutor] Basic telnet question

2016-09-24 Thread Phil

On 25/09/16 01:01, David Rock wrote:



On Sep 24, 2016, at 04:21, Phil <phil_...@bigpond.com> wrote:

The problem is that the client is not responding, certainly not as expected. 
There aren't any Python errors either, however, the console is blocked until 
the client is disabled. If I then attempt a connection with the disabled client 
a Python connection refused error is displayed, as I would expect.

I have read the telnetlib document and searched for examples but I seem to be 
stuck on a very basic problem.

By the way, I'm using Python 3.5 under Linux.


when you say "the client is not responding, certainly not as expected”, what, 
exactly, is the output you get?



In my dazed state I think I responded to David personally instead of the 
list, my apologies.


Thank you for your reply David.

This is what I expect:

Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

But, as I say, the console is blocked and nothing is returned.

I'll try the debug method that you suggested.



read_all is a bit touchy, and it’s a blocking operation. the blocking part is 
likely why the console is blocked.  read_all doesn’t know it should give things 
back to you just because you don’t see any new data; it’s still trying to read 
everything until it times out.

either add a short timeout value to your telnetlib.Telnet(), or try a different 
read method; for example, read_very_eager

you could also try using telnetlib.set_debuglevel() to try and get more details 
about what’s actually happening.



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


Re: [Tutor] Basic telnet question

2016-09-24 Thread Phil

On 24/09/16 21:03, Joaquin Alzola wrote:



$ telnet localhost 7356



The client then responds with:



Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.


Why not use the socket module?


I did try the socket module, Joaquin but it didn't seem to be leading 
anywhere plus the telnetlib module seemed to be a more logical choice. 
Is there some advantage to using the socket module?


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


[Tutor] Basic telnet question

2016-09-24 Thread Phil

Thank you for reading this.

If I enter the following at the prompt:

$ telnet localhost 7356

The client then responds with:

Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

I'd like to do the same from Python. My code is as follows:

import telnetlib

tn = telnetlib.Telnet("127.0.0.1", 7356)
print(tn.read_all())

Then, once a connection is established send the character "f"

tn.write("f" + "\n")
print(tn.read_all())

The problem is that the client is not responding, certainly not as 
expected. There aren't any Python errors either, however, the console is 
blocked until the client is disabled. If I then attempt a connection 
with the disabled client a Python connection refused error is displayed, 
as I would expect.


I have read the telnetlib document and searched for examples but I seem 
to be stuck on a very basic problem.


By the way, I'm using Python 3.5 under Linux.

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


[Tutor] Python 3 - bugs or installation problem

2015-03-04 Thread Phil
I hope this is not another embarrassingly obvious answer to a simple 
question.


Python 3, under Kubuntu.

xrange() fails whereas range() is accepted. Could this be an 
installation problem?


phil@Asus:~/Python$ python3
Python 3.4.2 (default, Oct  8 2014, 13:18:07)
[GCC 4.9.1] on linux
Type help, copyright, credits or license for more information.
 for row in xrange(0,12):
... print(row)
...
Traceback (most recent call last):
  File stdin, line 1, in module
NameError: name 'xrange' is not defined


Under IDLE 3:

for row in xrange(0,12):
print('test ',row)

xrange() is accepted but prints the following:

('test ', 0)
('test ', 1)
('test ', 2)
('test ', 3)
('test ', 4)

Whereas it should be printed as:

test 0
test 1
etc

Could this be another Python 3 installation problem, this time with print()?

Under the Python 3 interpreter using range() and not xrange() the 
printout is correct.


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


Re: [Tutor] List of ints

2015-03-03 Thread Phil

On 03/03/15 17:46, Mark Lawrence wrote:


You are trying to increment the first element of count which is itself a
list containing one element.  You actually need:-

count[0][0] +=1



Thank you Lawrence, Alan, and Danny,

The solution is embarrassingly obvious. It's been a long time since I've 
attempted any programming and I'd even forgotten that I needed a nested 
loop to access the cells in a two-dimensional array, or list. In this 
case I didn't need a two-dimensional array anyway.


I'd been away from home for five weeks and during a quiet period I 
installed QPython on my tablet with the aim of porting a programme that 
I'd written in C++ 15 years ago to Python. Cutting and pasting and even 
moving around the IDE turned out to be a truly frustrating exercise.


I wonder if it was just my clumsiness or if others have had the same 
experience?


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


[Tutor] List of ints

2015-03-02 Thread Phil

Thank you for reading this.
Python 3 under Linux.

I'd like to set up a two dimensional list of counters as follows;

count = [
[0],
[0],
[0]
]

And then increment the first counter as follows;

count [0] += 1

This fails with the following error;

TypeError: 'int' object is not iterable

The array module looks like the answer because it seems to function in 
the same way as an array under C. However, it seems to me that I should 
be able to do the same thing with a list.


Is there a way to add a value to a list of ints?

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


[Tutor] webservice question

2015-01-29 Thread Phil H
 Looking for a little help.  I'm working on a little project and think using 
python would be the best way to do it.  I am a novice but have read a few 
beginners books.  Well to not waste everyones time i'll just get to it.  I'm 
looking to use web services to get and post data from a server with a java rest 
interface
 
This is what I have been given from the Java end
Java method
public java.lang.String getSettings (java.lang.String username, 
java.lang.String pass, java.lang.String key, java.lang.string tag)
 
url example http://localhost:8080/gettag/tag(retrieve a tag from a DB)
 
i'm told it should return something like this
?xml version=1.0 encoding=UTF-8 ? gettag responsetag [tag''s value] 
/tag /response /gettag 
 
So for what is working
 

import urllib2
import requests

url = 'http://localhost:8080/gettag/testconnection'
response = urllib2.urlopen(url) .read()

print response
--
 
with this I get the expected response from the server
 
then I have a test to authenticate user and pass
 
url = 'http://localhost:8080/gettag/testauth?username=testuserpass=123456'
 
and this works
 
This is where I get confused, how do I pass the variable key's value and return 
the variable tag's value.
 
 
Thanks in advance for any help, I've tried a bunch of stuff and its just not 
working.
 
Phil
 
 
 
 
 
 
 
 
 
 

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


[Tutor] Allocation of serial ports

2013-11-29 Thread Phil

Thank you for reading this.

This question is not specifically related to Python, however, someone 
may be able to point me in the right direction. The operating system in 
use is Linux.


I have a twin USB to serial adaptor that gives me ttyUSB0 and ttyUSB1 
and my programme uses both of those ports. The problem is the random 
allocation of the ports. Port A, for example, could be either ttyUSB0 or 
ttyUSB1.


So, how can I ensure that port A is always ttyUSB0 or how can I adapt my 
programme so that the address of the port is known to the programme?



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


Re: [Tutor] Allocation of serial ports

2013-11-29 Thread Phil

On 11/29/2013 06:17 PM, Dominik George wrote:

Hi,


So, how can I ensure that port A is always ttyUSB0


http://hintshop.ludvig.co.nz/show/persistent-names-usb-serial-devices/



Thank you Dominik, the link answers my question exactly.

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


Re: [Tutor] Retrieving data from a web site

2013-05-20 Thread Phil

On 20/05/13 17:55, Peter Otten wrote:


I've rerun the script and it still works over here. I'm in Germany, though,
and therefore there's a small chance that I'm being served different data.
What does

import urllib2



Thank you Peter for your detailed reply, I now have a better 
understanding of how json works.


I discovered my error just before receiving your reply. I'm a little 
embarrassed to admit that despite giving you the correct url I had 
attempted to get the results from another tatts page.


Thank you again, your help is greatly appreciated.

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


Re: [Tutor] Retrieving data from a web site

2013-05-19 Thread Phil
My apatite having been whetted I'm now stymied because of a Ubuntu 
dependency problem during the installation of urllib3. This is listed as 
a bug. Has anyone overcome this problem?


Perhaps there's another library that I can use to download data from a 
web page?


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


Re: [Tutor] Retrieving data from a web site

2013-05-19 Thread Phil

On 19/05/13 18:05, Peter Otten wrote:

Phil wrote:


My apatite having been whetted I'm now stymied because of a Ubuntu
dependency problem during the installation of urllib3. This is listed as
a bug. Has anyone overcome this problem?

Perhaps there's another library that I can use to download data from a
web page?


You mean you are using Python 3? The replacement for urllib2 in Python 3 is
urllib.request and a few others. There is a tool called 2to3 that can help
you with the transition.



Thank you once again Peter for a very helpful reply.

Under Ubuntu (I'm actually using Kubuntu) the packages are 
python-urllib3 (for python 2) and python3-urllib3. Unfortunately neither 
will install because of a dependency issue with libbz2-1.0. So I'll have 
to put this project on hold until the bug is resolved.


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


Re: [Tutor] Retrieving data from a web site

2013-05-19 Thread Phil

On 19/05/13 21:46, Dave Angel wrote:


Have you simply tried using urlib.request ?  That should be built into
Python 3.3 without any outside packages from Kubuntu.  (I haven't used
Kubuntu, just making some bald assumptions)

Thanks Dave,

Thanks Dave,

The urllib.request package has the same dependency problem. I haven't 
checked to see if it's built into Python yet, it's getting a bit late 
here. A job for tomorrow.


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


Re: [Tutor] Retrieving data from a web site

2013-05-19 Thread Phil

On 19/05/13 18:05, Peter Otten wrote:


The original Python 2 code:

  $ cat parse.py
import urllib2
import json

url = http://*/goldencasket;
s = urllib2.urlopen(url).read()

s = s.partition(latestResults_productResults)[2].lstrip( =)
s = s.partition(;)[0]
data = json.loads(s)
lotto = data[GoldLottoSaturday]
print lotto[drawDayDateNumber]
print map(int, lotto[primaryNumbers])
print map(int, lotto[secondaryNumbers])
$ python parse.py
Sat 18/May/13, Draw 3321
[14, 31, 16, 25, 6, 3]
[9, 35]



It turns out that urllib2 and 3 are both built into python so I didn't 
have to stress over the dependency error. However, I do have an error 
and I'm not completely certain that I understand how the code provided 
by Peter works. The following is the error message:


Traceback (most recent call last):
  File /home/phil/Python/lotto.py, line 10, in module
data = json.loads(s)
  File /usr/lib/python2.7/json/__init__.py, line 338, in loads
return _default_decoder.decode(s)
  File /usr/lib/python2.7/json/decoder.py, line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File /usr/lib/python2.7/json/decoder.py, line 383, in raw_decode
raise ValueError(No JSON object could be decoded)
ValueError: No JSON object could be decoded

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


Re: [Tutor] Retrieving data from a web site

2013-05-18 Thread Phil

On 18/05/13 16:33, Alan Gauld wrote:

On 18/05/13 00:57, Phil wrote:

I'd like to download eight digits from a web site where the digits are
stored as individual graphics. Is this possible, using perhaps, one of
the countless number of Python modules? Is this the function of a web
scraper?


In addition to Dave's points there is also the legality to consider.
Images are often copyrighted (although images of digits are less
likely!) and sites often have conditions of use that prohibit web
scraping. Such sites often include scripts that analyze user activity
and if they suspect you of being a robot may ban your computer from
accessing the site - including by browser.

So be sure that you  are allowed to access the site robotically and that
you are allowed to download the content or you could find yourself
blacklisted and unable to access the site even with your browser.



Thanks for the replies,

The site in question is the Lotto results page and the drawn numbers are 
not obscured. So I don't expect that there would be any legal or 
copyright problems.


I have written a simple program that checks the results, for an unlikely 
win, but I have to manually enter the drawn numbers. I thought the next 
step might be to automatically download the results.


I can see that this would be a relatively easy task if the digits were 
not displayed as graphics.


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


Re: [Tutor] Retrieving data from a web site

2013-05-18 Thread Phil

On 18/05/13 19:25, Peter Otten wrote:


What's the url of the page?


http://tatts.com/goldencasket


Are there alternatives that give the number as plain text?


Not that I can find. A Google search hasn't turned up anything.


If not, do the images have names like whatever0.jpg, whatever1.jpg,
whatever2.jpg, ...? Then you could infer the value from the name.

If not, is a digit always represented by the same image? Then you could map
the image urls to the digits.


Good point Peter, I'll investigate.

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


Re: [Tutor] Retrieving data from a web site

2013-05-18 Thread Phil

On 18/05/13 19:25, Peter Otten wrote:


Are there alternatives that give the number as plain text?


Further investigation shows that the numbers are available if I view the 
source of the page. So, all I have to do is parse the page and extract 
the drawn numbers. I'm not sure, at the moment, how I might do that but 
I have something to work with.


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


Re: [Tutor] Retrieving data from a web site

2013-05-18 Thread Phil

On 18/05/13 22:44, Peter Otten wrote:

You can use a tool like lxml that understands html (though in this case
you'd need a javascript parser on top of that) -- or hack something together
with string methods or regular expressions. For example:

import urllib2
import json

s = urllib2.urlopen(http://*/goldencasket;).read()
s = s.partition(latestResults_productResults)[2].lstrip( =)
s = s.partition(;)[0]
data = json.loads(s)
lotto = data[GoldLottoSaturday]

print lotto[drawDayDateNumber]
print map(int, lotto[primaryNumbers])
print map(int, lotto[secondaryNumbers])

While this is brittle I've found that doing it right is usually not
worthwhile as it won't survive the next website redesign eighter.

PS: http://*/goldencasket/results/download-results
has links to zipped csv files with the results. Downloading, inflating and
reading these should be the simplest and best way to get your data.


Thanks again Peter and Walter,

The results download link points to a historical file of past results 
although the latest results are included at the bottom of the file. The 
file is quite large and it's zipped so I imagine unzipping would another 
problem. I've come across Beautiful Soup and it may also offer a simple 
solution.


Thanks for your response Walter, I'd like to download the Australian 
Lotto results and there isn't a simple way, as far as I can see, to do 
this. I'll read up on curl, maybe I can use it.


I'll experiment with the Peter's code and Beautiful Soup and see what I 
can come up with. Maybe unzipping the file could be the best solution, 
I'll experiment with that option as well.


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


[Tutor] Retrieving data from a web site

2013-05-17 Thread Phil
I'd like to download eight digits from a web site where the digits are 
stored as individual graphics. Is this possible, using perhaps, one of 
the countless number of Python modules? Is this the function of a web 
scraper?


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


[Tutor] Classes in multiple files

2013-04-03 Thread Phil

Thank you for reading this.

The recent question relating to classes has prompted to ask this one.

I have a main window class and a dialog class and they are defined in 
separate files. I'm attempting to display the dialog when a menu item is 
selected in the main window but it doesn't work because, I think, the 
main window class isn't aware of the dialog class in another file.


This is the beginning of the main window class;

class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent = None):

And this is the beginning of the dialog class;

class SatelliteListDialog(QDialog, Ui_Dialog):
def __init__(self, parent = None):

If this was C++ then I'd need to include a class header and so I'm 
thinking that an import statement is needed in the main window class 
referring to the dialog class. Import SatelliteListDialog isn't correct.


There are many on-line examples that deal with displaying dialogs, 
however, both classes are in the same file rather that being separated.


No doubt, this is a trivial question but, as yet, I have not found an 
answer.


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


Re: [Tutor] Classes in multiple files - code included

2013-04-03 Thread Phil

On 04/04/13 09:32, Alan Gauld wrote:
cut


Reme,ber that in python its the file name you need to use to import

So if SatelliteListDialog is defined in satellite.py you need

import satellite

in your main window file.
And satellite.py has to be in your library path too...


The Eric IDE must take care of the path. All I had to do was import the 
file containing the dialog class.



Then in your main window class you need to access the dialog with

self.sld = satellite.SatelliteListDialog(...)

or whatever. In other words you need the module name prefix.

If that still doesn't work post some code and any error messages.


I think I must be very close now so I'll post just the code that I think 
is relevant.


This the main window class:

from PyQt4.QtGui import QMainWindow
from PyQt4.QtCore import pyqtSignature

from Ui_mainwindow import Ui_MainWindow

from PyQt4 import QtGui

import satListDialog

class MainWindow(QMainWindow, Ui_MainWindow):

This is the function to show the dialog;

def on_actionList_triggered(self):

self.dialog = Ui_satListDialog.SatelliteListDialog()
self.dialog.show()

Finally, this is the dialog class;

from PyQt4.QtGui import QDialog
from PyQt4.QtCore import pyqtSignature

from Ui_satListDialog import Ui_Dialog

class SatelliteListDialog(QDialog, Ui_Dialog):

And this is the error message;

global name 'Ui_satListDialog' is not defined

I have tried just about every conceivable combination in the 
on_actionList_triggered(self) function but I still end up with a not 
defined error.


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


Re: [Tutor] Classes in multiple files - code included

2013-04-03 Thread Phil

On 04/04/13 11:58, Steven D'Aprano wrote:

On 04/04/13 12:47, Phil wrote:


And this is the error message;

global name 'Ui_satListDialog' is not defined


On its own, that is almost useless.

Python gives you more debugging information than that: it gives you a
complete traceback, which includes the actual line of code causing the
problem. We don't even know which file gives the error, let alone which
line of code!

When you try to run the program, you will get an error. Please copy and
paste the *complete* traceback, starting with the line Traceback (most
recent call last) all the way to the bottom. It will show you which
file contains the error, what type of error it is, and which line fails.



Thank you for your reply Steven,

As useless as the error message may be it's the only one given.

phil@Asus:~/Eric/Pest$ python pest.py
Traceback (most recent call last):
  File /home/phil/Eric/Pest/ui/mainwindow.py, line 57, in 
on_actionList_triggered

dialog = Ui_satListDialog.SatelliteListDialog(self)
NameError: global name 'Ui_satListDialog' is not defined
^CTraceback (most recent call last):
  File pest.py, line 9, in module
sys.exit(app.exec_())

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


Re: [Tutor] pyqt4 set horizontal header item - solved

2013-04-01 Thread Phil

On 01/04/13 19:47, eryksun wrote:

On Sun, Mar 31, 2013 at 8:13 PM, Phil phil_...@bigpond.com wrote:


I have the answer (provided by a member of another list) and I was correct,
it was something basic.

from PyQt4 import QtGui
QtGui.QTable etc


Sorry, I assumed you were familiar with the package layout.

http://pyqt.sourceforge.net/Docs/PyQt4/qtablewidgetitem.html

Notice the subtitle that says [QtGui module].

http://pyqt.sourceforge.net/Docs/PyQt4/classes.html
http://pyqt.sourceforge.net/Docs/PyQt4/qtgui.html
http://pyqt.sourceforge.net/Docs/PyQt4/qtcore.html
http://pyqt.sourceforge.net/Docs/PyQt4/qt.html


Thanks for the links Eryksun, it's all now starting to make sense.

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


[Tutor] pyqt4 set horizontal header item

2013-03-31 Thread Phil

Thank you for reading this.

I want to set a table widget header based on its cell contents.

The following sets all of the headers;

self.tableWidget.setHorizontalHeaderLabels([One, Two, Etc])

However, self.setHorizontalHeaderItem ( 1, [test]) and 
self.setHorizontalHeaderItem ( 1, test) fail with the following error;


'MainWindow' object has no attribute 'setHorizontalHeaderItem'

setHorizontalHeaderItem() exists in the documentation so I must be using 
it incorrectly. I've played with this for quite some time and searched 
the Internet for an answer. Can anyone offer a suggestion?


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


Re: [Tutor] pyqt4 set horizontal header item - extra info

2013-03-31 Thread Phil

On 31/03/13 14:29, Phil wrote:

Thank you for reading this.

I want to set a table widget header based on its cell contents.

The following sets all of the headers;

self.tableWidget.setHorizontalHeaderLabels([One, Two, Etc])

However, self.setHorizontalHeaderItem ( 1, [test]) and
self.setHorizontalHeaderItem ( 1, test) fail with the following error;

'MainWindow' object has no attribute 'setHorizontalHeaderItem'

setHorizontalHeaderItem() exists in the documentation so I must be using
it incorrectly. I've played with this for quite some time and searched
the Internet for an answer. Can anyone offer a suggestion?



I now realise the correct syntax is;

self.tableWidget.setHorizontalHeaderItem (1, QTableWidgetItem *item)

I have done this many years ago in C++ but I don't quite see how to get 
a QTableWidgetItem in Python.


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


Re: [Tutor] pyqt4 set horizontal header item - extra info

2013-03-31 Thread Phil

On 31/03/13 21:43, eryksun wrote:
cut



You can use setHorizontalHeaderItem(0, QTableWidgetItem('col 0'), and
so on. It may be simpler to use setHorizontalHeaderLabels(['col 0',
'col 1', 'etc']).



Thanks Eryksun,

I had already tried your suggestion last night and this is the result;

global name 'QTableWidgetItem' is not defined

You are correct, I can easily set all of the labels at once but only one 
label needs to be modified according to it's cell contents. I'm sure I'm 
missing something very basic.


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


Re: [Tutor] pyqt4 set horizontal header item - solved

2013-03-31 Thread Phil

On 31/03/13 21:43, eryksun wrote:
cut


You can use setHorizontalHeaderItem(0, QTableWidgetItem('col 0'), and
so on. It may be simpler to use setHorizontalHeaderLabels(['col 0',
'col 1', 'etc']).



I have the answer (provided by a member of another list) and I was 
correct, it was something basic.


from PyQt4 import QtGui
QtGui.QTable etc

As I previously said, I had done this under C++ many years ago. The 
Python method is far simpler, especially once you know how.


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


[Tutor] Udp socket questio

2013-03-26 Thread Phil

Thank you for reading this.

I'm a bit out of my depth here. I'm attempting to set up a simple udp 
client.


The example that follows results in an error message and I'm wondering 
if I should be importing a different module. A Google search doesn't 
support that idea.


''
udp socket client
Silver Moon
'''

import socket   #for sockets
import sys  #for exit

# create dgram udp socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
except socket.error:
print 'Failed to create socket'
sys.exit()

host = 'localhost';
port = ;

while(1) :
msg = raw_input('Enter message to send : ')

try :
#Set the whole string
s.sendto(msg, (host, port))

# receive data from client (data, addr)
d = s.recvfrom(1024)
reply = d[0]
addr = d[1]

print 'Server reply : ' + reply

except socket.error, msg:
print 'Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()


Traceback (most recent call last):
  File socket2.py, line 6, in module
import socket   #for sockets
  File /home/phil/Python/socket.py, line 7, in module
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
AttributeError: 'module' object has no attribute 'AF_INET'

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


Re: [Tutor] Beep sound

2013-03-24 Thread Phil

On 24/03/13 12:18, Steven D'Aprano wrote:

On 24/03/13 10:31, Phil wrote:


Actually, I didn't think there was any need to make any guesses since
echo -e is exclusively a Linux command.


Nonsense. Not only does echo exist as a command on any Unix, including
Apple Mac OS, FreeBSD, OpenBSD, Solaris and others, it also exists on
Windows and DOS:

http://www.computerhope.com/echohlp.htm



I don't want to appear augmentative but there is no echo -e command for 
Windows. There is, however, echo without the 'e' switch.


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


Re: [Tutor] Beep sound

2013-03-24 Thread Phil

On 24/03/13 18:24, eryksun wrote:
cut


PulseAudio also suggests that you're using Linux or BSD, though I
think it does have ports for OS X and Windows.

The ossaudiodev module exists on Linux/BSD, so try something
relatively simple like outputting a square wave to /dev/dsp. Here's an
example device configuration:

 format = ossaudiodev.AFMT_U8  # unsigned 8-bit
 channels = 1
 rate = 8000  # samples/second
 strict = True

 dsp = ossaudiodev.open('/dev/dsp', 'w')
 dsp.setparameters(format, channels, rate, strict)

Say you want a 1000 Hz, 50% duty-cycle square wave. Given the rate is
8000 sample/s, that's 8 samples per cycle. In 8-bit mode, a cycle has
four bytes at the given amplitude followed by four null bytes. For a
0.5 s beep, you need 0.5 * 1000 = 500 cycles.

In general:

 amp = chr(amplitude)  # bytes([amplitude]) in 3.x
 cycles = int(duration * frequency)
 nhalf = int(0.5 * rate / frequency)
 data = (amp * nhalf + b'\x00' * nhalf) * cycles

Then just write the data. Make sure to close the device when you no
longer need it.

 dsp.write(data)
 dsp.close()

You can use threading to play the beep in the background without
blocking the main thread. To me this is simpler than juggling partial
writes in nonblock mode. However, you can't access the device
concurrently. Instead you could make beep() a method. Then queue the
requests, to be handled sequentially by a worker thread.


Thanks Erksun for your detailed reply. I've saved your reply for a rainy 
day.


I had discovered some information about writing to the dsp device since 
my original post. However, my experiments have been temporarily 
curtailed by a wife who wants me to spent more time building our house 
and less time playing with the computer.


It's amazing what's available to play with these days.

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


Re: [Tutor] Beep sound

2013-03-24 Thread Phil

On 25/03/13 04:30, xDog Walker wrote:
cut


Maybe something here:

http://code.activestate.com/search/recipes/#q=beep


Thanks xDog, yet another sound library (pyaudio) to play with.

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


Re: [Tutor] Beep sound

2013-03-24 Thread Phil

On 25/03/13 00:27, Bod Soutar wrote:


Your on the right track, the other thing I've seen is pcspkr being
blacklisted. Look in /etc/modprobe.d/blacklist.conf for a line like
'blacklist pcspkr' if it's there, remove it then modprobe or reboot
and it should be working again.


Thanks Bodsda,

I had a brief look through the black list files a couple of days ago and 
didn't find any mention of pcspkr. I've decided to drop this and simply 
use a sound module because they provide greater scope for experimentation.


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


Re: [Tutor] Beep sound

2013-03-23 Thread Phil

On 24/03/13 03:42, Bod Soutar wrote:


On Mar 23, 2013 2:24 AM, Steven Dapos;Aprano st...@pearwood.info
mailto:st...@pearwood.info wrote:
 
  On 23/03/13 12:48, Phil wrote:
 
  Just out of curiosity how can a beep sound be generated?
 
  My interest in this came about because echo -e '\a' no longer works.
Also print '\a' doesn't work, presumably for the same reason. The
following is also mute:
 
  import Tkinter
  Tkinter.Tk().bell()
 
  Print '\a', under Idle, causes a bell icon to be displayed so it
seems that the lack of a beep is due to a system setting.
 
 
 
  Would you like us to guess what system you are running? Linux, Mac
OS, Windows, FreeBSD, OpenBSD, Android, something else? My guess is...
Windows XP. Am I close?
 
I'm gonna guess Ubuntu, in which case the system beep is probably
disabled system wide. Google ubuntu enable disable system beep



Thank you for your reply Bodsda,

Actually, I didn't think there was any need to make any guesses since 
echo -e is exclusively a Linux command. Anyway, I had already spent 
some time searching for an answerer and the answer given most often was 
to modprobe pcspkr. This didn't lead to a working beep.


As I said previously, I'm was only curious and it's of little 
importance. There are many methods, some more complex than others, to 
play sound files. I found that the pygame library is the easiest to use.


Thank you again for taking the time to answer.

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


[Tutor] Beep sound

2013-03-22 Thread Phil

Just out of curiosity how can a beep sound be generated?

My interest in this came about because echo -e '\a' no longer works. 
Also print '\a' doesn't work, presumably for the same reason. The 
following is also mute:


import Tkinter
Tkinter.Tk().bell()

Print '\a', under Idle, causes a bell icon to be displayed so it seems 
that the lack of a beep is due to a system setting.


A Google search has shown several methods to play .wav files, some 
easier than others. Perhaps Pulse Audio has made '\a' redundant?


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


Re: [Tutor] Dictionary get method

2013-03-20 Thread Phil

On 20/03/13 14:54, Amit Saha wrote:

Hello Phil,

On Wed, Mar 20, 2013 at 12:54 PM, Phil phil_...@bigpond.com wrote:

Thank you for reading this.

I'm working my way through a series of exercises where the author only
provides a few solutions.

The reader is asked to modify the histogram example so that it uses the get
method thereby eliminating the if and else statements. Histogram2 is my
effort.

The resulting dictionary only contains the default value provided by get
and I cannot see how the value can be incremented without an if statement.


You are almost there. Note that all you have to do is increment 1 to
the current 'value' for the key denoted by c. If you change the line
with get() to the following, it works as you want it to:

  d[c]= 1 + d.get(c, 0)

Output:

{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 1, 't': 1}

histogram2
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 1, 't': 1}

You were almost there. Good Luck.

-Amit.



Thanks Amit and Mitya,

I thought I must have been close.

I've played with C++ since the mid 90s and I'm finding Python very 
refreshing.


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


Re: [Tutor] Dictionary get method

2013-03-20 Thread Phil

On 20/03/13 15:09, Mitya Sirenef wrote:
cut



By the way, you can further simplify it by doing:

def histogram2(s):
 return {c: d.get(c,0)+1 for c in s}


That will work in python 3, in python 2 you need:

 return dict((c: d.get(c,0)+1) for c in s)



Thanks again Mitya, although I'm not sure it's a simplification at my 
present level.


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


[Tutor] Dictionary get method

2013-03-19 Thread Phil

Thank you for reading this.

I'm working my way through a series of exercises where the author only 
provides a few solutions.


The reader is asked to modify the histogram example so that it uses the 
get method thereby eliminating the if and else statements. Histogram2 is 
my effort.


The resulting dictionary only contains the default value provided by 
get and I cannot see how the value can be incremented without an if 
statement.


def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d

def histogram2(s):
d = dict()
for c in s:
d[c]= d.get(c, 0)

return d

h = histogram(brontosaurs)

print h

print

print histogram2

h = histogram2(brontosaurs)

print h

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


[Tutor] Print to file

2013-03-11 Thread Phil
The usage of print to file is much like the Arduino print to serial 
device and it's got me curious to know what the correct syntax is. 
Neither of the following is correct, but the second one seems closer to 
the mark.


 print(test, file=/home/phil/Python/words)
Traceback (most recent call last):
  File stdin, line 1, in module
AttributeError: 'str' object has no attribute 'write'

 f = open(/home/phil/Python/words, 'w')
 print(test, file=f

I've used the with statement to write and read files but print to file 
could be handy some time.


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