From phillor9 at gmail.com  Tue Feb  1 01:53:02 2022
From: phillor9 at gmail.com (Phil)
Date: Tue, 1 Feb 2022 17:53:02 +1100
Subject: [Tutor] Pygubu designer question
Message-ID: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>

I've spent most of the afternoon experimenting with Pygubu builder. I 
haven't done much with Tkinter so my knowledge is a bit thin. Pygubu 
uses a callback mechanism rather than the bind method that I'm more 
familiar with. What I'm trying to achieve is read the contents of an 
edit box when returned is pressed. I've done this in the past with 
"entry.bind('Return', on_change)" if I remember correctly.

This is taken from the file that Pygubu generates:

 ?????? self.entry1.configure(exportselection='true', relief='flat', 
takefocus=False, validate='focusout')

 ??????? self.entry1.delete('0', 'end')
 ??????? self.entry1.insert('0', _text_)
 ??????? self.entry1.place(anchor='sw', height='30', width='100', 
x='10', y='100')
 ??????? self.entry1.configure(validatecommand=self.callback)

There are other entry1 options but I think validatecommand is all that I 
need. I've searched the Internet for any clues but haven't turned up 
anything relevant.

My programme includes the following:

# define the function callbacks
def on_button1_click():
 ??? messagebox.showinfo('Message', 'You pressed me') # no problems here

def callback(self):
 ??? #print(entry1.get()) # entry1 is unknown and self.entry1 didn't 
help but that's another problem

 ??? print('here')


 ??????? # Configure callbacks
 ??????? callbacks = {
 ??????????? 'on_button1_clicked': on_button1_click,
 ??????????? 'callback' : callback # This doesn't look to be correct
 ??????? }

 ??????? builder.connect_callbacks(callbacks)

The word 'here' is printed when the programme is first run. I press the 
button so that the entry box loses focus and that's when the error 
message is displayed.

The error message is Exception in Tkinter callback
Traceback (most recent call last):
 ? File "/usr/lib/python3.9/tkinter/__init__.py", line 1892, in __call__
 ??? return self.func(*args)
TypeError: 'NoneType' object is not callable

I know that I need to read up on Tkinter but someone who may be familiar 
with callbacks and Pygubu may be able to help.

-- 
Regards,
Phil


From alan.gauld at yahoo.co.uk  Tue Feb  1 04:32:02 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 1 Feb 2022 09:32:02 +0000
Subject: [Tutor] Pygubu designer question
In-Reply-To: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
Message-ID: <staumj$169q$1@ciao.gmane.io>

On 01/02/2022 06:53, Phil wrote:
> I've spent most of the afternoon experimenting with Pygubu builder.

Caveat: I've never heard of Pygubu before let alone used it...

> uses a callback mechanism rather than the bind method that I'm more 
> familiar with. 

bind is a callback mechanism.
A callback is simply a function that gets called when an event occurs.
bind associates a callback function with an event.
pygubu must do the same somehow.

>  ??????? self.entry1.configure(validatecommand=self.callback)

The idea behind validatecommand is that you have a function which
checks that the contents of the box is valid data - for example
its numeric or looks like an email address or whatever.
But of course you could use it to process the data too.

> My programme includes the following:
> 
> # define the function callbacks
> def on_button1_click():
>  ??? messagebox.showinfo('Message', 'You pressed me') # no problems here

This is a standalone function, outside of any class(no self)

> def callback(self):
>  ??? #print(entry1.get()) # entry1 is unknown and self.entry1 didn't 

Depending where you put this iyt cxould be a method of a class (self) or
it could be a standalone function that just happens to take a parameter
called self. Its not clear which. If it in inside the class then
self.entry1 should work. If its outside the class it won't.

>  ??????? # Configure callbacks
>  ??????? callbacks = {
>  ??????????? 'on_button1_clicked': on_button1_click,
>  ??????????? 'callback' : callback # This doesn't look to be correct
>  ??????? }
> 
>  ??????? builder.connect_callbacks(callbacks)

I have no idea what this does, it is obviously a pygubu construct.
But it doesn't seem to tally with the validatecommand code above.

> The word 'here' is printed when the programme is first run. I press the 

That suggests that your callback is indeed a standalone function
rather than a method and that it is somehow being called - search
for "callback(" to see if it is being called rather than referenced.

> The error message is Exception in Tkinter callback
> Traceback (most recent call last):
>  ? File "/usr/lib/python3.9/tkinter/__init__.py", line 1892, in __call__
>  ??? return self.func(*args)
> TypeError: 'NoneType' object is not callable

I'm guesssing that somehere theres a place where you should have passed
callback but you've pased callback() Calling the function which returns
None and that has been stored as the actuall callback function. Then
when tkinter tries to call the function is hits None and you get this error.

> I know that I need to read up on Tkinter but someone who may be familiar 
> with callbacks and Pygubu may be able to help.

As I said above there is nothing special about callbacks. It's how
all Tkinter (and indeed all GUIs) function. They are just
functions that get passed into the GUI for future use. bind()
is one way of setting a callback, the widget options are another.
How pygubu does it I don;t know but somewhere under the hood
it will boil down to a bind() or widget option.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From phillor9 at gmail.com  Tue Feb  1 04:57:07 2022
From: phillor9 at gmail.com (Phil)
Date: Tue, 1 Feb 2022 20:57:07 +1100
Subject: [Tutor] Pygubu designer question
In-Reply-To: <staumj$169q$1@ciao.gmane.io>
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
 <staumj$169q$1@ciao.gmane.io>
Message-ID: <ef0b65f0-8d78-36ae-0b55-d989a6ac4612@gmail.com>


On 1/2/22 20:32, Alan Gauld via Tutor wrote:
> On 01/02/2022 06:53, Phil wrote:
>> I've spent most of the afternoon experimenting with Pygubu builder.
> Caveat: I've never heard of Pygubu before let alone used it...

Thank you Alan for your time.

I've spent a lot of time searching the Internet and there's some 
interest in Pygubu on Stack overflow and on YouTube. I have several 
Tkinter references that I'll continue to read.

-- 

Regards,
Phil


From wlfraed at ix.netcom.com  Tue Feb  1 09:58:53 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Tue, 01 Feb 2022 09:58:53 -0500
Subject: [Tutor] Pygubu designer question
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
Message-ID: <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>

On Tue, 1 Feb 2022 17:53:02 +1100, Phil <phillor9 at gmail.com> declaimed the
following:

>I've spent most of the afternoon experimenting with Pygubu builder. I 
>haven't done much with Tkinter so my knowledge is a bit thin. Pygubu 
>uses a callback mechanism rather than the bind method that I'm more 
>familiar with. What I'm trying to achieve is read the contents of an 
>edit box when returned is pressed. I've done this in the past with 
>"entry.bind('Return', on_change)" if I remember correctly.
>

	Documentation of pygubu is extremely sparse -- this is the first I've
heard of it, and all I find on-line are equivalent to "Hello world". I also
don't use Tkinter so any following comments are essentially what I
understand from searches.

>This is taken from the file that Pygubu generates:

	First thing I got from searching is that the interface editor builds an
XML file describing the GUI... It might be helpful to see what /that/
contains (especially as image attachments are stripped, so the screen shots
of what you defined can not be provided without using a 3rd-party hosting
service and giving URLs).

	https://github.com/alejandroautalan/pygubu/wiki/CommandProperties is
the closest I come to information on this, and even this is an example that
doesn't require arguments, et al. to be passed.

>
> ?????? self.entry1.configure(exportselection='true', relief='flat', 
>takefocus=False, validate='focusout')
>
> ??????? self.entry1.delete('0', 'end')
> ??????? self.entry1.insert('0', _text_)
> ??????? self.entry1.place(anchor='sw', height='30', width='100', 
>x='10', y='100')
> ??????? self.entry1.configure(validatecommand=self.callback)
>
>There are other entry1 options but I think validatecommand is all that I 
>need. I've searched the Internet for any clues but haven't turned up 
>anything relevant.
>

	Referring to the linked page, what did you enter in the properties for
the widget in question? Note: the example also has a tab for "bindings",
which may also be of concern.

>My programme includes the following:
>
># define the function callbacks
>def on_button1_click():
> ??? messagebox.showinfo('Message', 'You pressed me') # no problems here
>
>def callback(self):

	"self" is probably not what is being passed -- especially as the
indentation implies this is a top-level function, and not defined as part
of some class. If "self" were being passed, it (the "self" object) would
have to have been provided to whatever operation invokes the callback in
the first place.

> ??? #print(entry1.get()) # entry1 is unknown and self.entry1 didn't 
>help but that's another problem
>
	Did you just try printing "self" to find out just what you really
received. Possibly it IS the entry1 object apparently created earlier...

> ??????? # Configure callbacks
> ??????? callbacks = {
> ??????????? 'on_button1_clicked': on_button1_click,
> ??????????? 'callback' : callback # This doesn't look to be correct
> ??????? }
>
> ??????? builder.connect_callbacks(callbacks)

	As I understand the limited documentation, this associates the callback
function(s) with the names defined in the XML/editor property pages. So we
are back to: what did you call the "command" (or other property) when
defining the form/widget. {Hmmm, the property editor shows a separate field
for "class_" which might be how one links to methods [and gets a "self"
parameter?] vs a top-level function}.

>
>The word 'here' is printed when the programme is first run. I press the 

	Which implies that something is defined to call "callback" upon /some/
event happening... It sounds a lot like that is taking place on the
rendering of the widgets.

>button so that the entry box loses focus and that's when the error 
>message is displayed.
>
>The error message is Exception in Tkinter callback
>Traceback (most recent call last):
> ? File "/usr/lib/python3.9/tkinter/__init__.py", line 1892, in __call__
> ??? return self.func(*args)
>TypeError: 'NoneType' object is not callable
>

	Whatever .func() is at that point is not a function... So either
somewhere in the code where a function needs to be /passed/ it was instead
called -- and returned a None which was passed... OR perhaps the XML/editor
properties defined a name for a callback, and you have not provided a
function linked to that name.

>I know that I need to read up on Tkinter but someone who may be familiar 
>with callbacks and Pygubu may be able to help.

	Callbacks are just functions that get registered to named events
associated with widgets. The GUI main loop processing receives the events
from the I/O system, matches the event name (and possibly widget) to a
table of Event:callback, and invokes the callback function -- typically
passing event specifics (widget object or arguments defined by the event
type) so the callback can act upon it.

	I do take exception to Mr. Gauld's statement that ALL GUIs function via
callbacks. While it is the norm for tk, GTK, and wX -- all of which
typically consist of one defining an "application" class and specifying
event name<>callback linkages on the form widgets, followed by creating an
instance of that call, and then calling a .run() or .mainloop() method,
there is a more basic model. The native programming on the Amiga (yes, I'm
invoking a 30 odd-year-old system) required one to code explicit dispatch
loops for windows. Said code style (in Python pseudo-code) would look
something like:

	while True:
		event = readNextEvent()
		if event.name == "something":
			somethingCallBack(event.value)
		elif event.name == "more":
			moreCallBack(event.value)
		...

	PySimpleGUI also uses a similar dispatch loop with Tkinter/GTK/wX --
masking the normal event loop style (I suspect internally there is one
callback that just queues events, so that the event read processes them in
queue order).


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From alan.gauld at yahoo.co.uk  Tue Feb  1 11:55:25 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 1 Feb 2022 16:55:25 +0000
Subject: [Tutor] Pygubu designer question
In-Reply-To: <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
 <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>
Message-ID: <stbolu$13h4$1@ciao.gmane.io>

On 01/02/2022 14:58, Dennis Lee Bieber wrote:

> 	I do take exception to Mr. Gauld's statement that ALL GUIs function via
> callbacks. 

Mea culpa!

In fact the original Win32 GUI API didn't include a callback mechanism
either, you had to write an explicit event reading loop and call the
handlers.


> While it is the norm for tk, GTK, and wX

But it is the norm for *almost* all GUI frameworks.
Not just Python ones either, Cocoa, Windows .NET, Java, ...
all use callbacks. And indeed many other frameworks also use
a callback mechanism, notably twisted for network programming
in the Python world.

But, yes its true, not all GUIS use callbacks.
I do apologize. :-)


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From phillor9 at gmail.com  Tue Feb  1 18:24:02 2022
From: phillor9 at gmail.com (Phil)
Date: Wed, 2 Feb 2022 10:24:02 +1100
Subject: [Tutor] Pygubu designer question
In-Reply-To: <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
 <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>
Message-ID: <ef70588a-b0ae-3fbf-a6e7-13bde9f6154b@gmail.com>


On 2/2/22 01:58, Dennis Lee Bieber wrote:

> Documentation of pygubu is extremely sparse -- this is the first I've
> heard of it, and all I find on-line are equivalent to "Hello world". I also
> don't use Tkinter so any following comments are essentially what I
> understand from searches.

My first Tkinter project was GUI interface for an Arduino project, that 
was several years ago and didn't like the look of the flat button 
widgets and so I moved onto wxPython. Many of the tutorials that I found 
at the time, and even now, are dated and the provided example code is 
quite complex. Even so, I managed to produce passable projects with 
wxPython.

While looking for something to past some time yesterday I decided to 
have another look at Tkinter and discovered that the button widget has a 
"raised" property and didn't look out of place after all and that's when 
I also discovered Pygubu. Creating a GUI with Pygubu is easy, after some 
experimentation, and integrating the .ui code into a basic project is 
also easy. However, going beyond a basic project is? problematic and 
that's what led to my vague question.

What I did find useful is the ease of investigating widget properties. 
Also, rather than use the generated code as it is, portions of it can be 
cut and then pasted into a new project and that's what I've just done. 
Pygubu could be a good learning aid.

-- 

Regards,
Phil


From wlfraed at ix.netcom.com  Wed Feb  2 01:06:54 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Wed, 02 Feb 2022 01:06:54 -0500
Subject: [Tutor] Pygubu designer question
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
 <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com> <stbolu$13h4$1@ciao.gmane.io>
Message-ID: <n16kvgthmg21iogmsiusqq0is0sgv61t1n@4ax.com>

On Tue, 1 Feb 2022 16:55:25 +0000, Alan Gauld via Tutor <tutor at python.org>
declaimed the following:

>On 01/02/2022 14:58, Dennis Lee Bieber wrote:
>
>> 	I do take exception to Mr. Gauld's statement that ALL GUIs function via
>> callbacks. 
>
>Mea culpa!
>
>In fact the original Win32 GUI API didn't include a callback mechanism
>either, you had to write an explicit event reading loop and call the
>handlers.
>

	Based upon a now quite dated book ("The Viewport Technician: A Guide to
Portable Software Design" [1988 Michael Bentley]) the original Mac OS used
an explicit polling loop; M$ Windows (1, 2, maybe 3.x) example is
(pseudo-code)

	while True:
		event = getEvent()
		translateEvent(event) #converts key events into character events
		dispatch(event)

so while the loop is explicit, the dispatch is internal "callbacks"; didn't
see an example for the Apple IIGS.

	As the subtitle indicates, the book focus is more on concerns for
writing code that is more easily ported from one system to another, and
less on the actual details of GUI/Widget code itself. {Horrors -- it even
has two whole pages on Nassi-Schneiderman charts!}

	I'm pretty certain one could write wrappers for the native GUI design
elements in which one provides an ID for each widget/event, the ID and
function (callback) get added to an internal list, and then a mainloop does
the wait for event/dispatch to function based on ID...


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From alan.gauld at yahoo.co.uk  Thu Feb  3 16:25:46 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 3 Feb 2022 21:25:46 +0000
Subject: [Tutor] Pygubu designer question
In-Reply-To: <ef70588a-b0ae-3fbf-a6e7-13bde9f6154b@gmail.com>
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
 <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>
 <ef70588a-b0ae-3fbf-a6e7-13bde9f6154b@gmail.com>
Message-ID: <sthh8q$14f2$1@ciao.gmane.io>

On 01/02/2022 23:24, Phil wrote:

> My first Tkinter project was GUI interface for an Arduino project, that 
> was several years ago and didn't like the look of the flat button 
> widgets 

If you don't like the look of the Tkinter widgets you should
definitely look into ttk which gives them a native platform
look. (In fact you can  give them any kind of look by changing
the theme!)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From phillor9 at gmail.com  Thu Feb  3 17:43:34 2022
From: phillor9 at gmail.com (Phil)
Date: Fri, 4 Feb 2022 09:43:34 +1100
Subject: [Tutor] Pygubu designer question
In-Reply-To: <sthh8q$14f2$1@ciao.gmane.io>
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
 <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>
 <ef70588a-b0ae-3fbf-a6e7-13bde9f6154b@gmail.com>
 <sthh8q$14f2$1@ciao.gmane.io>
Message-ID: <dda87678-562b-0971-31e5-b14890c29dd8@gmail.com>


On 4/2/22 08:25, Alan Gauld via Tutor wrote:
> If you don't like the look of the Tkinter widgets you should
> definitely look into ttk which gives them a native platform
> look. (In fact you can  give them any kind of look by changing
> the theme!)

Thanks Alan. I wasn't aware of ttk until I discovered Pygubu and, after 
some experimentation, I'm now quite a fan of tkinter.

-- 

Regards,
Phil


From alan.gauld at yahoo.co.uk  Thu Feb  3 20:03:37 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 4 Feb 2022 01:03:37 +0000
Subject: [Tutor] Pygubu designer question
In-Reply-To: <dda87678-562b-0971-31e5-b14890c29dd8@gmail.com>
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
 <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>
 <ef70588a-b0ae-3fbf-a6e7-13bde9f6154b@gmail.com>
 <sthh8q$14f2$1@ciao.gmane.io>
 <dda87678-562b-0971-31e5-b14890c29dd8@gmail.com>
Message-ID: <sthu19$nnq$1@ciao.gmane.io>

On 03/02/2022 22:43, Phil wrote:

>> definitely look into ttk which gives them a native platform
> 
> Thanks Alan. I wasn't aware of ttk until I discovered Pygubu and, after 
> some experimentation, I'm now quite a fan of tkinter.

ttk is neat if you care about the look - personally I don't, but I was
raised on the original X windows flat UI without colour so any kind of
look is an improvement! But the work on ttk has meant that work has
stopped on Tix which I use a lot more. Tix has a lot of extra widgets in
it and not all of them have been moved into ttk. (and quite a few are
not included in the Python port!) So personally, I'd much rather they'd
done more work on Tix and not bothered with ttk! :-(

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From phillor9 at gmail.com  Fri Feb  4 02:42:58 2022
From: phillor9 at gmail.com (Phil)
Date: Fri, 4 Feb 2022 18:42:58 +1100
Subject: [Tutor] Pygubu designer question
In-Reply-To: <sthu19$nnq$1@ciao.gmane.io>
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
 <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>
 <ef70588a-b0ae-3fbf-a6e7-13bde9f6154b@gmail.com>
 <sthh8q$14f2$1@ciao.gmane.io>
 <dda87678-562b-0971-31e5-b14890c29dd8@gmail.com> <sthu19$nnq$1@ciao.gmane.io>
Message-ID: <67d295a1-c91a-f7ee-f0f9-eb8c5c84e10a@gmail.com>


On 4/2/22 12:03, Alan Gauld via Tutor wrote:
> ttk is neat if you care about the look
I've spent most of the day playing with ttk and, although the difference 
between some of the tk and ttk widgets is subtle, I think the ttk module 
is marvellous. I'm disappointed that I've overlooked tkinter for so long.
> But the work on ttk has meant that work has
> stopped on Tix which I use a lot more.

It's a coincidence that you've mentioned tix, I just finished reading 
through https://documentation.help/Python-3.7/tkinter.tix.html. Another 
fantastic module to experiment with.

-- 

Regards,
Phil


From alan.gauld at yahoo.co.uk  Fri Feb  4 03:41:19 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 4 Feb 2022 08:41:19 +0000
Subject: [Tutor] Pygubu designer question
In-Reply-To: <67d295a1-c91a-f7ee-f0f9-eb8c5c84e10a@gmail.com>
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
 <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>
 <ef70588a-b0ae-3fbf-a6e7-13bde9f6154b@gmail.com>
 <sthh8q$14f2$1@ciao.gmane.io>
 <dda87678-562b-0971-31e5-b14890c29dd8@gmail.com> <sthu19$nnq$1@ciao.gmane.io>
 <67d295a1-c91a-f7ee-f0f9-eb8c5c84e10a@gmail.com>
Message-ID: <stiorh$q40$1@ciao.gmane.io>

On 04/02/2022 07:42, Phil wrote:
> 
> On 4/2/22 12:03, Alan Gauld via Tutor wrote:

> It's a coincidence that you've mentioned tix, I just finished reading 
> through https://documentation.help/Python-3.7/tkinter.tix.html. Another 
> fantastic module to experiment with.
> 

The problem with Tix is that it's considered obsolescent. It will
eventually die. This is a decision by the underlying Tk community
not the Python team. But it does mean that I wouldn't invest too much
time on Tix unless you find you really need some of the widgets
that it has but ttk doesn't.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From phillor9 at gmail.com  Fri Feb  4 17:13:27 2022
From: phillor9 at gmail.com (Phil)
Date: Sat, 5 Feb 2022 09:13:27 +1100
Subject: [Tutor] Pygubu designer question
In-Reply-To: <stiorh$q40$1@ciao.gmane.io>
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
 <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>
 <ef70588a-b0ae-3fbf-a6e7-13bde9f6154b@gmail.com>
 <sthh8q$14f2$1@ciao.gmane.io>
 <dda87678-562b-0971-31e5-b14890c29dd8@gmail.com> <sthu19$nnq$1@ciao.gmane.io>
 <67d295a1-c91a-f7ee-f0f9-eb8c5c84e10a@gmail.com> <stiorh$q40$1@ciao.gmane.io>
Message-ID: <3beaef04-157f-4e05-8dd2-aab57a1b9ef6@gmail.com>


On 4/2/22 19:41, Alan Gauld via Tutor wrote:
> The problem with Tix is that it's considered obsolescent.

Thank you Alan, I won't investigate tix any further.

-- 

Regards,
Phil


From phillor9 at gmail.com  Sat Feb  5 19:43:30 2022
From: phillor9 at gmail.com (Phil)
Date: Sun, 6 Feb 2022 11:43:30 +1100
Subject: [Tutor] Pygubu designer question
In-Reply-To: <CWLP265MB5473A6A4AA4586137F561D63972A9@CWLP265MB5473.GBRP265.PROD.OUTLOOK.COM>
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
 <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>
 <ef70588a-b0ae-3fbf-a6e7-13bde9f6154b@gmail.com>
 <sthh8q$14f2$1@ciao.gmane.io>
 <dda87678-562b-0971-31e5-b14890c29dd8@gmail.com> <sthu19$nnq$1@ciao.gmane.io>
 <67d295a1-c91a-f7ee-f0f9-eb8c5c84e10a@gmail.com> <stiorh$q40$1@ciao.gmane.io>
 <3beaef04-157f-4e05-8dd2-aab57a1b9ef6@gmail.com>
 <CWLP265MB5473A6A4AA4586137F561D63972A9@CWLP265MB5473.GBRP265.PROD.OUTLOOK.COM>
Message-ID: <c9cd2a14-1b56-91ab-be30-5ae357de854d@gmail.com>


On 6/2/22 03:14, Flynn, Stephen (Life & Pensions) wrote:
> Don't forget that there are some truly excellent TUI available for python - Textual for example is looks exceptionally good (https://www.youtube.com/results?search_query=textual+python) and there's Rich, by the same author.

Thanks Stephen, I'll have a look.

I've been reacquainting myself with pyfirmata this morning; there's no 
end of things to play with.

-- 

Regards,
Phil


From Steve.Flynn at capita.com  Sat Feb  5 11:14:40 2022
From: Steve.Flynn at capita.com (Flynn, Stephen (Life & Pensions))
Date: Sat, 5 Feb 2022 16:14:40 +0000
Subject: [Tutor] Pygubu designer question
In-Reply-To: <3beaef04-157f-4e05-8dd2-aab57a1b9ef6@gmail.com>
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
 <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>
 <ef70588a-b0ae-3fbf-a6e7-13bde9f6154b@gmail.com>
 <sthh8q$14f2$1@ciao.gmane.io>
 <dda87678-562b-0971-31e5-b14890c29dd8@gmail.com> <sthu19$nnq$1@ciao.gmane.io>
 <67d295a1-c91a-f7ee-f0f9-eb8c5c84e10a@gmail.com> <stiorh$q40$1@ciao.gmane.io>
 <3beaef04-157f-4e05-8dd2-aab57a1b9ef6@gmail.com>
Message-ID: <CWLP265MB5473A6A4AA4586137F561D63972A9@CWLP265MB5473.GBRP265.PROD.OUTLOOK.COM>

Don't forget that there are some truly excellent TUI available for python - Textual for example is looks exceptionally good (https://www.youtube.com/results?search_query=textual+python) and there's Rich, by the same author.

Plenty of videos showing what it's capable of with very little effort on your part.

S.

-----Original Message-----
From: Tutor <tutor-bounces+steve.flynn=capita.co.uk at python.org> On Behalf Of Phil
Sent: Friday, February 4, 2022 10:13 PM
To: tutor at python.org
Subject: Re: [Tutor] Pygubu designer question

**EXTERNAL**

On 4/2/22 19:41, Alan Gauld via Tutor wrote:
> The problem with Tix is that it's considered obsolescent.

Thank you Alan, I won't investigate tix any further.

--

Regards,
Phil

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


This message has been scanned by Capita systems, but if you believe it to be spam, please send it to spam at forcepoint.com.

Messages sent to spam at forcepoint.com are queued for email analysis by Forcepoint Threat Lab.
This email originates from outside of Capita.
Keep this in mind before responding, opening attachments or clicking any links. Unless you recognise the sender and know the content is safe.
If in any doubt, the grammar and spelling are poor, or the name doesn't match the email address then please contact the sender via an alternate known method.



This email is security checked and subject to the disclaimer on web-page: https://www.capita.com/email-disclaimer.aspx

From alan.gauld at yahoo.co.uk  Sat Feb  5 19:59:40 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 6 Feb 2022 00:59:40 +0000
Subject: [Tutor] Pygubu designer question
In-Reply-To: <c9cd2a14-1b56-91ab-be30-5ae357de854d@gmail.com>
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
 <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>
 <ef70588a-b0ae-3fbf-a6e7-13bde9f6154b@gmail.com>
 <sthh8q$14f2$1@ciao.gmane.io>
 <dda87678-562b-0971-31e5-b14890c29dd8@gmail.com> <sthu19$nnq$1@ciao.gmane.io>
 <67d295a1-c91a-f7ee-f0f9-eb8c5c84e10a@gmail.com> <stiorh$q40$1@ciao.gmane.io>
 <3beaef04-157f-4e05-8dd2-aab57a1b9ef6@gmail.com>
 <CWLP265MB5473A6A4AA4586137F561D63972A9@CWLP265MB5473.GBRP265.PROD.OUTLOOK.COM>
 <c9cd2a14-1b56-91ab-be30-5ae357de854d@gmail.com>
Message-ID: <stn6ht$q5b$1@ciao.gmane.io>

On 06/02/2022 00:43, Phil wrote:
> 
> On 6/2/22 03:14, Flynn, Stephen (Life & Pensions) wrote:
>> Don't forget that there are some truly excellent TUI available 
>>for python - Textual for example is looks exceptionally good

Very interesting and completely new to me.
Even the concept of a TUI is a new one.

I'll definitely be looking at this more closely!
Thanks for posting.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Sun Feb  6 08:54:17 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 6 Feb 2022 13:54:17 +0000
Subject: [Tutor] Rich (and Textual) was: Re: Pygubu designer question
In-Reply-To: <CWLP265MB5473A6A4AA4586137F561D63972A9@CWLP265MB5473.GBRP265.PROD.OUTLOOK.COM>
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
 <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>
 <ef70588a-b0ae-3fbf-a6e7-13bde9f6154b@gmail.com>
 <sthh8q$14f2$1@ciao.gmane.io>
 <dda87678-562b-0971-31e5-b14890c29dd8@gmail.com> <sthu19$nnq$1@ciao.gmane.io>
 <67d295a1-c91a-f7ee-f0f9-eb8c5c84e10a@gmail.com> <stiorh$q40$1@ciao.gmane.io>
 <3beaef04-157f-4e05-8dd2-aab57a1b9ef6@gmail.com>
 <CWLP265MB5473A6A4AA4586137F561D63972A9@CWLP265MB5473.GBRP265.PROD.OUTLOOK.COM>
Message-ID: <stojua$kd0$1@ciao.gmane.io>

On 05/02/2022 16:14, Flynn, Stephen (Life & Pensions) wrote:
> Don't forget that there are some truly excellent TUI available ...
> and there's Rich, by the same author.

I've just spent some time going through the rich documentation
and playing with it and I must admit I'm impressed.
In fact I really wish I'd known about rich when I wrote my
curses book because it would have gotten a mention in the
alternatives to curses section for sure.

If I was starting a new non-windowed terminal app I'm pretty
sure I'd choose rich over curses. It doesn't do anything extra
(so far as I can tell) but it does it a lot more easily and
more readably!

I'm slightly less impressed with Textual, just because it
is still in development and less polished. But it too has real
potential, one to watch. It could replace curses for
window based console apps.

Thanks again for highlighting those modules.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From marcus.luetolf at bluewin.ch  Mon Feb  7 04:21:45 2022
From: marcus.luetolf at bluewin.ch (marcus.luetolf at bluewin.ch)
Date: Mon, 7 Feb 2022 10:21:45 +0100
Subject: [Tutor] removing items from list
Message-ID: <001801d81c04$223f99b0$66becd10$@bluewin.ch>

Hello Experts,

of a list of n items at each of n iterations one other item should be
removed.

The result should yield n lists consisting of n-1 items.

Even using a copy oft he list  the indexing got mixed up.  

 

My last attempt:

 

all_items = ['item1 ','item2 ', item3 ',' item4 ', 'item5 ','item6 ',
'item7', 'item8', 'item9', 'item10 ']

 

copy_all_items = ['item1 ','item2 ', item3 ',' item4 ', 'item5 ','item6 ',
'item7', 'item8', 'item9', 'item10 ']

 

for player in all_items:

    if item in all_items:    

        c_all_items.remove(item)

        c_all_items = all_items

        print(item, c_all_items)

 

I'dappreciate to learn my mistake, thank you.


From alan.gauld at yahoo.co.uk  Mon Feb  7 05:21:08 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 7 Feb 2022 10:21:08 +0000
Subject: [Tutor] removing items from list
In-Reply-To: <001801d81c04$223f99b0$66becd10$@bluewin.ch>
References: <001801d81c04$223f99b0$66becd10$@bluewin.ch>
Message-ID: <stqrqk$15nv$1@ciao.gmane.io>

On 07/02/2022 09:21, marcus.luetolf at bluewin.ch wrote:
> Hello Experts,
> 
> of a list of n items at each of n iterations one other item should be
> removed.
> 
> The result should yield n lists consisting of n-1 items.

> all_items = ['item1 ','item2 ', item3 ',' item4 ', 'item5 ','item6 ',
> 'item7', 'item8', 'item9', 'item10 ']
> 
> copy_all_items = ['item1 ','item2 ', item3 ',' item4 ', 'item5 ','item6 ',
> 'item7', 'item8', 'item9', 'item10 ']

There's a missing quote in both lists.
Please cut n paste actual code, don't re-type it.

> 
> for player in all_items:

You never use player?

>     if item in all_items:    

You don't have anything called item

>         c_all_items.remove(item)

You don't have anything called c_all_items

>         c_all_items = all_items

But you do now...

>         print(item, c_all_items)

> I'd appreciate to learn my mistake, thank you.

When posting please always include any error messages in full.
You must have had errors trying to run that code!

However, lets try to clarify your assignment.
You just want to produce N lists of N-1 items?
It doesn't matter which item gets removed? Is that right?

If so its easier to just remove the last item N times.
Something like(untested):

new_lists = []
for n in range(len(all_items)):
    newlists.append(all_items[:])  # [:] takes a copy
    del(all_items[-1])   # the last item
print(new_lists)


You can do it even more concisely using slicing but I
don't know if you covered that yet.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From leamhall at gmail.com  Mon Feb  7 11:59:39 2022
From: leamhall at gmail.com (Leam Hall)
Date: Mon, 7 Feb 2022 10:59:39 -0600
Subject: [Tutor] Rich (and Textual) was: Re: Pygubu designer question
In-Reply-To: <stojua$kd0$1@ciao.gmane.io>
References: <f88d23cf-0776-d3e7-9b4c-10dd992f0af7@gmail.com>
 <q7givgpo188o4jl0cdl9ee6rlan6i51nub@4ax.com>
 <ef70588a-b0ae-3fbf-a6e7-13bde9f6154b@gmail.com>
 <sthh8q$14f2$1@ciao.gmane.io>
 <dda87678-562b-0971-31e5-b14890c29dd8@gmail.com> <sthu19$nnq$1@ciao.gmane.io>
 <67d295a1-c91a-f7ee-f0f9-eb8c5c84e10a@gmail.com> <stiorh$q40$1@ciao.gmane.io>
 <3beaef04-157f-4e05-8dd2-aab57a1b9ef6@gmail.com>
 <CWLP265MB5473A6A4AA4586137F561D63972A9@CWLP265MB5473.GBRP265.PROD.OUTLOOK.COM>
 <stojua$kd0$1@ciao.gmane.io>
Message-ID: <a8dbc631-58bd-7571-c061-55c70b8763d9@gmail.com>

On 2/6/22 07:54, Alan Gauld via Tutor wrote:

> If I was starting a new non-windowed terminal app I'm pretty
> sure I'd choose rich over curses. It doesn't do anything extra
> (so far as I can tell) but it does it a lot more easily and
> more readably!

Sounds like an opportunity for a new book.  :)

-- 
Site Automation Engineer   (reuel.net/resume)
Scribe: The Domici War     (domiciwar.net)
General Ne'er-do-well      (github.com/LeamHall)

From wlfraed at ix.netcom.com  Mon Feb  7 12:20:19 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Mon, 07 Feb 2022 12:20:19 -0500
Subject: [Tutor] removing items from list
References: <001801d81c04$223f99b0$66becd10$@bluewin.ch>
Message-ID: <egk20hhrl6kn99u6lehl3gmg7brjk8mt12@4ax.com>

On Mon, 7 Feb 2022 10:21:45 +0100, <marcus.luetolf at bluewin.ch> declaimed
the following:

>Hello Experts,
>
>of a list of n items at each of n iterations one other item should be
>removed.
>
>The result should yield n lists consisting of n-1 items.
>
>Even using a copy oft he list  the indexing got mixed up.  
>
> 
>
>My last attempt:
>
> 
>
>all_items = ['item1 ','item2 ', item3 ',' item4 ', 'item5 ','item6 ',
>'item7', 'item8', 'item9', 'item10 ']
>
> 
>
>copy_all_items = ['item1 ','item2 ', item3 ',' item4 ', 'item5 ','item6 ',
>'item7', 'item8', 'item9', 'item10 ']
>
> 
>
>for player in all_items:
>
>    if item in all_items:    

	Where did "item" come from? Did you mean "player"?

	This is a tautology -- since the for loop extracts one item from the
list, then by definition, that item is IN the list.

>
>        c_all_items.remove(item)

	Where did "c_all_items' come from? {I'll be kind and assume you meant
the "copy_all_items" from above}

>
>        c_all_items = all_items

	You've just replaced the list you removed an item from, with a
reference to the original (full list) list so further loop cycles will be
removing items from the full list... THAT is a major NO-NO when iterating
over a list (the list is getting shorter, but the iteration is advancing --
so you skip over entries).




>>> from itertools import combinations
>>> itemList = ["item1", "item2", "item3", "item4",
... 		"item5", "item6", "item7", "item8",
... 		"item9", "item0"]
>>> results = combinations(itemList, len(itemList) - 1)
>>> for res in results:
... 	print(res)
... 
('item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8',
'item9')
('item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8',
'item0')
('item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item9',
'item0')
('item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item8', 'item9',
'item0')
('item1', 'item2', 'item3', 'item4', 'item5', 'item7', 'item8', 'item9',
'item0')
('item1', 'item2', 'item3', 'item4', 'item6', 'item7', 'item8', 'item9',
'item0')
('item1', 'item2', 'item3', 'item5', 'item6', 'item7', 'item8', 'item9',
'item0')
('item1', 'item2', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9',
'item0')
('item1', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9',
'item0')
('item2', 'item3', 'item4', 'item5', 'item6', 'item7', 'item8', 'item9',
'item0')
>>> 


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From wlfraed at ix.netcom.com  Mon Feb  7 12:51:11 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Mon, 07 Feb 2022 12:51:11 -0500
Subject: [Tutor] removing items from list
References: <001801d81c04$223f99b0$66becd10$@bluewin.ch>
 <egk20hhrl6kn99u6lehl3gmg7brjk8mt12@4ax.com>
Message-ID: <gsl20h9de471ebqfrbkrs1nahv86djsb2e@4ax.com>


	My apologies for jumping directly to the itertools module solution...
I'm not quite awake yet. I should have rather looked for some page defining
the algorithm for computing combinations (and/or permutations). {Though I'm
finding lots for permutations, not as many for combinations...
https://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n
seems the most packed}

	And perhaps combinations is not the desired result (though with that
erroneous attempted reset of the list on each pass, combinations made more
sense than a continuously shrinking list as the latter is somewhat poorly
defined: remove from front, remove from end, remove at random?, or even
recursively do reducing combinations on each combination).


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From aj0358 at web.de  Mon Feb  7 14:53:06 2022
From: aj0358 at web.de (aj0358 at web.de)
Date: Mon, 7 Feb 2022 20:53:06 +0100
Subject: [Tutor] Speeding up my Python program
Message-ID: <trinity-51badeb3-1cdc-453e-a2df-f344d87d2812-1644263586002@3c-app-webde-bs26>

   Hi!
   ?
   I am pretty new to python, so I thought, this would be a good place to ask
   my question :)
   I am looking for a way to speed up my python program.?
   It contains a simple while-loop, a few print commands and some imports of
   the external libraries PIL and time:
   ?
   from PIL import ImageGrab
   import time
   ?
   while end_time < 1:
   ? ? start_time=time.time()
   ? ? rgb1 = ImageGrab.grab().load()[1185,561]
   ? ? rgb2 = ImageGrab.grab().load()[1260,568]
   ? ? rgb3 = ImageGrab.grab().load()[1331,571]
   ? ? print(rgb1)
   ? ? print(rgb2)
   ? ? print(rgb3)
   ? ? end_time=time.time()-start_time
   ? ? print(end_time)
   ?
   The goal is to analyse every frames of a video (60 fps) and to get the
   pixel colors of three pixels. Unfortunately, at the moment, the programm
   only analyses one frame every (about) 0.5?seconds.?
   ?
   example Output of the programm:
   (68, 30, 21)?
   (66, 22, 12)
   (129, 78, 28)? ? ? ? ? ? ? ? ? ? ? ? ? -> pixel colors of the three pixels
   0.4589216709136963? ? ? ? ? ? ? -> time it took to proceed this
   single?operation
   ?
   Now I am looking for a tool to speed up his specific program. Do You have
   any ideas which library or tool to use (I ve heard sth of cython and numpy
   but dont know how they work...)
   ?
   Thanks for your replies and best regards!
   ?
   Axel

From Ollie.ha at outlook.com  Mon Feb  7 17:05:27 2022
From: Ollie.ha at outlook.com (Oliver Haken)
Date: Mon, 7 Feb 2022 22:05:27 +0000
Subject: [Tutor] any(x)
Message-ID: <SA0PR05MB7404EF239DD2D1C5E0418B97982C9@SA0PR05MB7404.namprd05.prod.outlook.com>

I have a generator to make an infinite list of numbers


Code: Select all<https://forums.sourcepython.com/viewtopic.php?t=2663#>

 t = 0
u = []
def h ():
 while True:
  t = t + 1
  u.append(t)
  yield u
h ()


But how do I use it?


Code: Select all<https://forums.sourcepython.com/viewtopic.php?t=2663#>

 z = any(u)


Thanks, Oliver

Get Outlook for iOS<https://aka.ms/o0ukef>

From alan.gauld at yahoo.co.uk  Mon Feb  7 18:30:39 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 7 Feb 2022 23:30:39 +0000
Subject: [Tutor] Speeding up my Python program
In-Reply-To: <trinity-51badeb3-1cdc-453e-a2df-f344d87d2812-1644263586002@3c-app-webde-bs26>
References: <trinity-51badeb3-1cdc-453e-a2df-f344d87d2812-1644263586002@3c-app-webde-bs26>
Message-ID: <stsa32$127r$1@ciao.gmane.io>

On 07/02/2022 19:53, aj0358 at web.de wrote:
>    I am looking for a way to speed up my python program.?

The first thing to do is find out where the time is being spent.
Python has profiling tools but Pillow is written on C so will be very
fast so if the time is spent there you need to think about how to speed
it up.

For example you are grabbing the whole screen, it might be better to
only grab the area you need. That will reduce the work Pillow has
to do processing it.

In particular note the warning on the PixelAccess class documentation page:

"""
Accessing individual pixels is fairly slow. If you are looping over all
of the pixels in an image, there is likely a faster way using other
parts of the Pillow API.
"""

Also, do you need to call load() explicitly? If not it may be that
Pillow is calling it internally, thus doubling the work done.

>    It contains a simple while-loop, a few print commands and some imports of
>    the external libraries PIL and time:
    ?
>    from PIL import ImageGrab
>    import time
>    ?
>    while end_time < 1:

You never set end_time to an initial value, are you missing some code?

>    ? ? start_time=time.time()
>    ? ? rgb1 = ImageGrab.grab().load()[1185,561]
>    ? ? rgb2 = ImageGrab.grab().load()[1260,568]
>    ? ? rgb3 = ImageGrab.grab().load()[1331,571]
>    ? ? print(rgb1)
>    ? ? print(rgb2)
>    ? ? print(rgb3)
>    ? ? end_time=time.time()-start_time
>    ? ? print(end_time)
>    ?
>    The goal is to analyse every frames of a video (60 fps) and to get the
>    pixel colors of three pixels. Unfortunately, at the moment, the programm
>    only analyses one frame every (about) 0.5?seconds.?

You may be asking more of Pillow than it is capable of, it isn't really
designed for real-time video processing so far as I'm aware. There are
some video libraries around that may do this better, eg. cgkit might do
what you want.

Also the Blender community uses Python extensively and asking for
assistance there may throw up some other options.

>    Now I am looking for a tool to speed up his specific program. Do You have
>    any ideas which library or tool to use (I ve heard sth of cython and numpy
>    but dont know how they work...)

I doubt if that is the best route here, I'm fairly sure almost all the
time is spent in the Pillow functions and they are already written in C...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Mon Feb  7 18:37:44 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 7 Feb 2022 23:37:44 +0000
Subject: [Tutor] any(x)
In-Reply-To: <SA0PR05MB7404EF239DD2D1C5E0418B97982C9@SA0PR05MB7404.namprd05.prod.outlook.com>
References: <SA0PR05MB7404EF239DD2D1C5E0418B97982C9@SA0PR05MB7404.namprd05.prod.outlook.com>
Message-ID: <stsag9$sqh$1@ciao.gmane.io>

On 07/02/2022 22:05, Oliver Haken wrote:
> I have a generator to make an infinite list of numbers
> 
> Code: Select all<https://forums.sourcepython.com/viewtopic.php?t=2663#>
> 
>  t = 0
> u = []
> def h ():
>  while True:
>   t = t + 1
>   u.append(t)
>   yield u
> h ()
> 
> But how do I use it?

Like any function you need to use the value returned.
Although in this case you are returning the list which
is already available as a global variable.

It would be more normal for the generator to yield the
integer and then for your code to store it in the list:

def get_num():
   n = 0
   while True:
      n += 1
      yield n

u = []
for j in range(100):   # or however many numbers you need...
   u.append(get_num())

print(u)

By putting the number inside the function you don't get any
weird side-effects - like if somebody modifies t between calls?



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From wlfraed at ix.netcom.com  Mon Feb  7 21:31:36 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Mon, 07 Feb 2022 21:31:36 -0500
Subject: [Tutor] Speeding up my Python program
References: <trinity-51badeb3-1cdc-453e-a2df-f344d87d2812-1644263586002@3c-app-webde-bs26>
 <stsa32$127r$1@ciao.gmane.io>
Message-ID: <toj30h5hlqfgnpkjd22b5h03ncndv1n2a9@4ax.com>

On Mon, 7 Feb 2022 23:30:39 +0000, Alan Gauld via Tutor <tutor at python.org>
declaimed the following:

>On 07/02/2022 19:53, aj0358 at web.de wrote:
>>    I am looking for a way to speed up my python program.?

>For example you are grabbing the whole screen, it might be better to
>only grab the area you need. That will reduce the work Pillow has
>to do processing it.
>

	Which may imply passing a "bounding box" to the .grab() call.

>In particular note the warning on the PixelAccess class documentation page:
>
>"""
>Accessing individual pixels is fairly slow. If you are looping over all
>of the pixels in an image, there is likely a faster way using other
>parts of the Pillow API.
>"""
>
	Well, the OP looks to only be grabbing three specific pixels, not
looping, but...

"""
Image.getpixel(xy)
    Returns the pixel value at a given position.

    Parameters
        xy ? The coordinate, given as (x, y). See Coordinate System.

    Returns
        The pixel value. If the image is a multi-layer image, this method
returns a tuple.
"""


>Also, do you need to call load() explicitly? If not it may be that
>Pillow is calling it internally, thus doubling the work done.
>
And... the first thing the source shows for that (.getpixel()) call is: 
		self.load()
so doing an explicit .load() first is likely futile. Especially when one
looks at
"""
PIL.ImageGrab.grab(bbox=None, include_layered_windows=False,
all_screens=False, xdisplay=None)[source]?

<SNIP>
    Parameters
            bbox ? What region to copy. Default is the entire screen. Note
that on Windows OS, the top-left point may be negative if all_screens=True
is used.
<SNIP>
    Returns
        An image
"""
in conjunction with
"""
 Image.load()?

    Allocates storage for the image and loads the pixel data. In normal
cases, you don?t need to call this method, since the Image class
automatically loads an opened image when it is accessed for the first time.
"""
(under file handling)
"""
Any Pillow method that creates a new image instance based on another will
internally call load() on the original image and then read the data. The
new image instance will not be associated with the original image file.
"""

>
>>    ? ? start_time=time.time()
>>    ? ? rgb1 = ImageGrab.grab().load()[1185,561]
>>    ? ? rgb2 = ImageGrab.grab().load()[1260,568]
>>    ? ? rgb3 = ImageGrab.grab().load()[1331,571]

	I'd suggest the first optimization would be to only grab the screen
ONCE. Then access the three pixels from the single grabbed screen.

	Something like:

		scn = ImageGrab.grab()
		rgb1 = scn.getpixel((1185, 561))
		rgb2 = scn...

>>    ? ? print(rgb1)
>>    ? ? print(rgb2)
>>    ? ? print(rgb3)
>>    ? ? end_time=time.time()-start_time

	Technically, "end_time" is what time.time() returned. "duration" is
what is being computed here.

>>    ? ? print(end_time)
>>    ?
>>    The goal is to analyse every frames of a video (60 fps) and to get the
>>    pixel colors of three pixels. Unfortunately, at the moment, the programm
>>    only analyses one frame every (about) 0.5?seconds.?
>
>You may be asking more of Pillow than it is capable of, it isn't really
>designed for real-time video processing so far as I'm aware. There are
>some video libraries around that may do this better, eg. cgkit might do
>what you want.
>

	I'm pretty certain it isn't designed for real-time video processing...
Even dedicated NLEs (like the old Vegas product) don't promise realtime. As
I recall, on my computer it /previews/ video at around 20fps, and depending
upon operations being performed, can render at less than 1fps (many years
ago I was applying a trapezoidal correction to part of a video* -- a 5-10
minute video took something like 10-15 hours to process)



* the variety show at a FurCon -- my camera was set up with a fairly good
view of the stage, but they had a few segments that were shown on large
monitors to left and right; those monitors were angled such that I was
recording them as 
/____\
shaped.


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From cs at cskk.id.au  Mon Feb  7 22:57:49 2022
From: cs at cskk.id.au (Cameron Simpson)
Date: Tue, 8 Feb 2022 14:57:49 +1100
Subject: [Tutor] any(x)
In-Reply-To: <SA0PR05MB7404EF239DD2D1C5E0418B97982C9@SA0PR05MB7404.namprd05.prod.outlook.com>
References: <SA0PR05MB7404EF239DD2D1C5E0418B97982C9@SA0PR05MB7404.namprd05.prod.outlook.com>
Message-ID: <YgHqPYAaAlSOW2U/@cskk.homeip.net>

On 07Feb2022 22:05, Oliver Haken <Ollie.ha at outlook.com> wrote:
>I have a generator to make an infinite list of numbers

Hmm. Your computer must be _way_ faster than mine :-) Might be better to 
call it an unbounded sequence of numbers.

>Code: Select all<https://forums.sourcepython.com/viewtopic.php?t=2663#>
>
> t = 0
>u = []
>def h ():
> while True:
>  t = t + 1
>  u.append(t)
>  yield u
>h ()

As Alan remarked, you would not normally yield "u" (the list), you would 
yield each value of "t". The caling code might assemble those into a 
list, or otherwise process them.

So:

    def h(t=0):
      while True:
        yield t
        t += 1

which would yield numbers starting at 0 (by default) indefinitely.

Your expression "h()" does _not_ run the function. It prepares a 
generator to run the function and returns the generator. A generator is 
iterable, so you can iterate over the values it yields. For example in a 
for-loop. To make it clear:

    g = h()
    for i in g:
        print(i)

prints 0, then 1, etc. Usually you'd do that directly of course:

    for i in h():

>But how do I use it?

So here:

Your code:
> z = any(u)

you want:

    z = any(h())

since any() can use any iterable, and a generator is an iterable.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From barrettf50cal at gmail.com  Mon Feb  7 22:20:43 2022
From: barrettf50cal at gmail.com (Barrett Ferguson)
Date: Mon, 7 Feb 2022 22:20:43 -0500
Subject: [Tutor] Conditional Statement without if statement?
Message-ID: <14DB2815-AFBD-45FA-A136-78FCC8F7D9D2@gmail.com>

Hello,

 I have an assignment which asks me to create an if statement without using if, pls help. :)
I have attached the complete question

Write code that sets the value of a variable named delicious to True if jellybeans is greater than 20, or licorice is greater than 30, or their sum is greater than 40. Otherwise, set it to False. Do NOT use an if statement in your solution. Assume jellybeans and licorice already have values.

From bouncingcats at gmail.com  Tue Feb  8 05:03:26 2022
From: bouncingcats at gmail.com (David)
Date: Tue, 8 Feb 2022 21:03:26 +1100
Subject: [Tutor] Conditional Statement without if statement?
In-Reply-To: <14DB2815-AFBD-45FA-A136-78FCC8F7D9D2@gmail.com>
References: <14DB2815-AFBD-45FA-A136-78FCC8F7D9D2@gmail.com>
Message-ID: <CAMPXz=qWWU6pPrkdxGsONitd-NB6_41VrWQROoa3n=JKQTOi7Q@mail.gmail.com>

On Tue, 8 Feb 2022 at 20:42, Barrett Ferguson <barrettf50cal at gmail.com> wrote:

> Do NOT use an if statement in your solution.

Hi,

There's a syntax named "conditional expression"
which is similar to an if statement, but it is not a
statement. It is an expression (an expression is
not a statement). And it can be used for variable
assignment. Maybe that's what you're looking for.
Discussed here:
  https://realpython.com/python-conditional-statements/#conditional-expressions-pythons-ternary-operator

From lists at linguarum.net  Tue Feb  8 04:57:48 2022
From: lists at linguarum.net (Susana)
Date: Tue, 8 Feb 2022 10:57:48 +0100
Subject: [Tutor] Conditional Statement without if statement?
In-Reply-To: <14DB2815-AFBD-45FA-A136-78FCC8F7D9D2@gmail.com>
References: <14DB2815-AFBD-45FA-A136-78FCC8F7D9D2@gmail.com>
Message-ID: <20220208095748.GA23791@huginn>

Hi Barret,

you need to use combinations of relational operators (ex. >, <=, etc) and logical operators (and, or...).

Greetings.

Barrett Ferguson escreveu:
> Hello,
> 
>  I have an assignment which asks me to create an if statement without using if, pls help. :)
> I have attached the complete question
> 
> Write code that sets the value of a variable named delicious to True if jellybeans is greater than 20, or licorice is greater than 30, or their sum is greater than 40. Otherwise, set it to False. Do NOT use an if statement in your solution. Assume jellybeans and licorice already have values.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

-- 
Susana Sotelo Doc?o                                  gpg-id: 0E9BEDA4

From bouncingcats at gmail.com  Tue Feb  8 05:32:13 2022
From: bouncingcats at gmail.com (David)
Date: Tue, 8 Feb 2022 21:32:13 +1100
Subject: [Tutor] Conditional Statement without if statement?
In-Reply-To: <20220208095748.GA23791@huginn>
References: <14DB2815-AFBD-45FA-A136-78FCC8F7D9D2@gmail.com>
 <20220208095748.GA23791@huginn>
Message-ID: <CAMPXz=pSPnnKrAYk4oZNjQpY0yO=g4kj7C4CFsXyL_ja19tLgQ@mail.gmail.com>

On Tue, 8 Feb 2022 at 21:22, Susana via Tutor <tutor at python.org> wrote:

> you need to use combinations of relational operators
> (ex. >, <=, etc) and logical operators (and, or...).

Yes, I think this is more likely to be the expected answer
method, and so is a better suggestion than the one I gave
earlier.

From alan.gauld at yahoo.co.uk  Tue Feb  8 05:35:09 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 8 Feb 2022 10:35:09 +0000
Subject: [Tutor] Conditional Statement without if statement?
In-Reply-To: <14DB2815-AFBD-45FA-A136-78FCC8F7D9D2@gmail.com>
References: <14DB2815-AFBD-45FA-A136-78FCC8F7D9D2@gmail.com>
Message-ID: <stth0t$s9$1@ciao.gmane.io>

On 08/02/2022 03:20, Barrett Ferguson wrote:
> Hello,
> 
>  I have an assignment which asks me to create an if statement without using if, pls help. :)
> I have attached the complete question
> 
> Write code that sets the value of a variable named delicious to True if jellybeans is greater than 20, or licorice is greater than 30, or their sum is greater than 40. Otherwise, set it to False. Do NOT use an if statement in your solution. Assume jellybeans and licorice already have values.

I really hate it when teachers set homework that encourages
writing bad code!  What they really want you to do is use logical
operations. But they didn't want to say that because, presumably,
it was too much of a clue! So instead they create the impression that
you can/should use alternatives to the built in features of the
language! grrrrr!

But if you simply treat it as a logical operation then you can
just write it as given.

The only thing to remember after that is that Python returns
the actual values from a boolean comparison.

Thus

x = 42 or 66

x will have the value 66

To get that as a genuine boolean value (ie True or false) you
need to call bool()

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alexkleider at gmail.com  Tue Feb  8 14:14:44 2022
From: alexkleider at gmail.com (Alex Kleider)
Date: Tue, 8 Feb 2022 11:14:44 -0800
Subject: [Tutor] Conditional Statement without if statement?
In-Reply-To: <stth0t$s9$1@ciao.gmane.io>
References: <14DB2815-AFBD-45FA-A136-78FCC8F7D9D2@gmail.com>
 <stth0t$s9$1@ciao.gmane.io>
Message-ID: <CAMCEyD6THXfyJG1rsEM472wdhefMff0aVp34_QWgxs3f+ff3Ew@mail.gmail.com>

(p10) alex at X1:~/Git/Club/Guides$ python
Python 3.10.0 (default, Nov 16 2021, 13:37:55) [GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 40 or 60
>>> x
40
>>>

l

> x = 42 or 66
>
> x will have the value 66
>
> To get that as a genuine boolean value (ie True or false) you
> need to call bool()
>
>

From wlfraed at ix.netcom.com  Tue Feb  8 17:41:19 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Tue, 08 Feb 2022 17:41:19 -0500
Subject: [Tutor] Conditional Statement without if statement?
References: <14DB2815-AFBD-45FA-A136-78FCC8F7D9D2@gmail.com>
 <stth0t$s9$1@ciao.gmane.io>
 <CAMCEyD6THXfyJG1rsEM472wdhefMff0aVp34_QWgxs3f+ff3Ew@mail.gmail.com>
Message-ID: <hsr50hl6e1n2n2ou2f9o93mapftl8fh6gl@4ax.com>

On Tue, 8 Feb 2022 11:14:44 -0800, Alex Kleider <alexkleider at gmail.com>
declaimed the following:

>(p10) alex at X1:~/Git/Club/Guides$ python
>Python 3.10.0 (default, Nov 16 2021, 13:37:55) [GCC 8.3.0] on linux
>Type "help", "copyright", "credits" or "license" for more information.
>>>> x = 40 or 60
>>>> x
>40
>>>>

	The concise statement is that for a sequence of

OR		the first non-false ends the comparison and is returned
		if all are false, the last one is returned
		(false commonly being: False, 0, 0.0, (), [], "", {})

AND	the first false ends the comparison and is returned
		if all are non-false, the last is returned

>>> [] or 0 or 30 or True
30
>>> 30 and True and [] and (1, 3)
[]
>>> 
>>> [] or 0 or () or {}
{}
>>> 30 and True and [None] and (1, 3)
(1, 3)
>>> 


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From alan.gauld at yahoo.co.uk  Tue Feb  8 18:50:18 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 8 Feb 2022 23:50:18 +0000
Subject: [Tutor] Conditional Statement without if statement?
In-Reply-To: <stth0t$s9$1@ciao.gmane.io>
References: <14DB2815-AFBD-45FA-A136-78FCC8F7D9D2@gmail.com>
 <stth0t$s9$1@ciao.gmane.io>
Message-ID: <stuvjr$cmk$1@ciao.gmane.io>

On 08/02/2022 10:35, Alan Gauld via Tutor wrote:

> The only thing to remember after that is that Python returns
> the actual values from a boolean comparison.
> 
> Thus
> 
> x = 42 or 66
> 
> x will have the value 66

Oops! And that demonstrates why you shouldn't use it
as a conditional statement! :-)

I actually had a much longer answer typed out with
multiple examples from the >>> prompt but then decided
I was overcomplicating things so used this simpler but
untested example. sigh.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From nathan-tech at hotmail.com  Tue Feb  8 19:02:25 2022
From: nathan-tech at hotmail.com (Nathan Smith)
Date: Wed, 9 Feb 2022 00:02:25 +0000
Subject: [Tutor] quick function variable
Message-ID: <DB7PR07MB5093D31365AA2E994ABB54ADE42E9@DB7PR07MB5093.eurprd07.prod.outlook.com>

Hi guys,


Consider the following:

def func(name="bob", lastname="bobland", chicken="soup"):

 ?print("Hello")


if I wanted to call this function and only change the variable name I 
could do:

func(name="Jimmy")


How could I do this in variables?

EG:

variable_change="name"

value="Bob"

func(variable_change=value)


Thanks

Nathan

-- 

Best Wishes,

Nathan Smith, BSC


My Website: https://nathantech.net



From alan.gauld at yahoo.co.uk  Tue Feb  8 19:54:42 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 9 Feb 2022 00:54:42 +0000
Subject: [Tutor] quick function variable
In-Reply-To: <DB7PR07MB5093D31365AA2E994ABB54ADE42E9@DB7PR07MB5093.eurprd07.prod.outlook.com>
References: <DB7PR07MB5093D31365AA2E994ABB54ADE42E9@DB7PR07MB5093.eurprd07.prod.outlook.com>
Message-ID: <stv3ci$1361$1@ciao.gmane.io>

On 09/02/2022 00:02, Nathan Smith wrote:

> def func(name="bob", lastname="bobland", chicken="soup"):

> How could I do this in variables?
> 
> EG:
> 
> variable_change="name"
> value="Bob"
> func(variable_change=value)

I have no idea!
but I suspect if there is a way, the answer might lie in
the functools module, so that might be worthy of some study.

Just a guess!

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From manpritsinghece at gmail.com  Tue Feb  8 20:39:13 2022
From: manpritsinghece at gmail.com (Manprit Singh)
Date: Wed, 9 Feb 2022 07:09:13 +0530
Subject: [Tutor] Detect duplicate digits in a number
Message-ID: <CAO1OCwaweK8eRuEC=KwJ+Ax0CoM8SzO1-FQt4bfbK6HtKSVZmA@mail.gmail.com>

Dear Sir,

I have to produce a result False if a number contains repeating digits and
True if the number do not have any repeating digit:

Example :
if number is 2343 the result produced must be False
if number is 235 the result produced must be True

I have tried to implement it in  the following ways:
1) Using user defined function

def detect_repeat(num):
    lx = []
    while num:
        num, rem = divmod(num, 10)
        if rem  in lx:
            return False
        lx.append(rem)
    return True

ans = detect_repeat(2343)
print(ans)   # Results in False that is the desired result

2) Using str, set, len

len(set(str(2343))) == len(str(2343))
that also produces the  desired result -False

The second solution according to me lacks readability and again there are
lots of conversion str, set and all .
The  first solution, I feel , is good.

Just need your opinion and guidance . In the first solution If you can see,
there are two return statements . Is this practice considered ok ?

Regards
Manprit Singh

From joel.goldstick at gmail.com  Tue Feb  8 20:46:13 2022
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 8 Feb 2022 20:46:13 -0500
Subject: [Tutor] Detect duplicate digits in a number
In-Reply-To: <CAO1OCwaweK8eRuEC=KwJ+Ax0CoM8SzO1-FQt4bfbK6HtKSVZmA@mail.gmail.com>
References: <CAO1OCwaweK8eRuEC=KwJ+Ax0CoM8SzO1-FQt4bfbK6HtKSVZmA@mail.gmail.com>
Message-ID: <CAPM-O+xi_3pg8KeEaTnOy_rPuGVq26YpR=OodT0quSiUUhznfQ@mail.gmail.com>

On Tue, Feb 8, 2022 at 8:39 PM Manprit Singh <manpritsinghece at gmail.com> wrote:
>
> Dear Sir,
>
> I have to produce a result False if a number contains repeating digits and
> True if the number do not have any repeating digit:
>
> Example :
> if number is 2343 the result produced must be False
> if number is 235 the result produced must be True
>
> I have tried to implement it in  the following ways:
> 1) Using user defined function
>
> def detect_repeat(num):
>     lx = []
>     while num:
>         num, rem = divmod(num, 10)
>         if rem  in lx:
>             return False
>         lx.append(rem)
>     return True
>
> ans = detect_repeat(2343)
> print(ans)   # Results in False that is the desired result
>
> 2) Using str, set, len
>
> len(set(str(2343))) == len(str(2343))
> that also produces the  desired result -False
>
> The second solution according to me lacks readability and again there are
> lots of conversion str, set and all .
> The  first solution, I feel , is good.
>
> Just need your opinion and guidance . In the first solution If you can see,
> there are two return statements . Is this practice considered ok ?
>
> Regards
> Manprit Singh
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

You can convert your number to a string.  Then convert the string to a
list of characters.  Then convert the list to a set.  If the length of
the set is different than the length of the list, you have repeated
digits:

>>> n = 12341
>>> s = str(n)
>>> s
'12341'
>>> l = list(s)
>>> l
['1', '2', '3', '4', '1']
>>> s = set(l)
>>> s
{'4', '2', '3', '1'}
>>> len(s)
4
>>> len(l)
5
>>>


-- 
Joel Goldstick

From joel.goldstick at gmail.com  Tue Feb  8 20:51:27 2022
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 8 Feb 2022 20:51:27 -0500
Subject: [Tutor] Detect duplicate digits in a number
In-Reply-To: <CAPM-O+xi_3pg8KeEaTnOy_rPuGVq26YpR=OodT0quSiUUhznfQ@mail.gmail.com>
References: <CAO1OCwaweK8eRuEC=KwJ+Ax0CoM8SzO1-FQt4bfbK6HtKSVZmA@mail.gmail.com>
 <CAPM-O+xi_3pg8KeEaTnOy_rPuGVq26YpR=OodT0quSiUUhznfQ@mail.gmail.com>
Message-ID: <CAPM-O+zKAKmeTenM-03uVY5BTjB1=WdTxch97uZjt3qBXP5Maw@mail.gmail.com>

On Tue, Feb 8, 2022 at 8:46 PM Joel Goldstick <joel.goldstick at gmail.com> wrote:
>
> On Tue, Feb 8, 2022 at 8:39 PM Manprit Singh <manpritsinghece at gmail.com> wrote:
> >
> > Dear Sir,
> >
> > I have to produce a result False if a number contains repeating digits and
> > True if the number do not have any repeating digit:
> >
> > Example :
> > if number is 2343 the result produced must be False
> > if number is 235 the result produced must be True
> >
> > I have tried to implement it in  the following ways:
> > 1) Using user defined function
> >
> > def detect_repeat(num):
> >     lx = []
> >     while num:
> >         num, rem = divmod(num, 10)
> >         if rem  in lx:
> >             return False
> >         lx.append(rem)
> >     return True
> >
> > ans = detect_repeat(2343)
> > print(ans)   # Results in False that is the desired result
> >
> > 2) Using str, set, len
> >
> > len(set(str(2343))) == len(str(2343))
> > that also produces the  desired result -False
> >
> > The second solution according to me lacks readability and again there are
> > lots of conversion str, set and all .
> > The  first solution, I feel , is good.
> >
> > Just need your opinion and guidance . In the first solution If you can see,
> > there are two return statements . Is this practice considered ok ?
> >
> > Regards
> > Manprit Singh
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > https://mail.python.org/mailman/listinfo/tutor
>
> You can convert your number to a string.  Then convert the string to a
> list of characters.  Then convert the list to a set.  If the length of
> the set is different than the length of the list, you have repeated
> digits:
>
> >>> n = 12341
> >>> s = str(n)
> >>> s
> '12341'
> >>> l = list(s)
> >>> l
> ['1', '2', '3', '4', '1']
> >>> s = set(l)
> >>> s
> {'4', '2', '3', '1'}
> >>> len(s)
> 4
> >>> len(l)
> 5

> Joel Goldstick

Sorry, I was too quick to read your original post, so I offered a
solution you already know about.  I think the manipulation of the data
into different data types is more clear(to me!).  Maybe it's also more
'pythonic' in that it makes use of python features.

-- 
Joel Goldstick

From cs at cskk.id.au  Tue Feb  8 19:39:02 2022
From: cs at cskk.id.au (Cameron Simpson)
Date: Wed, 9 Feb 2022 11:39:02 +1100
Subject: [Tutor] quick function variable
In-Reply-To: <DB7PR07MB5093D31365AA2E994ABB54ADE42E9@DB7PR07MB5093.eurprd07.prod.outlook.com>
References: <DB7PR07MB5093D31365AA2E994ABB54ADE42E9@DB7PR07MB5093.eurprd07.prod.outlook.com>
Message-ID: <YgMNJhHuvXGQCYgq@cskk.homeip.net>

On 09Feb2022 00:02, nathan tech <nathan-tech at hotmail.com> wrote:
>Consider the following:
>
>    def func(name="bob", lastname="bobland", chicken="soup"):
>        print("Hello")
>
>if I wanted to call this function and only change the variable name I 
>could do:
>
>    func(name="Jimmy")
>
>How could I do this in variables?
>
>EG:
>variable_change="name"
>value="Bob"
>
>func(variable_change=value)

Keyword arguments can be unpacked from a mapping such as a dict.

    kw = {'name': 'Bob'}
    func(**kw)

Cheers,
Cameron Simpson <cs at cskk.id.au>

From alexkleider at gmail.com  Tue Feb  8 21:16:16 2022
From: alexkleider at gmail.com (Alex Kleider)
Date: Tue, 8 Feb 2022 18:16:16 -0800
Subject: [Tutor] Detect duplicate digits in a number
In-Reply-To: <CAO1OCwaweK8eRuEC=KwJ+Ax0CoM8SzO1-FQt4bfbK6HtKSVZmA@mail.gmail.com>
References: <CAO1OCwaweK8eRuEC=KwJ+Ax0CoM8SzO1-FQt4bfbK6HtKSVZmA@mail.gmail.com>
Message-ID: <CAMCEyD7bPwSE6Eig3huFbeZVfR5-Va-Zm6wd=gp0=qvXaN59Hg@mail.gmail.com>

I'd suggest using sets.
turn each number into a string:
>>> s = str(n)
# create a set of characters in the string thus eliminating duplicates:
>>> myset = {c for c in s}
>>> if len(myset) == len(s):  # if the lengths are the same- there weren't
any duplicates
           print("there are no duplicates")
       else:  # there were duplicates
          print("duplicates were present")

On Tue, Feb 8, 2022 at 5:40 PM Manprit Singh <manpritsinghece at gmail.com>
wrote:

> Dear Sir,
>
> I have to produce a result False if a number contains repeating digits and
> True if the number do not have any repeating digit:
>
> Example :
> if number is 2343 the result produced must be False
> if number is 235 the result produced must be True
>
> I have tried to implement it in  the following ways:
> 1) Using user defined function
>
> def detect_repeat(num):
>     lx = []
>     while num:
>         num, rem = divmod(num, 10)
>         if rem  in lx:
>             return False
>         lx.append(rem)
>     return True
>
> ans = detect_repeat(2343)
> print(ans)   # Results in False that is the desired result
>
> 2) Using str, set, len
>
> len(set(str(2343))) == len(str(2343))
> that also produces the  desired result -False
>
> The second solution according to me lacks readability and again there are
> lots of conversion str, set and all .
> The  first solution, I feel , is good.
>
> Just need your opinion and guidance . In the first solution If you can see,
> there are two return statements . Is this practice considered ok ?
>
> Regards
> Manprit Singh
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From nathan-tech at hotmail.com  Tue Feb  8 21:22:40 2022
From: nathan-tech at hotmail.com (Nathan Smith)
Date: Wed, 9 Feb 2022 02:22:40 +0000
Subject: [Tutor] quick function variable
In-Reply-To: <stv3ci$1361$1@ciao.gmane.io>
References: <DB7PR07MB5093D31365AA2E994ABB54ADE42E9@DB7PR07MB5093.eurprd07.prod.outlook.com>
 <stv3ci$1361$1@ciao.gmane.io>
Message-ID: <DB7PR07MB5093D73F22CD88927CB0CC87E42E9@DB7PR07MB5093.eurprd07.prod.outlook.com>

Hi!


As Cameron? mentioned the end solution was:


d={'name': 'bob'}

func(**d)


thanks a lot :)

Nathan

On 09/02/2022 00:54, Alan Gauld via Tutor wrote:
> On 09/02/2022 00:02, Nathan Smith wrote:
>
>> def func(name="bob", lastname="bobland", chicken="soup"):
>> How could I do this in variables?
>>
>> EG:
>>
>> variable_change="name"
>> value="Bob"
>> func(variable_change=value)
> I have no idea!
> but I suspect if there is a way, the answer might lie in
> the functools module, so that might be worthy of some study.
>
> Just a guess!
>
-- 

Best Wishes,

Nathan Smith, BSC


My Website: https://nathantech.net



From barrettf50cal at gmail.com  Tue Feb  8 20:17:37 2022
From: barrettf50cal at gmail.com (Barrett Ferguson)
Date: Tue, 8 Feb 2022 20:17:37 -0500
Subject: [Tutor] Conditional Statement without if statement?
In-Reply-To: <stuvjr$cmk$1@ciao.gmane.io>
References: <14DB2815-AFBD-45FA-A136-78FCC8F7D9D2@gmail.com>
 <stth0t$s9$1@ciao.gmane.io> <stuvjr$cmk$1@ciao.gmane.io>
Message-ID: <A2926690-AE77-4773-AD6D-56D48B35B644@gmail.com>

Alright guys, I went to tutoring hours and got some help to figure out the answer. Il?ll re-enter the question for reference: 
Write code that sets the value of a variable named delicious to True if jellybeans is greater than 20, or licorice is greater than 30, or their sum is greater than 40. Otherwise, set it to False. Do NOT use an if statement in your solution. Assume jellybeans and licorice already have values.

The answer is: delicious = jellybeans > 20 or licorice > 30 or jellybeans + licorice > 40

What are yalls thoughts?

> On Feb 8, 2022, at 18:50, Alan Gauld via Tutor <tutor at python.org> wrote:
> 
> On 08/02/2022 10:35, Alan Gauld via Tutor wrote:
> 
>> The only thing to remember after that is that Python returns
>> the actual values from a boolean comparison.
>> 
>> Thus
>> 
>> x = 42 or 66
>> 
>> x will have the value 66
> 
> Oops! And that demonstrates why you shouldn't use it
> as a conditional statement! :-)
> 
> I actually had a much longer answer typed out with
> multiple examples from the >>> prompt but then decided
> I was overcomplicating things so used this simpler but
> untested example. sigh.
> 
> -- 
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


From alan.gauld at yahoo.co.uk  Wed Feb  9 04:59:38 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 9 Feb 2022 09:59:38 +0000
Subject: [Tutor] quick function variable
In-Reply-To: <YgMNJhHuvXGQCYgq@cskk.homeip.net>
References: <DB7PR07MB5093D31365AA2E994ABB54ADE42E9@DB7PR07MB5093.eurprd07.prod.outlook.com>
 <YgMNJhHuvXGQCYgq@cskk.homeip.net>
Message-ID: <su03aa$s3s$1@ciao.gmane.io>

On 09/02/2022 00:39, Cameron Simpson wrote:

> Keyword arguments can be unpacked from a mapping such as a dict.
> 
>     kw = {'name': 'Bob'}
>     func(**kw)

Doh! How did I forget about that! :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Wed Feb  9 05:09:09 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 9 Feb 2022 10:09:09 +0000
Subject: [Tutor] Detect duplicate digits in a number
In-Reply-To: <CAO1OCwaweK8eRuEC=KwJ+Ax0CoM8SzO1-FQt4bfbK6HtKSVZmA@mail.gmail.com>
References: <CAO1OCwaweK8eRuEC=KwJ+Ax0CoM8SzO1-FQt4bfbK6HtKSVZmA@mail.gmail.com>
Message-ID: <su03s6$38u$1@ciao.gmane.io>

On 09/02/2022 01:39, Manprit Singh wrote:

> def detect_repeat(num):
>     lx = []
>     while num:
>         num, rem = divmod(num, 10)
>         if rem  in lx:
>             return False
>         lx.append(rem)
>     return True

I'd either rename the function to something like unique_digits()
or reverse the return values. If I saw code like

if detect_repeat(n):
    # do_something()

I'd expect do_something to be called if there were repeat
digits. You function reverses the logic implied by the name.

> len(set(str(2343))) == len(str(2343))
> that also produces the  desired result -False
> 
> The second solution according to me lacks readability and again there are
> lots of conversion str, set and all .

You can reduce the number of conversions by just doing it once:

s = str(n)
len(s) == len(set(s))

If you are concerned about performance test it. Try your function
versus the str/set test(in another function) and see which is fastest.
Your functuon is doing a lot of work so I wouldn't be surprised if
it's actually slower than the str/set approach.

> Just need your opinion and guidance . In the first solution If you can see,
> there are two return statements . Is this practice considered ok ?

Computer Science purists will say no.
Pragmatic programmers will say yes, it's very common.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Wed Feb  9 05:14:34 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 9 Feb 2022 10:14:34 +0000
Subject: [Tutor] Conditional Statement without if statement?
In-Reply-To: <A2926690-AE77-4773-AD6D-56D48B35B644@gmail.com>
References: <14DB2815-AFBD-45FA-A136-78FCC8F7D9D2@gmail.com>
 <stth0t$s9$1@ciao.gmane.io> <stuvjr$cmk$1@ciao.gmane.io>
 <A2926690-AE77-4773-AD6D-56D48B35B644@gmail.com>
Message-ID: <su046b$t3t$1@ciao.gmane.io>

On 09/02/2022 01:17, Barrett Ferguson wrote:
> Alright guys, I went to tutoring hours and got some help to figure out the answer. Il?ll re-enter the question for reference: 
> Write code that sets the value of a variable named delicious to True if jellybeans is greater than 20, or licorice is greater than 30, or their sum is greater than 40. Otherwise, set it to False. Do NOT use an if statement in your solution. Assume jellybeans and licorice already have values.
> 
> The answer is: delicious = jellybeans > 20 or licorice > 30 or jellybeans + licorice > 40
> 
> What are yalls thoughts?

The bottom line is, does it work?
Did you test it? That is, did you try all the different
combinations of values for the variables and get the
right result from your expression, both True and False.

You might also want to consider adding parentheses
just for improved readability.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From phillor9 at gmail.com  Fri Feb 11 01:35:24 2022
From: phillor9 at gmail.com (Phil)
Date: Fri, 11 Feb 2022 17:35:24 +1100
Subject: [Tutor] Tkinter and matplotlib
Message-ID: <7657be54-39fb-4faf-ac4a-5f555afe5d5d@gmail.com>

I've used matplotlib in a stand-alone fashion but now I want to use 
matplotlib on a tkinter canvas so that I can add buttons to control 
what's happening.

There are many examples to be found on the Internet; some are dated and 
use Python2 while some are overly complex. Referring to one that I found 
one that I have greatly simplified (code following) I don't understand 
exactly what the purpose of "lines = ax.plot([],[])[0]" is and where? " 
lines.set_xdata(Time) and "lines.set_ydata(data)" comes from. I only 
know that they're needed to plot something. I have checked the 
matplotlib document page and other references.

As I say, many examples seem to be dated. Is this the correct and 
current method to plot data on a tkinter canvas?

Also, I haven't seen "root.update();" used before adding buttons. 
Although I've little experience using tkinter I thought the something 
like this is the correct method:

class Root(tk.Tk):
 ??? def __init__(self):
 ??????? super().__init__()

 ??????? self.button = ttk.Button(
 ??????????? self.frame, text='Click this', command=self.button_click)

Would the following code be better worked into a class or not? I suppose 
the canvas goes onto a frame?

import time
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import tkinter as tk
import pyfirmata

data = []
Time = []
time0 = time.time()
cnt = 0

def plot_data():
 ??? global data, Time, time0, cnt

 ??? instance = time.time()
 ??? Time.append(instance-time0)

 ??? data.append(cnt)

 ??? lines.set_xdata(Time) # Is lines.set_xdata() the correct method?
 ??? lines.set_ydata(data)

 ??? canvas.draw()
 ??? cnt += 1

 ??? root.after(1000,plot_data)

def plot_start():
 ??? global cond
 ??? cond = True

def plot_stop():
 ??? global cond
 ??? cond = False


#-----Main GUI code-----
root = tk.Tk()
root.title('Real Time Plot')
root.geometry("700x500")

#------create Plot object on GUI----------
# add figure canvas
fig = Figure();
ax = fig.add_subplot(111)??? # I know what this means

ax.set_title('Serial Data');
ax.set_xlabel('Sample')
ax.set_ylabel('Voltage')
ax.set_xlim(0,100)
ax.set_ylim(0, 100)
lines = ax.plot([],[])[0]??? # I don't know this means

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().place(x = 10,y=10, width = 500,height = 400)
canvas.draw()

#----------create button---------
root.update();
start = tk.Button(root, text = "Start", font = ('calbiri',12),command = 
lambda: plot_start())
start.place(x = 100, y = 450 )

root.update();
stop = tk.Button(root, text = "Stop", font = ('calbiri',12), command = 
lambda:plot_stop())
stop.place(x = start.winfo_x()+start.winfo_reqwidth() + 20, y = 450)


root.after(1000,plot_data)
root.mainloop()

-- 

Regards,
Phil


From wlfraed at ix.netcom.com  Fri Feb 11 13:50:32 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Fri, 11 Feb 2022 13:50:32 -0500
Subject: [Tutor] Tkinter and matplotlib
References: <7657be54-39fb-4faf-ac4a-5f555afe5d5d@gmail.com>
Message-ID: <r43d0h9rquoc9oadetdb1ncdf6cjehq29i@4ax.com>

On Fri, 11 Feb 2022 17:35:24 +1100, Phil <phillor9 at gmail.com> declaimed the
following:

>
>There are many examples to be found on the Internet; some are dated and 
>use Python2 while some are overly complex. Referring to one that I found 
>one that I have greatly simplified (code following) I don't understand 
>exactly what the purpose of "lines = ax.plot([],[])[0]" is and where? " 
>lines.set_xdata(Time) and "lines.set_ydata(data)" comes from. I only 
>know that they're needed to plot something. I have checked the 
>matplotlib document page and other references.
>

	Can't help with the "lines" references but there are a multitude of
other things that jump out at me...

>Would the following code be better worked into a class or not? I suppose 
>the canvas goes onto a frame?
>

	A class for the functions would be my first choice...

>import time
>from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
>from matplotlib.figure import Figure
>import tkinter as tk
>import pyfirmata

	You aren't using pyfirmata in this example...

>
>data = []
>Time = []
>time0 = time.time()
>cnt = 0
>
>def plot_data():
> ??? global data, Time, time0, cnt

	Since you never rebind data/Time/time0 they don't need to be declared
global; you do rebind cnt. "Time" and "data" are poorly named -- especially
when you have a module "time" with function ".time()", and time0 (look at
how similar time0 and time() appear). As a class, all these could become
instance variables (self.whatever).
>
> ??? instance = time.time()
> ??? Time.append(instance-time0)
>
> ??? data.append(cnt)
>

	I'm not sure what the purpose of "data" is... you are appending a
linearly incrementing counter. Presuming this function is called on a
regular basis (so that the time values are evenly spaced) all you are
plotting is a diagonal line. 

> ??? lines.set_xdata(Time) # Is lines.set_xdata() the correct method?
> ??? lines.set_ydata(data)

	See prior: you could just pass range(len(Time)) and forget about "data"

>
> ??? canvas.draw()
> ??? cnt += 1
>
> ??? root.after(1000,plot_data)

	I would note that using a fixed "1000" (1 second?) doesn't account for
processing overhead above (nor OS overhead/process swapping -- but you
can't do anything about that without using a deterministic real-time OS) so
the collection interval won't be exactly 1 second intervals. If minimizing
jitter is desirable, you can minimize the accumulation of internal
processing overhead by computing the time delta for the next wake-up.

#initialize for first .after() call
last_time = time.time() + 1.0
... .after(... 1000, ...)

#in the loop process before .after()
#find out how much time has elapsed in processing
#NOTE: I'm not checking for overruns!
#current time minus the scheduled start of this pass
delta = time.time() - last_time
#actual wait is 1 second minus overhead time
... .after(..., int((1.0 - delta) * 1000), ...)
#set last_time to "expected" next pass start time
last_time += 1.0


>
>def plot_start():
> ??? global cond
> ??? cond = True
>
>def plot_stop():
> ??? global cond
> ??? cond = False

	These are the only places where "cond" is used, so they are currently
meaningless. Was the intention to make the accumulation function skip
adding time points? If so, you need an "if" statement in the data
collection routine to NOT accumulate the time but still reschedule the
collection routine. NOTE that with a 1 second wake-up, the granularity of
data collection will be to the nearest 1 second relative interval. You
would never see any start/stop (or stop/start) button clicks with less than
1 second between them (and maybe not even those that are less than 2
seconds)

>
>
>#-----Main GUI code-----
>root = tk.Tk()
>root.title('Real Time Plot')
>root.geometry("700x500")
>
>#------create Plot object on GUI----------
># add figure canvas
>fig = Figure();
>ax = fig.add_subplot(111)??? # I know what this means
>
>ax.set_title('Serial Data');
>ax.set_xlabel('Sample')
>ax.set_ylabel('Voltage')

	For the code you've provided, these labels are obviously meaningless
("voltage" starts at 0 and goes up by 1 each second; "sample" is the time
in seconds from start of plot).

>ax.set_xlim(0,100)
>ax.set_ylim(0, 100)

	What happens when your routine goes over 100 seconds? (and 100 time
points).

>lines = ax.plot([],[])[0]??? # I don't know this means

	What documentation have you looked at...

ax is a (sub)plot of figure, so you would need to follow documented return
values starting at matplotlib.figure to find just which .plot() is being
invoked here.

https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.plot.html#matplotlib.axes.Axes.plot
"""
 Axes.plot(*args, scalex=True, scaley=True, data=None, **kwargs)[source]
    Plot y versus x as lines and/or markers.
"""

	You are passing empty lists for X and Y, so I'd expect nothing is
plotted.

"""
Returns
    list of Line2D
        A list of lines representing the plotted data.
"""

... which you are subscripting to keep only the first "line" from the list.

https://matplotlib.org/stable/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D
"""
 set_data(*args)
    Set the x and y data.
    Parameters
        *args(2, N) array or two 1D arrays
"""
"""
set_xdata(x)
    Set the data array for x.
    Parameters
        x1D array

set_ydata(y)
    Set the data array for y.
    Parameters
        y1D array
"""

	Since you are always setting both x and y, using one call to
.set_data() would be more apropos.

FYI: the font name is "calibri" not "calbiri"!

	I have a suspicion you've simplified the actual problem to the point
where a solution as I'd write it may be irrelevant. The labels and
inclusion of pyfirmata indicates that you really want to collect data
points from an Arduino or similar. But you have your data collection tied
to your Tk frame update rate which is maybe not the same rate as that at
which the Arduino is generating it. That would mean you need to be able to
separate the accumulation of data from the display update. Assuming you get
the data on-demand, and not asynchronously...


****** COMPLETELY UNTESTED ******
import time
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import tkinter as tk
import pyfirmata


class TVplot():
    def __init__(self, tkparent):
        self.tkparent = tkparent
        self.voltages = []
        self.sampletimes = []
        self.expectedtime = None
        self.running = False

	# set up Arduino interface?

        fig = Figure()
        ax = fig.add_subplot(111)
        ax.set_title("Voltage vs Time")
        ax.set_xlabel("Time")
        ax.set_ylabel("Voltage")
        ax.set_xlim(0.0, 100.0)
        ax.set_ylim(0.0, 100.0) #uhm... what is the range you really expect

        self.line = ax.plot([], [])[0]
        self.canvas = FigureCanvaseTkAgg(self.fig, 
										master=tkparent)
        self.canvas.get_tk_widget().place(x=10, y=10, 
									width=500, 
									height=400)
        self.canvas.draw()

    def update(self):
        if self.expectedtime is None:
	      #initialize t0 and jitter correction times
            self.expectedtime = time.time()
            self.t0 = self.expectedtime
            
        if self.running:
	      #don't collect if not running
            #TBD Arduino access
            self.voltages.append(TBD)   #something
            self.sampletimes.append(time.time() - self.t0)
						#something may take time
            self.line.set_data(sampletimes, voltages)
            self.canvas.draw()

        delta = time.time() - self.expectedtime
        self.tkparent.after(int((1.0 - delta) * 1000),
                            self.update)
        self.expectedtime += 1.0
        
    def start(self):
        self.running = True

    def stop(self):
        self.running = False

#-----Main GUI code-----
root = tk.Tk()
root.title('Real Time Plot')
root.geometry("700x500")

aPlot = TVplot(root)

#----------create button---------
start = tk.Button(root, text = "Start",
                  font = ('calibri',12),
                  command = lambda: aPlot.start())
# I wonder if you need the lambda?
#                   command = aPlot.start   ) #no () on command
start.place(x = 100, y = 450 )

stop = tk.Button(root, text = "Stop",
                 font = ('calibri',12),
                 command = lambda: aPlot.stop())    #ditto
stop.place(x = start.winfo_x()+start.winfo_reqwidth() + 20, y = 450)

root.after(1000, aPlot.update)
root.mainloop()



-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From phillor9 at gmail.com  Fri Feb 11 17:36:00 2022
From: phillor9 at gmail.com (Phil)
Date: Sat, 12 Feb 2022 09:36:00 +1100
Subject: [Tutor] Tkinter and matplotlib
In-Reply-To: <r43d0h9rquoc9oadetdb1ncdf6cjehq29i@4ax.com>
References: <7657be54-39fb-4faf-ac4a-5f555afe5d5d@gmail.com>
 <r43d0h9rquoc9oadetdb1ncdf6cjehq29i@4ax.com>
Message-ID: <27cc93c7-abc1-0c34-9027-c5ab90f3502f@gmail.com>


On 12/2/22 05:50, Dennis Lee Bieber wrote:

> 	Can't help with the "lines" references but there are a multitude of
> other things that jump out at me...

Thank you Dennis for your thoughtful reply, you went far beyond what I 
had expected.

The code that I posted was a simplified version of a project that I 
found on the Internet, I simplified it even further so that I could 
provide relevance for my question. I probably should have removed 
removed even more of the original code.

I've constructed a simple capacitor / resistor oscillator using an 
Arduino board. I'm plotting two cycles of the waveform with matplotlib 
by popping the first value from the collected readings when the count 
reaches 50. This way the displayed wave doesn't compress and so more 
resembles the view normally seen on a CRO.

My default browser uses DuckDuckGo as the search engine. I also have a 
second browser that uses Google as it's search engine. Using that 
browser, after I posted my question, I came across two more examples of 
embedding a matplotlib display on a tkinter canvas. I also discovered 
better matplotlib documentation.

Thank you again.

-- 

Regards,
Phil


From wlfraed at ix.netcom.com  Fri Feb 11 19:02:27 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Fri, 11 Feb 2022 19:02:27 -0500
Subject: [Tutor] Tkinter and matplotlib
References: <7657be54-39fb-4faf-ac4a-5f555afe5d5d@gmail.com>
 <r43d0h9rquoc9oadetdb1ncdf6cjehq29i@4ax.com>
 <27cc93c7-abc1-0c34-9027-c5ab90f3502f@gmail.com>
Message-ID: <3fsd0h9kihl8b35cq0co4oldok7fup2cii@4ax.com>

On Sat, 12 Feb 2022 09:36:00 +1100, Phil <phillor9 at gmail.com> declaimed the
following:


>The code that I posted was a simplified version of a project that I 
>found on the Internet, I simplified it even further so that I could 
>provide relevance for my question. I probably should have removed 
>removed even more of the original code.

	Or left more of the original -- that incrementing "cnt" logic was
rather baffling: it would just produce a diagonal line for evenly spaced
time points; the only divergence would be if you "stop" for a few seconds
and then "start" again, as the adjacent times would now be more than a
second apart.

>
>I've constructed a simple capacitor / resistor oscillator using an 
>Arduino board. I'm plotting two cycles of the waveform with matplotlib 
>by popping the first value from the collected readings when the count 
>reaches 50. This way the displayed wave doesn't compress and so more 
>resembles the view normally seen on a CRO.

	There seem to be many examples of Python display & Arduino sampling
"oscilloscopes" out there (search terms in Google: python arduino
oscilloscope) -- but I haven't seen one using Tkinter (yet).

https://circuitdigest.com/microcontroller-projects/arduino-oscilloscope-code-circuit
uses "drawnow" library to allow for dynamic updating matplotlib

https://maker.pro/arduino/tutorial/how-to-make-a-basic-arduino-pc-oscilloscope
uses pygame library for display/control; appears to be snapshot mode
(collect readings, then display)

https://pypi.org/project/SerialScope/
pip installable package using (copied) pysimplegui (which does default to
Tkinter <G>, full pysimplegui has variants for gtk and wx if that's one's
preference). There's also something using C++ in the github sources; I
don't know if that's an addition beyond the Python or used by the Python.

	Many of these don't seem to have logic for controllable time-base --
they seem to collect the data as fast as possible, and just scale it to the
width of window. Time base may need some interaction between Python and
Arduino code (Python sending rate to Arduino which does the interval
timing).




-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From phillor9 at gmail.com  Fri Feb 11 20:10:17 2022
From: phillor9 at gmail.com (Phil)
Date: Sat, 12 Feb 2022 12:10:17 +1100
Subject: [Tutor] Tkinter and matplotlib
In-Reply-To: <3fsd0h9kihl8b35cq0co4oldok7fup2cii@4ax.com>
References: <7657be54-39fb-4faf-ac4a-5f555afe5d5d@gmail.com>
 <r43d0h9rquoc9oadetdb1ncdf6cjehq29i@4ax.com>
 <27cc93c7-abc1-0c34-9027-c5ab90f3502f@gmail.com>
 <3fsd0h9kihl8b35cq0co4oldok7fup2cii@4ax.com>
Message-ID: <7f09fd50-6dad-d9a3-c30f-bd7a2b8c44c5@gmail.com>


On 12/2/22 11:02, Dennis Lee Bieber wrote:
> On Sat, 12 Feb 2022 09:36:00 +1100, Phil <phillor9 at gmail.com> declaimed the
> following:

> 	Or left more of the original -- that incrementing "cnt" logic was
> rather baffling: it would just produce a diagonal line for evenly spaced
> time points;

It was just an illustration, that's all.

Thanks for the links. By the way, I'm not trying to simulate a CRO, it's 
just an exercise to embed matplotlib in Tkinter and then test it with 
some data.


> https://circuitdigest.com/microcontroller-projects/arduino-oscilloscope-code-circuit
> uses "drawnow" library to allow for dynamic updating matplotlib

I haven't seen that one, although I have used the drawnow library.

-- 

Regards,
Phil


From nathan-tech at hotmail.com  Fri Feb 11 21:38:58 2022
From: nathan-tech at hotmail.com (Nathan Smith)
Date: Sat, 12 Feb 2022 02:38:58 +0000
Subject: [Tutor] What am I missing here?
Message-ID: <DB7PR07MB5093BEC6E18E7E9D7306F289E4319@DB7PR07MB5093.eurprd07.prod.outlook.com>

Hi List,


I wrote a proof of concept program, it was supposed to be a more 
accessible command line for windows.

Essentially it was just supposed to be a pretty gui for command line.

To act as command line, I had:

handle=subprocess.Popen("c:\\windows\\System32\\cmd.exe", 
stderr=subprocess.PIPE, stdout=subprocess.PIPE, 
stdin=subprocess.PIPE,creationflags = subprocess.CREATE_NO_WINDOW,, 
universal_newlines=True)


Then I tthreaded while loops to read from stdout and stderr and put the 
contents into a text box, while anything entered into the other box got 
written to stdin and flushed

Such as:

line=get_line()

handle.stdin.write(line+"\n")

handle.stdin.flush()


And it works. Kind of.


Two places it does not work:

1 In command line, it always puts the current directory at the end of 
the execution of a command, eg

dir:

output

c:/users/user/documents

echo hi

hi

c:/users/user/documents


In my GUI that path does not always show, but I'm assuming that's just 
because it doesn't throw in an extra empty blank line or some such?


More to the point though, if I run python from my gui, it just doesn't 
show anything. No output, nothing. It's like it disconnects.

Am I missing something?

Even if the python command puts us into it's own command line, surely 
subprocess's stdout and stderr should capture the output?


Thanks in advance for any help..

Confused

-- 

Best Wishes,

Nathan Smith, BSC


My Website: https://nathantech.net



From nathan-tech at hotmail.com  Sat Feb 12 04:46:37 2022
From: nathan-tech at hotmail.com (Nathan Smith)
Date: Sat, 12 Feb 2022 09:46:37 +0000
Subject: [Tutor] What am I missing here?
In-Reply-To: <17eec062a12.2f1fb57d32611.469870197340030779@hvdev.cc>
References: <DB7PR07MB5093BEC6E18E7E9D7306F289E4319@DB7PR07MB5093.eurprd07.prod.outlook.com>
 <17eec062a12.2f1fb57d32611.469870197340030779@hvdev.cc>
Message-ID: <DB7PR07MB509325DB0417DB68E4866046E4319@DB7PR07MB5093.eurprd07.prod.outlook.com>

Hi there,


To be honest, I just didn't think of it, I just kind of used it by reflex.

Even changing it over to this has the same problem though:

for line in handle.stdout:

 ?process the line


Once I try and execute the python command, output just stops flowing.


Is there another pipe I should be capturing other than stdout and stderr?


Nathan

On 12/02/2022 03:42, V? Thanh H?i wrote:
> Hi Nathan,
>
> I'm just curious why are you using get_line? That might not work when some command line program requires interactive input.
>
>   >
>   > hi
>   >
>   > c:/users/user/documents
>   >
>   >
>   > In my GUI that path does not always show, but I'm assuming that's just
>   > because it doesn't throw in an extra empty blank line or some such?
>   >
>
> The path will not show itself because it is not part of STDOUT, I guess.
>
> Thanks and kind regards,
>
> Vu Thanh Hai
> Full-stack Developer
>
> -o-0_o-0-o_0-o-0_o-0-o-
> ?
> Website: https://emea01.safelinks.protection.outlook.com/?url=http%3A%2F%2Fwww.hvdev.cc%2F&amp;data=04%7C01%7C%7C6e83aefb6ab24f7382aa08d9edd9ad02%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637802341428866342%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000&amp;sdata=kd9YLMdzAT97QjLQvYvMgZj8%2B8z%2FNii%2BsUN%2BHhHSUqA%3D&amp;reserved=0
> Email: m at hvdev.cc
> Twitter: @hvhvdevdev
> GitHub: @hvhvdevdev
>
> ---- On Sat, 12 Feb 2022 09:38:58 +0700 Nathan Smith <nathan-tech at hotmail.com> wrote ----
>
>   > Hi List,
>   >
>   >
>   > I wrote a proof of concept program, it was supposed to be a more
>   > accessible command line for windows.
>   >
>   > Essentially it was just supposed to be a pretty gui for command line.
>   >
>   > To act as command line, I had:
>   >
>   > handle=subprocess.Popen("c:\\windows\\System32\\cmd.exe",
>   > stderr=subprocess.PIPE, stdout=subprocess.PIPE,
>   > stdin=subprocess.PIPE,creationflags = subprocess.CREATE_NO_WINDOW,,
>   > universal_newlines=True)
>   >
>   >
>   > Then I tthreaded while loops to read from stdout and stderr and put the
>   > contents into a text box, while anything entered into the other box got
>   > written to stdin and flushed
>   >
>   > Such as:
>   >
>   > line=get_line()
>   >
>   > handle.stdin.write(line+"\n")
>   >
>   > handle.stdin.flush()
>   >
>   >
>   > And it works. Kind of.
>   >
>   >
>   > Two places it does not work:
>   >
>   > 1 In command line, it always puts the current directory at the end of
>   > the execution of a command, eg
>   >
>   > dir:
>   >
>   > output
>   >
>   > c:/users/user/documents
>   >
>   > echo hi
>   >
>   > hi
>   >
>   > c:/users/user/documents
>   >
>   >
>   > In my GUI that path does not always show, but I'm assuming that's just
>   > because it doesn't throw in an extra empty blank line or some such?
>   >
>   >
>   > More to the point though, if I run python from my gui, it just doesn't
>   > show anything. No output, nothing. It's like it disconnects.
>   >
>   > Am I missing something?
>   >
>   > Even if the python command puts us into it's own command line, surely
>   > subprocess's stdout and stderr should capture the output?
>   >
>   >
>   > Thanks in advance for any help..
>   >
>   > Confused
>   >
>   > --
>   >
>   > Best Wishes,
>   >
>   > Nathan Smith, BSC
>   >
>   >
>   > My Website: https://emea01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fnathantech.net%2F&amp;data=04%7C01%7C%7C6e83aefb6ab24f7382aa08d9edd9ad02%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637802341428866342%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000&amp;sdata=D3r6zFeDD6x%2Bb7HuajzSOec%2B50q238wCVzzvX3O8lbA%3D&amp;reserved=0
>   >
>   >
>   > _______________________________________________
>   > Tutor maillist  - Tutor at python.org
>   > To unsubscribe or change subscription options:
>   > https://emea01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fmail.python.org%2Fmailman%2Flistinfo%2Ftutor&amp;data=04%7C01%7C%7C6e83aefb6ab24f7382aa08d9edd9ad02%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637802341428866342%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000&amp;sdata=Orjnp4fPh2fv7J9rHlf%2BUYfSATqczLdlzPLf9jVBsAY%3D&amp;reserved=0
>   >
-- 

Best Wishes,

Nathan Smith, BSC


My Website: https://nathantech.net



From m at hvdev.cc  Fri Feb 11 22:42:14 2022
From: m at hvdev.cc (=?UTF-8?Q?V=C5=A9_Thanh_H=E1=BA=A3i?=)
Date: Sat, 12 Feb 2022 10:42:14 +0700
Subject: [Tutor] What am I missing here?
In-Reply-To: <DB7PR07MB5093BEC6E18E7E9D7306F289E4319@DB7PR07MB5093.eurprd07.prod.outlook.com>
References: <DB7PR07MB5093BEC6E18E7E9D7306F289E4319@DB7PR07MB5093.eurprd07.prod.outlook.com>
Message-ID: <17eec062a12.2f1fb57d32611.469870197340030779@hvdev.cc>

Hi Nathan,

I'm just curious why are you using get_line? That might not work when some command line program requires interactive input.

 >  
 > hi 
 >  
 > c:/users/user/documents 
 >  
 >  
 > In my GUI that path does not always show, but I'm assuming that's just 
 > because it doesn't throw in an extra empty blank line or some such? 
 >  

The path will not show itself because it is not part of STDOUT, I guess.

Thanks and kind regards,

Vu Thanh Hai 
Full-stack Developer

-o-0_o-0-o_0-o-0_o-0-o-
?
Website: www.hvdev.cc
Email: m at hvdev.cc
Twitter: @hvhvdevdev
GitHub: @hvhvdevdev

---- On Sat, 12 Feb 2022 09:38:58 +0700 Nathan Smith <nathan-tech at hotmail.com> wrote ----

 > Hi List, 
 >  
 >  
 > I wrote a proof of concept program, it was supposed to be a more 
 > accessible command line for windows. 
 >  
 > Essentially it was just supposed to be a pretty gui for command line. 
 >  
 > To act as command line, I had: 
 >  
 > handle=subprocess.Popen("c:\\windows\\System32\\cmd.exe", 
 > stderr=subprocess.PIPE, stdout=subprocess.PIPE, 
 > stdin=subprocess.PIPE,creationflags = subprocess.CREATE_NO_WINDOW,, 
 > universal_newlines=True) 
 >  
 >  
 > Then I tthreaded while loops to read from stdout and stderr and put the 
 > contents into a text box, while anything entered into the other box got 
 > written to stdin and flushed 
 >  
 > Such as: 
 >  
 > line=get_line() 
 >  
 > handle.stdin.write(line+"\n") 
 >  
 > handle.stdin.flush() 
 >  
 >  
 > And it works. Kind of. 
 >  
 >  
 > Two places it does not work: 
 >  
 > 1 In command line, it always puts the current directory at the end of 
 > the execution of a command, eg 
 >  
 > dir: 
 >  
 > output 
 >  
 > c:/users/user/documents 
 >  
 > echo hi 
 >  
 > hi 
 >  
 > c:/users/user/documents 
 >  
 >  
 > In my GUI that path does not always show, but I'm assuming that's just 
 > because it doesn't throw in an extra empty blank line or some such? 
 >  
 >  
 > More to the point though, if I run python from my gui, it just doesn't 
 > show anything. No output, nothing. It's like it disconnects. 
 >  
 > Am I missing something? 
 >  
 > Even if the python command puts us into it's own command line, surely 
 > subprocess's stdout and stderr should capture the output? 
 >  
 >  
 > Thanks in advance for any help.. 
 >  
 > Confused 
 >  
 > -- 
 >  
 > Best Wishes, 
 >  
 > Nathan Smith, BSC 
 >  
 >  
 > My Website: https://nathantech.net 
 >  
 >  
 > _______________________________________________ 
 > Tutor maillist  - Tutor at python.org 
 > To unsubscribe or change subscription options: 
 > https://mail.python.org/mailman/listinfo/tutor 
 > 

From wlfraed at ix.netcom.com  Sat Feb 12 12:24:33 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Sat, 12 Feb 2022 12:24:33 -0500
Subject: [Tutor] Tkinter and matplotlib
References: <7657be54-39fb-4faf-ac4a-5f555afe5d5d@gmail.com>
 <r43d0h9rquoc9oadetdb1ncdf6cjehq29i@4ax.com>
 <27cc93c7-abc1-0c34-9027-c5ab90f3502f@gmail.com>
 <3fsd0h9kihl8b35cq0co4oldok7fup2cii@4ax.com>
 <7f09fd50-6dad-d9a3-c30f-bd7a2b8c44c5@gmail.com>
Message-ID: <6uqf0hhcus1ob9cjefebanl40ektbv195f@4ax.com>

On Sat, 12 Feb 2022 12:10:17 +1100, Phil <phillor9 at gmail.com> declaimed the
following:

>Thanks for the links. By the way, I'm not trying to simulate a CRO, it's 

	I'd refrained from asking just what you had meant by CRO... I suspected
cathode ray oscilloscope -- but earlier in the same paragraph you mention
capacitor resistor oscillator...

>just an exercise to embed matplotlib in Tkinter and then test it with 
>some data.

	Heh... I suspect I'd have pulled in the random module and rolled dice
(say a 3D6 which would tend to center around 11.5 but with excursions
possible to 3 and 18; a single die would jump too much since any of the 6
states is equally likely)

	From what I could tell, there wasn't really much involved in the
Tkinter part -- create a placeholder for the plot, then user a matplotlib
backend that understands Tkinter to fill it in...


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From wlfraed at ix.netcom.com  Sat Feb 12 12:49:38 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Sat, 12 Feb 2022 12:49:38 -0500
Subject: [Tutor] What am I missing here?
References: <DB7PR07MB5093BEC6E18E7E9D7306F289E4319@DB7PR07MB5093.eurprd07.prod.outlook.com>
Message-ID: <pbrf0h1s6aga0gaofu6vml6j10f1upnrjl@4ax.com>

On Sat, 12 Feb 2022 02:38:58 +0000, Nathan Smith <nathan-tech at hotmail.com>
declaimed the following:


>Two places it does not work:
>
>1 In command line, it always puts the current directory at the end of 
>the execution of a command, eg
>
>dir:
>
>output
>
>c:/users/user/documents
>
>echo hi
>
>hi
>
>c:/users/user/documents

	Please cut&paste the actual text. Windows command shells use \ for path
separators (the internal API doesn't care) -- and the prompt concludes with
a > marker

Microsoft Windows [Version 10.0.19041.1415]
(c) Microsoft Corporation. All rights reserved.

C:\Users\Wulfraed>echo help me
help me

C:\Users\Wulfraed>

>
>
>In my GUI that path does not always show, but I'm assuming that's just 
>because it doesn't throw in an extra empty blank line or some such?
>
	The I/O system, when not connected to a terminal/console, typically
doesn't flush the output until a new-line is emitted; it expects the next
command to be input on the same "line" -- so the prompt may not be
available on your line-oriented read operation.

>
>More to the point though, if I run python from my gui, it just doesn't 
>show anything. No output, nothing. It's like it disconnects.
>
>Am I missing something?
>
>Even if the python command puts us into it's own command line, surely 
>subprocess's stdout and stderr should capture the output?
>
	I believe it is possible for processes to "attach" to a "console" which
is the window itself, not the default shell process within it. I
hypothesize that stdin/stdout/stderr are tied to the process, not to the
console.

https://docs.microsoft.com/en-us/windows/console/attaching-to-a-console
https://docs.microsoft.com/en-us/windows/console/attachconsole
"""
This function is primarily useful to applications that were linked with
/SUBSYSTEM:WINDOWS, which implies to the operating system that a console is
not needed before entering the program's main method. In that instance, the
standard handles retrieved with GetStdHandle will likely be invalid on
startup until AttachConsole is called. The exception to this is if the
application is launched with handle inheritance by its parent process.
"""
	Yes -- normally sub-processes started from a console process do inherit
the streams... but nothing says the sub-process has to use them <G>

https://docs.microsoft.com/en-us/windows/console/allocconsole
"""
This function is primarily used by a graphical user interface (GUI)
application to create a console window. GUI applications are initialized
without a console. Console applications are initialized with a console,
unless they are created as detached processes (by calling the CreateProcess
function with the DETACHED_PROCESS flag).
"""

	Since running a "console" (*.py) script by double-clicking results in a
console window being created to display output, I suspect the interpreter
starts up in a "no console" mode, and then determines if it can attach or
needs to allocate... "GUI" (*.pyw) scripts aren't supposed to have a
console at all.


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From jf_byrnes at comcast.net  Sat Feb 12 13:06:28 2022
From: jf_byrnes at comcast.net (Jim Byrnes)
Date: Sat, 12 Feb 2022 12:06:28 -0600
Subject: [Tutor] Tkinter and matplotlib
In-Reply-To: <7f09fd50-6dad-d9a3-c30f-bd7a2b8c44c5@gmail.com>
References: <7657be54-39fb-4faf-ac4a-5f555afe5d5d@gmail.com>
 <r43d0h9rquoc9oadetdb1ncdf6cjehq29i@4ax.com>
 <27cc93c7-abc1-0c34-9027-c5ab90f3502f@gmail.com>
 <3fsd0h9kihl8b35cq0co4oldok7fup2cii@4ax.com>
 <7f09fd50-6dad-d9a3-c30f-bd7a2b8c44c5@gmail.com>
Message-ID: <su8sv4$fvp$1@ciao.gmane.io>

On 2/11/22 19:10, Phil wrote:
> 

> It was just an illustration, that's all.
> 
> Thanks for the links. By the way, I'm not trying to simulate a CRO, it's 
> just an exercise to embed matplotlib in Tkinter and then test it with 
> some data.
> 

I missed the start of this thread, so maybe I am way off base. Have you 
considered using Jupyter notebook? I just finished an on line Pandas 
course and it used Jypyter notebook. I was amazed what you could do with 
just a few lines of code. Nicely formatted tables and Matplotlib will 
display plots in Jupyter. I just signed up for a course on Jupyter 
notebooks to get more than a surface understanding of them.

Regards,  Jim


From phillor9 at gmail.com  Sat Feb 12 18:50:00 2022
From: phillor9 at gmail.com (Phil)
Date: Sun, 13 Feb 2022 10:50:00 +1100
Subject: [Tutor] Tkinter and matplotlib
In-Reply-To: <su8sv4$fvp$1@ciao.gmane.io>
References: <7657be54-39fb-4faf-ac4a-5f555afe5d5d@gmail.com>
 <r43d0h9rquoc9oadetdb1ncdf6cjehq29i@4ax.com>
 <27cc93c7-abc1-0c34-9027-c5ab90f3502f@gmail.com>
 <3fsd0h9kihl8b35cq0co4oldok7fup2cii@4ax.com>
 <7f09fd50-6dad-d9a3-c30f-bd7a2b8c44c5@gmail.com> <su8sv4$fvp$1@ciao.gmane.io>
Message-ID: <3fd7161f-227b-80c4-70fd-fa693cc0a514@gmail.com>


On 13/2/22 05:06, Jim Byrnes wrote:
>
> I missed the start of this thread, so maybe I am way off base. Have 
> you considered using Jupyter notebook?

Thanks Jim, I'm aware of Jypyter notebook but I've never used it. I'm 
looking for a new project so I'll do some investigation.

-- 

Regards,
Phil


From phillor9 at gmail.com  Sat Feb 12 18:56:09 2022
From: phillor9 at gmail.com (Phil)
Date: Sun, 13 Feb 2022 10:56:09 +1100
Subject: [Tutor] Tkinter and matplotlib
In-Reply-To: <6uqf0hhcus1ob9cjefebanl40ektbv195f@4ax.com>
References: <7657be54-39fb-4faf-ac4a-5f555afe5d5d@gmail.com>
 <r43d0h9rquoc9oadetdb1ncdf6cjehq29i@4ax.com>
 <27cc93c7-abc1-0c34-9027-c5ab90f3502f@gmail.com>
 <3fsd0h9kihl8b35cq0co4oldok7fup2cii@4ax.com>
 <7f09fd50-6dad-d9a3-c30f-bd7a2b8c44c5@gmail.com>
 <6uqf0hhcus1ob9cjefebanl40ektbv195f@4ax.com>
Message-ID: <0736b3df-a326-53b6-19ec-f8c13485dba8@gmail.com>


On 13/2/22 04:24, Dennis Lee Bieber wrote:
>   -- but earlier in the same paragraph you mention
> capacitor resistor oscillator...

I needed some continually varying data to feed matplotlib and a low 
frequency, roughly sawtooth, oscillation was just the shot.

-- 

Regards,
Phil


From nathan-tech at hotmail.com  Sat Feb 12 21:17:14 2022
From: nathan-tech at hotmail.com (Nathan Smith)
Date: Sun, 13 Feb 2022 02:17:14 +0000
Subject: [Tutor] What am I missing here?
In-Reply-To: <pbrf0h1s6aga0gaofu6vml6j10f1upnrjl@4ax.com>
References: <DB7PR07MB5093BEC6E18E7E9D7306F289E4319@DB7PR07MB5093.eurprd07.prod.outlook.com>
 <pbrf0h1s6aga0gaofu6vml6j10f1upnrjl@4ax.com>
Message-ID: <DB7PR07MB509385B79B37429144A7B1ACE4329@DB7PR07MB5093.eurprd07.prod.outlook.com>

Hi there,


Thanks for this response! In particular thanks for pointing out my logic 
error regarding the way cmd.exe expects input and how it attaches that 
to the end of the prompt line.

I switched over to winexpect and it actually did start printing the 
prompt line, but either way it's good to know so again, thanks for that.


I had a read through the links provided and admit I'm not sure if I 
understood *all* of it, though I agree with you on the point about how 
the interpreter probably handles booting up.

Interestingly, if I send commands through stdin blindly, eg from my gui 
send:

python

f=open("test.txt","w")

f.write("hi")

f.close()


Then it actually does go through, the file gets created.

the only problem is nothing gets printed to stdout or stderr, or at 
least not that the subprocess can see and thus not that the gui can see.

I'm assuming, as you mentioned, that this is because the interpreter is 
not inheriting those stdout and stderr handles from the cmd.exe?


Is there a work around for this?

The whole point of the proof of concept was to be able to provide a more 
friendly interface for python interpreter from a screen reader 
perspective, so be disappointed if I'm stuck here.


Best,

Nathan

On 12/02/2022 17:49, Dennis Lee Bieber wrote:
> On Sat, 12 Feb 2022 02:38:58 +0000, Nathan Smith <nathan-tech at hotmail.com>
> declaimed the following:
>
>
>> Two places it does not work:
>>
>> 1 In command line, it always puts the current directory at the end of
>> the execution of a command, eg
>>
>> dir:
>>
>> output
>>
>> c:/users/user/documents
>>
>> echo hi
>>
>> hi
>>
>> c:/users/user/documents
> 	Please cut&paste the actual text. Windows command shells use \ for path
> separators (the internal API doesn't care) -- and the prompt concludes with
> a > marker
>
> Microsoft Windows [Version 10.0.19041.1415]
> (c) Microsoft Corporation. All rights reserved.
>
> C:\Users\Wulfraed>echo help me
> help me
>
> C:\Users\Wulfraed>
>
>>
>> In my GUI that path does not always show, but I'm assuming that's just
>> because it doesn't throw in an extra empty blank line or some such?
>>
> 	The I/O system, when not connected to a terminal/console, typically
> doesn't flush the output until a new-line is emitted; it expects the next
> command to be input on the same "line" -- so the prompt may not be
> available on your line-oriented read operation.
>
>> More to the point though, if I run python from my gui, it just doesn't
>> show anything. No output, nothing. It's like it disconnects.
>>
>> Am I missing something?
>>
>> Even if the python command puts us into it's own command line, surely
>> subprocess's stdout and stderr should capture the output?
>>
> 	I believe it is possible for processes to "attach" to a "console" which
> is the window itself, not the default shell process within it. I
> hypothesize that stdin/stdout/stderr are tied to the process, not to the
> console.
>
> https://emea01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fconsole%2Fattaching-to-a-console&amp;data=04%7C01%7C%7C4d480ac0412c47bc861708d9ee504a23%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637802850884755366%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000&amp;sdata=S7q2xuq1uXp8U8UxEr2YaD09zzNPA304wuDPqb774Gw%3D&amp;reserved=0
> https://emea01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fconsole%2Fattachconsole&amp;data=04%7C01%7C%7C4d480ac0412c47bc861708d9ee504a23%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637802850884755366%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000&amp;sdata=TMXuQmtispog86SWNth03doh%2BMKzgIGrhlAS4oRub18%3D&amp;reserved=0
> """
> This function is primarily useful to applications that were linked with
> /SUBSYSTEM:WINDOWS, which implies to the operating system that a console is
> not needed before entering the program's main method. In that instance, the
> standard handles retrieved with GetStdHandle will likely be invalid on
> startup until AttachConsole is called. The exception to this is if the
> application is launched with handle inheritance by its parent process.
> """
> 	Yes -- normally sub-processes started from a console process do inherit
> the streams... but nothing says the sub-process has to use them <G>
>
> https://emea01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fdocs.microsoft.com%2Fen-us%2Fwindows%2Fconsole%2Fallocconsole&amp;data=04%7C01%7C%7C4d480ac0412c47bc861708d9ee504a23%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637802850884755366%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000&amp;sdata=ZcjzGw%2BJ9yp6XRWizoJYpQY0L%2FDvRPbVmUkW0Sx3N6k%3D&amp;reserved=0
> """
> This function is primarily used by a graphical user interface (GUI)
> application to create a console window. GUI applications are initialized
> without a console. Console applications are initialized with a console,
> unless they are created as detached processes (by calling the CreateProcess
> function with the DETACHED_PROCESS flag).
> """
>
> 	Since running a "console" (*.py) script by double-clicking results in a
> console window being created to display output, I suspect the interpreter
> starts up in a "no console" mode, and then determines if it can attach or
> needs to allocate... "GUI" (*.pyw) scripts aren't supposed to have a
> console at all.
>
>
-- 

Best Wishes,

Nathan Smith, BSC


My Website: https://nathantech.net



From wlfraed at ix.netcom.com  Sat Feb 12 22:05:04 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Sat, 12 Feb 2022 22:05:04 -0500
Subject: [Tutor] Tkinter and matplotlib
References: <7657be54-39fb-4faf-ac4a-5f555afe5d5d@gmail.com>
 <r43d0h9rquoc9oadetdb1ncdf6cjehq29i@4ax.com>
 <27cc93c7-abc1-0c34-9027-c5ab90f3502f@gmail.com>
 <3fsd0h9kihl8b35cq0co4oldok7fup2cii@4ax.com>
 <7f09fd50-6dad-d9a3-c30f-bd7a2b8c44c5@gmail.com>
 <6uqf0hhcus1ob9cjefebanl40ektbv195f@4ax.com>
 <0736b3df-a326-53b6-19ec-f8c13485dba8@gmail.com>
Message-ID: <p6tg0hlg5eoqp2gs8qol7ifqornu2ha7i4@4ax.com>

On Sun, 13 Feb 2022 10:56:09 +1100, Phil <phillor9 at gmail.com> declaimed the
following:

>
>On 13/2/22 04:24, Dennis Lee Bieber wrote:
>>   -- but earlier in the same paragraph you mention
>> capacitor resistor oscillator...
>
>I needed some continually varying data to feed matplotlib and a low 
>frequency, roughly sawtooth, oscillation was just the shot.

	My comment was really toward the potential confusion factor:

CRO => cathode ray oscilloscope	OR
CRO => capacitor resistor oscillator (I'm more used to seeing RC listings
in circuits)


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From phillor9 at gmail.com  Sat Feb 12 22:40:05 2022
From: phillor9 at gmail.com (Phil)
Date: Sun, 13 Feb 2022 14:40:05 +1100
Subject: [Tutor] Tkinter and matplotlib
In-Reply-To: <p6tg0hlg5eoqp2gs8qol7ifqornu2ha7i4@4ax.com>
References: <7657be54-39fb-4faf-ac4a-5f555afe5d5d@gmail.com>
 <r43d0h9rquoc9oadetdb1ncdf6cjehq29i@4ax.com>
 <27cc93c7-abc1-0c34-9027-c5ab90f3502f@gmail.com>
 <3fsd0h9kihl8b35cq0co4oldok7fup2cii@4ax.com>
 <7f09fd50-6dad-d9a3-c30f-bd7a2b8c44c5@gmail.com>
 <6uqf0hhcus1ob9cjefebanl40ektbv195f@4ax.com>
 <0736b3df-a326-53b6-19ec-f8c13485dba8@gmail.com>
 <p6tg0hlg5eoqp2gs8qol7ifqornu2ha7i4@4ax.com>
Message-ID: <aaf3d789-cfc5-5b76-da9a-e7b25ed29dc2@gmail.com>


On 13/2/22 14:05, Dennis Lee Bieber wrote:
> 	My comment was really toward the potential confusion factor:
>
> CRO => cathode ray oscilloscope	OR
> CRO => capacitor resistor oscillator (I'm more used to seeing RC listings
> in circuits)

OK, I see.

-- 

Regards,
Phil


From wlfraed at ix.netcom.com  Sat Feb 12 23:13:28 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Sat, 12 Feb 2022 23:13:28 -0500
Subject: [Tutor] What am I missing here?
References: <DB7PR07MB5093BEC6E18E7E9D7306F289E4319@DB7PR07MB5093.eurprd07.prod.outlook.com>
 <pbrf0h1s6aga0gaofu6vml6j10f1upnrjl@4ax.com>
 <DB7PR07MB509385B79B37429144A7B1ACE4329@DB7PR07MB5093.eurprd07.prod.outlook.com>
Message-ID: <ietg0h5i89ums6i9tl1icu4npfqsjl6gbq@4ax.com>

On Sun, 13 Feb 2022 02:17:14 +0000, Nathan Smith <nathan-tech at hotmail.com>
declaimed the following:

>
>I had a read through the links provided and admit I'm not sure if I 
>understood *all* of it, though I agree with you on the point about how 
>the interpreter probably handles booting up.
>
	Take into account that this was all hypothesis on my part. I've never
coded something using that level of Win32.


>I'm assuming, as you mentioned, that this is because the interpreter is 
>not inheriting those stdout and stderr handles from the cmd.exe?
>

	Again, hypothesis... One would have to study the Python start-up code
for Windows to see what it is doing with the I/O.

	If you really want to get perplexed, open a command shell and enter:

start /b python

(normally "start" will open a new console if the application is not a
windowed program; /b prevents the new console).

	My experiment showed that Python was seeing 1 character for each line
of input and CMD shell was seeing the rest.

>
>Is there a work around for this?
>

	I don't know of one, off hand. It's a partial problem (in my mind) of
how subprocess communication works in Python (and the various OSs*). The
only system I ever encountered that got close to what you are trying to do
was the Commodore Amiga with ARexx. I don't know of Regina on Windows can
duplicate it for this.

	A language feature of Rexx (ARexx was an Amiga port, and Regina is a
generalized port) is the ADDRESS statement which is used to specify a
"command interpreter" to be used by anything in the Rexx script that is NOT
parsed as a Rexx statement. Such statements would be evaluated (variable
substitutions made) and then sent directly to the "command interpreter" for
processing. Special variables would capture returns from the external
processing. On the Amiga, any program that "opened a RexxPort" could be
specified as the command interpreter (so with proper switching of "command
interpreter" one could send word processor commands to one process to, say,
select and copy a paragraph, and then switch to a desktop publishing
program to paste that paragraph). Regina basically just has a standard
shell as the target (or no shell -- direct execution).


>The whole point of the proof of concept was to be able to provide a more 
>friendly interface for python interpreter from a screen reader 
>perspective, so be disappointed if I'm stuck here.

	Unfortunately, I suspect the spawning of an interactive process may be
a hindrance (have you tried with other interactive command line programs?
Pity M$ never updated EDIT or EDLIN for 64-bit OS; they'd be ideal. I have
the impression all your other tests have been one-shot shell commands --
like "echo" -- that don't really do interaction)

	Oh, one thing...

C:\Users\Wulfraed>python /?
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)

<SNIP>

-u     : force the stdout and stderr streams to be unbuffered;
         this option has no effect on stdin; also PYTHONUNBUFFERED=x

<SNIP>

	Instead of just issuing "python", try "python -u"


*	I've only seen two operating systems that supported a simple means of
ad-hoc interprocess communication. Everything else seems to rely on things
like TCP/UDP sockets, or named pipes.
	The Amiga: the whole OS was based upon passing messages via message
ports (basically linked lists -- posting a message would add your message
structure to the end of a linked list, the target process would read
messages from the list, do stuff, and send a reply back [the message
structure included data on what port to send replies]). This was pretty
much a no-cost operation as all memory was shared by processes (which is
also the downfall of the OS -- to use protected memory would mean message
passing would have to trigger supervisor mode, so the message memory could
be unmapped from source and mapped to target).
	VAX/VMS (OpenVMS): supported things called mailboxes -- which are NOT
like mailboxes in real-time OSs. One would send messages to "named"
mailboxes and other processes could read from those mailboxes (obviously
this scheme goes through supervisor levels for memory mapping. Unlike Amiga
ports, which are readable only by the port creator, mailboxes are shared
reader/writer systems.


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From marcus.luetolf at bluewin.ch  Sun Feb 13 02:52:14 2022
From: marcus.luetolf at bluewin.ch (marcus.luetolf at bluewin.ch)
Date: Sun, 13 Feb 2022 08:52:14 +0100
Subject: [Tutor] removing items from list in for loop
Message-ID: <000f01d820ae$9fe5b760$dfb12620$@bluewin.ch>

Hello Experts, I am still trying to 

create from a list of n items, n copies of this list in a for loop with one
item successivly removed at each iteration.

I should get n copies each with n-1 items.

 

Beeing aware of problems arising when a list is alterated during an
iteration I tried to get around using a copy oft he original list.

However I got strange results, the copied list getting shorter at each
iteration or the items didn't got removed in order.

 

For example In my last attempt below item1 was never removed and I can't
understand what happens to the indexing:

 

>all_items = ['item1 ','item2 ', 'item3 ',' item4 ', 'item5 ','item6 ',
'item7', 'item8', 'item9', 'item10 ']

 

>copy_all_items = ['item1 ','item2 ', 'item3 ',' item4 ', 'item5 ','item6 ',
'item7', 'item8', 'item9', 'item10 ']

 

>for item in copy_all_items: 

    >copy_all_items.remove(item)

    >copy_all_items = all_items

    >print(item, copy_all_items)

 

 

I'd really appreciate to learn my mistake, thank you.


From joel.goldstick at gmail.com  Sun Feb 13 03:24:38 2022
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Sun, 13 Feb 2022 03:24:38 -0500
Subject: [Tutor] removing items from list in for loop
In-Reply-To: <000f01d820ae$9fe5b760$dfb12620$@bluewin.ch>
References: <000f01d820ae$9fe5b760$dfb12620$@bluewin.ch>
Message-ID: <CAPM-O+x9NEtjdNdLaW90JKWA6CFveSMkut+93B+VTDrt1o3sVw@mail.gmail.com>

On Sun, Feb 13, 2022 at 2:55 AM <marcus.luetolf at bluewin.ch> wrote:
>
> Hello Experts, I am still trying to
>
> create from a list of n items, n copies of this list in a for loop with one
> item successivly removed at each iteration.
>
> I should get n copies each with n-1 items.
>
>
>
> Beeing aware of problems arising when a list is alterated during an
> iteration I tried to get around using a copy oft he original list.
>
> However I got strange results, the copied list getting shorter at each
> iteration or the items didn't got removed in order.
>
>
>
> For example In my last attempt below item1 was never removed and I can't
> understand what happens to the indexing:
>
>
>
> >all_items = ['item1 ','item2 ', 'item3 ',' item4 ', 'item5 ','item6 ',
> 'item7', 'item8', 'item9', 'item10 ']
>
>
>
> >copy_all_items = ['item1 ','item2 ', 'item3 ',' item4 ', 'item5 ','item6 ',
> 'item7', 'item8', 'item9', 'item10 ']
>
>
>
> >for item in copy_all_items:
>
>     >copy_all_items.remove(item)
>
>     >copy_all_items = all_items
>
>     >print(item, copy_all_items)
>
>
>
>
>
> I'd really appreciate to learn my mistake, thank you.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

Show the code you have written.  Copy and paste it in your message.



-- 
Joel Goldstick

From alan.gauld at yahoo.co.uk  Sun Feb 13 03:50:41 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 13 Feb 2022 08:50:41 +0000
Subject: [Tutor] removing items from list in for loop
In-Reply-To: <000f01d820ae$9fe5b760$dfb12620$@bluewin.ch>
References: <000f01d820ae$9fe5b760$dfb12620$@bluewin.ch>
Message-ID: <suagp2$dg2$1@ciao.gmane.io>

On 13/02/2022 07:52, marcus.luetolf at bluewin.ch wrote:

>> all_items = ['item1 ','item2 ', 'item3 ',' item4 ', 'item5 ','item6 ',
> 'item7', 'item8', 'item9', 'item10 ']
> 
>> copy_all_items = ['item1 ','item2 ', 'item3 ',' item4 ', 'item5 ','item6 ',
> 'item7', 'item8', 'item9', 'item10 ']

Rather than had code it use pythons copy facilities, its a lot less
error prone

copy_all_items = all_items[:]

>> for item in copy_all_items: 
>     >copy_all_items.remove(item)

You are removing from the thing you are iterating over,
that's never a good idea!

>     >copy_all_items = all_items

But then you replace the thing you are iterating over
with something else, that's also not a good idea.

>     >print(item, copy_all_items)

This is the same as
     print(item, all_items)

iterate over all_items and remove from copy_all_items.
(or vice-versa, it doesn't matter which way round.
Just be consistent. iterate over one list remove from the other)

And do not reassign the lists.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From wescpy at gmail.com  Sun Feb 13 04:31:35 2022
From: wescpy at gmail.com (wesley chun)
Date: Sun, 13 Feb 2022 01:31:35 -0800
Subject: [Tutor] removing items from list in for loop
In-Reply-To: <000f01d820ae$9fe5b760$dfb12620$@bluewin.ch>
References: <000f01d820ae$9fe5b760$dfb12620$@bluewin.ch>
Message-ID: <CAB6eaA4h9ipVaL+POxm9JiRS+sGQr+ONpb3bCY_BYER1se8TPA@mail.gmail.com>

Rather than provide a direct answer to your inquiry, the fact that you are
already aware of the issues when modifying a list you're iterating over,
you're part way through learning something deeper about how Python works
under the covers. While not directly related to your question, I posted this
SO Q&A answer <https://stackoverflow.com/a/2573965/305689> that will shed
more light. It suffices to say that the issue you have is that Python lists
are mutable objects, and mutability is the cause of >50% of the bugs for
those somewhat new to Python.

Best of luck!
--Wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"A computer never does what you want... only what you tell it."
    wesley chun :: @wescpy <http://twitter.com/wescpy> :: Software
Architect & Engineer
    Developer Advocate at Google
<https://cloud.google.com/developers/advocates/wesley-chun/> by day; at
night: Core Python <http://amzn.com/dp/0132269937>



On Sat, Feb 12, 2022 at 11:54 PM <marcus.luetolf at bluewin.ch> wrote:

> Hello Experts, I am still trying to
>
> create from a list of n items, n copies of this list in a for loop with one
> item successivly removed at each iteration.
>
> I should get n copies each with n-1 items.
>
>
>
> Beeing aware of problems arising when a list is alterated during an
> iteration I tried to get around using a copy oft he original list.
>
> However I got strange results, the copied list getting shorter at each
> iteration or the items didn't got removed in order.
>
>
>
> For example In my last attempt below item1 was never removed and I can't
> understand what happens to the indexing:
>
>
>
> >all_items = ['item1 ','item2 ', 'item3 ',' item4 ', 'item5 ','item6 ',
> 'item7', 'item8', 'item9', 'item10 ']
>
>
>
> >copy_all_items = ['item1 ','item2 ', 'item3 ',' item4 ', 'item5 ','item6
> ',
> 'item7', 'item8', 'item9', 'item10 ']
>
>
>
> >for item in copy_all_items:
>
>     >copy_all_items.remove(item)
>
>     >copy_all_items = all_items
>
>     >print(item, copy_all_items)
>
>
>
>
>
> I'd really appreciate to learn my mistake, thank you.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From __peter__ at web.de  Sun Feb 13 05:56:01 2022
From: __peter__ at web.de (Peter Otten)
Date: Sun, 13 Feb 2022 11:56:01 +0100
Subject: [Tutor] removing items from list in for loop
In-Reply-To: <000f01d820ae$9fe5b760$dfb12620$@bluewin.ch>
References: <000f01d820ae$9fe5b760$dfb12620$@bluewin.ch>
Message-ID: <d087746b-14be-dc1a-6111-6a86bc652831@web.de>

On 13/02/2022 08:52, marcus.luetolf at bluewin.ch wrote:
> Hello Experts, I am still trying to
>
> create from a list of n items, n copies of this list in a for loop with one
> item successivly removed at each iteration.


 >>> def build_lists(items):
     result = []
     for value in items:
         # copy the original list
         copy = items[:]
         # remove the current value from the copy
         copy.remove(value)
         # append to the result (a list of lists)
         result.append(copy)
     return result

 >>> build_lists(["Peter", "Paul", "Mary"])
[['Paul', 'Mary'], ['Peter', 'Mary'], ['Peter', 'Paul']]

But note a potential problem with this:

 >>> build_lists([1, 2, 1.0])
[[2, 1.0], [1, 1.0], [2, 1.0]]

You always remove the first match. If you have duplicates and want to
remove the right occurrence you need to delete rather than remove. One way:

 >>> def deleted(items, index):
	result = items[:]
	del result[index]
	return result

 >>> items = [1, 2, 1.0]
 >>> [deleted(items, i) for i in range(len(items))]
[[2, 1.0], [1, 1.0], [1, 2]]

From nathan-tech at hotmail.com  Sun Feb 13 07:17:22 2022
From: nathan-tech at hotmail.com (Nathan Smith)
Date: Sun, 13 Feb 2022 12:17:22 +0000
Subject: [Tutor] What am I missing here?
In-Reply-To: <ietg0h5i89ums6i9tl1icu4npfqsjl6gbq@4ax.com>
References: <DB7PR07MB5093BEC6E18E7E9D7306F289E4319@DB7PR07MB5093.eurprd07.prod.outlook.com>
 <pbrf0h1s6aga0gaofu6vml6j10f1upnrjl@4ax.com>
 <DB7PR07MB509385B79B37429144A7B1ACE4329@DB7PR07MB5093.eurprd07.prod.outlook.com>
 <ietg0h5i89ums6i9tl1icu4npfqsjl6gbq@4ax.com>
Message-ID: <DB7PR07MB5093EC4C44B5A37404C65141E4329@DB7PR07MB5093.eurprd07.prod.outlook.com>

Heya,


thanks for your response.

Admittedly, a bit of a shame as from what you've mentioned, and from 
research I've done that supports it, it does seem like this proof of 
concept was a bit of a bust. Well, sort of anyway.

the command prompt side of things works, but the second you hand off to 
interactive shells, bust. And not only bust but stuck bust so you can't 
even back out of it.

It's true I could write in an exception something like...

if(line==">>>"):

 ?# we're in the python console

 ?handle.stdin.write("exit")

 ?# some code here to send control z, I think winpexpect actually has a 
function for that

 ?# tell the user that interactive shells are not supported


Which is fine for python, but would not be a catch all for any other 
interactive shell out there that may do things in a similar way, I'm 
thinking of gdb for instance (though is there a windows gdb?)


On a side note of this not being a *complete* bust, I could do a 
separate program for running the python interactive shell by wrapping 
something around eval, right?

Eval can be dangerous because you can literally execute anything but, in 
the case of a shell wrapper, that's kind of the point because it's the 
same as running the python command anyway?


In that light though I have a new question. How would I go about running 
something that was multiple lines?

It's a bit of reinventing the wheel but if the user enters:

for x in range(10):

 ?print(x)


How would I hand that off to eval? Putting:

eval("for x in range(10): \n print(x)") throws me a syntax error.


Best

Nathan

On 13/02/2022 04:13, Dennis Lee Bieber wrote:
> On Sun, 13 Feb 2022 02:17:14 +0000, Nathan Smith <nathan-tech at hotmail.com>
> declaimed the following:
>
>> I had a read through the links provided and admit I'm not sure if I
>> understood *all* of it, though I agree with you on the point about how
>> the interpreter probably handles booting up.
>>
> 	Take into account that this was all hypothesis on my part. I've never
> coded something using that level of Win32.
>
>
>> I'm assuming, as you mentioned, that this is because the interpreter is
>> not inheriting those stdout and stderr handles from the cmd.exe?
>>
> 	Again, hypothesis... One would have to study the Python start-up code
> for Windows to see what it is doing with the I/O.
>
> 	If you really want to get perplexed, open a command shell and enter:
>
> start /b python
>
> (normally "start" will open a new console if the application is not a
> windowed program; /b prevents the new console).
>
> 	My experiment showed that Python was seeing 1 character for each line
> of input and CMD shell was seeing the rest.
>
>> Is there a work around for this?
>>
> 	I don't know of one, off hand. It's a partial problem (in my mind) of
> how subprocess communication works in Python (and the various OSs*). The
> only system I ever encountered that got close to what you are trying to do
> was the Commodore Amiga with ARexx. I don't know of Regina on Windows can
> duplicate it for this.
>
> 	A language feature of Rexx (ARexx was an Amiga port, and Regina is a
> generalized port) is the ADDRESS statement which is used to specify a
> "command interpreter" to be used by anything in the Rexx script that is NOT
> parsed as a Rexx statement. Such statements would be evaluated (variable
> substitutions made) and then sent directly to the "command interpreter" for
> processing. Special variables would capture returns from the external
> processing. On the Amiga, any program that "opened a RexxPort" could be
> specified as the command interpreter (so with proper switching of "command
> interpreter" one could send word processor commands to one process to, say,
> select and copy a paragraph, and then switch to a desktop publishing
> program to paste that paragraph). Regina basically just has a standard
> shell as the target (or no shell -- direct execution).
>
>
>> The whole point of the proof of concept was to be able to provide a more
>> friendly interface for python interpreter from a screen reader
>> perspective, so be disappointed if I'm stuck here.
> 	Unfortunately, I suspect the spawning of an interactive process may be
> a hindrance (have you tried with other interactive command line programs?
> Pity M$ never updated EDIT or EDLIN for 64-bit OS; they'd be ideal. I have
> the impression all your other tests have been one-shot shell commands --
> like "echo" -- that don't really do interaction)
>
> 	Oh, one thing...
>
> C:\Users\Wulfraed>python /?
> usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
> Options and arguments (and corresponding environment variables):
> -b     : issue warnings about str(bytes_instance), str(bytearray_instance)
>           and comparing bytes/bytearray with str. (-bb: issue errors)
>
> <SNIP>
>
> -u     : force the stdout and stderr streams to be unbuffered;
>           this option has no effect on stdin; also PYTHONUNBUFFERED=x
>
> <SNIP>
>
> 	Instead of just issuing "python", try "python -u"
>
>
> *	I've only seen two operating systems that supported a simple means of
> ad-hoc interprocess communication. Everything else seems to rely on things
> like TCP/UDP sockets, or named pipes.
> 	The Amiga: the whole OS was based upon passing messages via message
> ports (basically linked lists -- posting a message would add your message
> structure to the end of a linked list, the target process would read
> messages from the list, do stuff, and send a reply back [the message
> structure included data on what port to send replies]). This was pretty
> much a no-cost operation as all memory was shared by processes (which is
> also the downfall of the OS -- to use protected memory would mean message
> passing would have to trigger supervisor mode, so the message memory could
> be unmapped from source and mapped to target).
> 	VAX/VMS (OpenVMS): supported things called mailboxes -- which are NOT
> like mailboxes in real-time OSs. One would send messages to "named"
> mailboxes and other processes could read from those mailboxes (obviously
> this scheme goes through supervisor levels for memory mapping. Unlike Amiga
> ports, which are readable only by the port creator, mailboxes are shared
> reader/writer systems.
>
>
-- 

Best Wishes,

Nathan Smith, BSC


My Website: https://nathantech.net



From wlfraed at ix.netcom.com  Sun Feb 13 12:37:34 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Sun, 13 Feb 2022 12:37:34 -0500
Subject: [Tutor] What am I missing here?
References: <DB7PR07MB5093BEC6E18E7E9D7306F289E4319@DB7PR07MB5093.eurprd07.prod.outlook.com>
 <pbrf0h1s6aga0gaofu6vml6j10f1upnrjl@4ax.com>
 <DB7PR07MB509385B79B37429144A7B1ACE4329@DB7PR07MB5093.eurprd07.prod.outlook.com>
 <ietg0h5i89ums6i9tl1icu4npfqsjl6gbq@4ax.com>
 <DB7PR07MB5093EC4C44B5A37404C65141E4329@DB7PR07MB5093.eurprd07.prod.outlook.com>
Message-ID: <l3fi0h9beu3kmeio2qrj960dl4gf4rkucl@4ax.com>

On Sun, 13 Feb 2022 12:17:22 +0000, Nathan Smith <nathan-tech at hotmail.com>
declaimed the following:

>
>On a side note of this not being a *complete* bust, I could do a 
>separate program for running the python interactive shell by wrapping 
>something around eval, right?
>
>Eval can be dangerous because you can literally execute anything but, in 
>the case of a shell wrapper, that's kind of the point because it's the 
>same as running the python command anyway?
>

	Ugh... (Personal impression -- you also would have to manage the
"environment": global and local namespaces, to avoid having the "run task"
fill up your "shell" process with junk... or even change stuff if variable
names are the same)

>
>In that light though I have a new question. How would I go about running 
>something that was multiple lines?
>

	Did you look at exec()? Same problem with environment management but
works with "suites" of statements (think the >>> to ... change over in the
interactive Python console when entering an "if" statement, or similar).
https://docs.python.org/3/library/functions.html#eval
https://docs.python.org/3/library/functions.html#exec

>It's a bit of reinventing the wheel but if the user enters:
>
>for x in range(10):
>
> ?print(x)
>
>
>How would I hand that off to eval? Putting:
>
>eval("for x in range(10): \n print(x)") throws me a syntax error.
>

	eval() works with EXPRESSIONS -- basically, anything that can be on the
right-hand side of an =

>>> while True:
...   expr = input("Enter expression to be evaluated> ")
...   resl = eval(expr)
...   print("Result:\t%s" % resl)
...
Enter expression to be evaluated> 3 + 234
Result: 237
Enter expression to be evaluated> 3 + 234 / 123
Result: 4.902439024390244
Enter expression to be evaluated> Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
EOFError
>>>

	exec(), as mentioned, works with statement (suites), not expressions,
and returns None (so if you need to extract computed values they should be
in the globals or locals dictionaries that are mutatable).

	Unfortunately, that does mean you'll need complete statement/suites --
you can't just feed one line at a time to it. (I'm not going to attempt a
demo). Which could mean having to implement (or invoke) the Python parser
and somehow tracking when it reports it is back to the top-level of
indentation -- then passing the code block to exec().



-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From wlfraed at ix.netcom.com  Sun Feb 13 13:45:47 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Sun, 13 Feb 2022 13:45:47 -0500
Subject: [Tutor] removing items from list in for loop
References: <000f01d820ae$9fe5b760$dfb12620$@bluewin.ch>
Message-ID: <bqgi0hpdjbo36srsqn3ar5v86o0ks5i3nt@4ax.com>

On Sun, 13 Feb 2022 08:52:14 +0100, <marcus.luetolf at bluewin.ch> declaimed
the following:

>create from a list of n items, n copies of this list in a for loop with one
>item successivly removed at each iteration.
>
>I should get n copies each with n-1 items.

	It would help if you showed us, for a toy data set, the input list, AND
all appropriate output lists.

	Secondly, do you need to accumulate the lists (eg: a list of output
lists) for later usage, or do you just need to dump each to the display?

	The first time you posted this matter, I jumped into the deep end using
a module with a function to generate combinations (not permutations) --
since what you seem to be asking for is

		all combinations of N items taken N-1 at a time

That is almost a one-liner; the code to display each combination takes up
more space then generating them.


>Beeing aware of problems arising when a list is alterated during an
>iteration I tried to get around using a copy oft he original list.
>
>However I got strange results, the copied list getting shorter at each
>iteration or the items didn't got removed in order.
>

	Try to rethink the problem... As you have it, you are trying 1) extract
one item from some list, 2) asking Python to remove that same item from a
copy of the same list (which means Python has to loop over the list trying
to match the item), 3) and repeat for each item in the original list.
That's a lot of (hidden) looping/matching being performed.

	Assuming I understand the assignment -- you don't even need to start
with a copy of the list and remove one item from it... Just slice the
original list /skipping/ one item to create the result list. That just
requires knowing the position in the list to be excluded.

>>> alist = list(range(10))
>>> alist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> rlist = alist[:2] + alist[3:]
>>> rlist
[0, 1, 3, 4, 5, 6, 7, 8, 9]
>>> rlist = alist[:0] + alist[1:]
>>> rlist
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> rlist = alist[:9] + alist[10:]
>>> rlist
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> 

	It should be trivial to create a loop that starts with the first
position and goes to the length of the list.


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From wlfraed at ix.netcom.com  Sun Feb 13 14:02:14 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Sun, 13 Feb 2022 14:02:14 -0500
Subject: [Tutor] removing items from list in for loop
References: <000f01d820ae$9fe5b760$dfb12620$@bluewin.ch>
 <bqgi0hpdjbo36srsqn3ar5v86o0ks5i3nt@4ax.com>
Message-ID: <95li0hlf4brmct0ff8r2v646gv2nv9d7rb@4ax.com>

On Sun, 13 Feb 2022 13:45:47 -0500, Dennis Lee Bieber
<wlfraed at ix.netcom.com> declaimed the following:


>>>> alist = list(range(10))
>>>> alist
>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>> rlist = alist[:2] + alist[3:]
>>>> rlist
>[0, 1, 3, 4, 5, 6, 7, 8, 9]
>>>> rlist = alist[:0] + alist[1:]
>>>> rlist
>[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>> rlist = alist[:9] + alist[10:]
>>>> rlist
>[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>>> 
>
>	It should be trivial to create a loop that starts with the first
>position and goes to the length of the list.

	If it isn't clear from the examples

	[:pos]		keep all items from start of list to <pos> (to be skipped)
	[pos+1:]		keep all items from after skipped <pos> to end

<pos> is 0 for the first item in the list
<pos> is len(list)-1 for the last item in the list
	ie: for a 10-item list, <pos> is 0 to 9 (just what range(10) generates)



-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From cs at cskk.id.au  Sun Feb 13 16:54:03 2022
From: cs at cskk.id.au (Cameron Simpson)
Date: Mon, 14 Feb 2022 08:54:03 +1100
Subject: [Tutor] removing items from list in for loop
In-Reply-To: <000f01d820ae$9fe5b760$dfb12620$@bluewin.ch>
References: <000f01d820ae$9fe5b760$dfb12620$@bluewin.ch>
Message-ID: <Ygl9+zTLPNtVatVw@cskk.homeip.net>

On 13Feb2022 08:52, marcus.luetolf at bluewin.ch <marcus.luetolf at bluewin.ch> wrote:
>create from a list of n items, n copies of this list in a for loop with 
>one item successivly removed at each iteration.
>
>I should get n copies each with n-1 items.
>
>
>Beeing aware of problems arising when a list is alterated during an
>iteration I tried to get around using a copy oft he original list.
[...]

You code here:

    all_items = ['item1 ','item2 ', ......]
    copy_all_items = ... the same list definition ...
    for item in copy_all_items:
        copy_all_items.remove(item)
        copy_all_items = all_items
        print(item, copy_all_items)

does not do what you think. Specificly this step:

    copy_all_items = all_items

Does not make a copy of "all_items". Instead, it makes "copy_all_items" 
a reference to the original list referenced by "all_items". From then on 
you're modifying the "all_items" list. So your first pass for "item1 " 
removed from your original duplicate list, because that is what 
"copy_all_items" referred to. Every subsequent pass removed from the 
first list.

Only the fact that your for-loop iterates over the original 
"copy_all_items" brings even a semblance of normal operation.

The quick way to copy a list is either:

    list2 = list(list1)

which constructs a new list from the elements in "list1" or:

    list2 = list1[:]

which constructs a new list as a slice of from "list1", but the slice is 
the size of the entire list, thus a copy.

Both of these construct new lists. Compared with:

    list2 = list1

which just makes "list2" point at the same list as "list1". No second 
list is made/copied.

Note that _all_ Python variables are references, and an assigment 
statement never copies the contents of an object - it just takes an 
object reference (the right hand side) and places it in the variable on 
the left hand side.

Cheers,
Cameron Simpson <cs at cskk.id.au>

From ibrahim_y23 at yahoo.com  Sat Feb 19 07:18:41 2022
From: ibrahim_y23 at yahoo.com (mohammed ibrahim)
Date: Sat, 19 Feb 2022 07:18:41 -0500
Subject: [Tutor] Automate report from tableau dashboard
References: <3D0EBABF-6FE3-4E14-B6C9-C4CF7B71C9B1.ref@yahoo.com>
Message-ID: <3D0EBABF-6FE3-4E14-B6C9-C4CF7B71C9B1@yahoo.com>

Hi Pythoners

I?m trying to automate a report that should run every hour  and execute a series of filter from a tableau dashboard and send a report email to few people , please let me know if this is doable ?







Thanks
Ibrahim




From alan.gauld at yahoo.co.uk  Sat Feb 19 11:49:12 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 19 Feb 2022 16:49:12 +0000
Subject: [Tutor] Automate report from tableau dashboard
In-Reply-To: <3D0EBABF-6FE3-4E14-B6C9-C4CF7B71C9B1@yahoo.com>
References: <3D0EBABF-6FE3-4E14-B6C9-C4CF7B71C9B1.ref@yahoo.com>
 <3D0EBABF-6FE3-4E14-B6C9-C4CF7B71C9B1@yahoo.com>
Message-ID: <sur729$i58$1@ciao.gmane.io>

On 19/02/2022 12:18, mohammed ibrahim via Tutor wrote:
> Hi Pythoners
> 
> I?m trying to automate a report that should run every hour  and execute 
> a series of filter from a tableau dashboard and send a report email 
> to few people , please let me know if this is doable ?
Yes it is.

But how to do it will depend a lot on your OS since each OS has its own
tools for scheduling jobs.

Also what format the report is in etc. will make a big difference.
I'm not sure if a tableu dashboard in this case means a specific
product or a generic type of tableu. If its a specific prodct it
may have an API, possubly even a python package for accessing it.
If you mean a generic tableu then a lot will depend on how it
is built and what access it offers.

It will also depend n whether you have direct access to the servers
or whether you must access it remotely. If the latter is it within
the same firewall or remotely over the internet?

So, yes it is possible, but exactly how remains a mystery.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From m at hvdev.cc  Sat Feb 19 19:29:34 2022
From: m at hvdev.cc (=?UTF-8?Q?V=C5=A9_Thanh_H=E1=BA=A3i?=)
Date: Sun, 20 Feb 2022 07:29:34 +0700
Subject: [Tutor] Automate report from tableau dashboard
In-Reply-To: <3D0EBABF-6FE3-4E14-B6C9-C4CF7B71C9B1@yahoo.com>
References: <3D0EBABF-6FE3-4E14-B6C9-C4CF7B71C9B1.ref@yahoo.com>
 <3D0EBABF-6FE3-4E14-B6C9-C4CF7B71C9B1@yahoo.com>
Message-ID: <17f1488a6e0.1db4896d67068.4820078627767396933@hvdev.cc>

Hello Ibrahim,

Yes this is doable, but not about Python.

On linux you have `Cron Job`. On Windows there is `Scheduled Task`.  
Set them up to schedule running your Python script.

Thanks and kind regards,

Vu Thanh Hai 
Full-stack Developer

-o-0_o-0-o_0-o-0_o-0-o-
?
Website: www.hvdev.cc
Email: m at hvdev.cc
Twitter: @hvhvdevdev
GitHub: @hvhvdevdev

---- On Sat, 19 Feb 2022 19:18:41 +0700 mohammed ibrahim via Tutor <tutor at python.org> wrote ----

 > Hi Pythoners
 > 
 > I?m trying to automate a report that should run every hour  and execute a series of filter from a tableau dashboard and send a report email to few people , please let me know if this is doable ?
 > 
 > 
 > 
 > 
 > 
 > 
 > 
 > Thanks
 > Ibrahim
 > 
 > 
 > 
 > _______________________________________________
 > Tutor maillist  - Tutor at python.org
 > To unsubscribe or change subscription options:
 > https://mail.python.org/mailman/listinfo/tutor
 > 

From pgoedde2 at gmail.com  Sat Feb 19 15:34:49 2022
From: pgoedde2 at gmail.com (ShockTube)
Date: Sat, 19 Feb 2022 13:34:49 -0700
Subject: [Tutor] pip install issues
Message-ID: <CAFZvtV0una_74XFwvev0QxpeKX8FZX7nGWMy3Pa08Byka-wB3g@mail.gmail.com>

Hello:

Very new to python. Have programming background but in RPG, Bought a Python
book, ran into a roadblock, reached out to publishers, who
contacted author, who never bothered to reply. Reached out to Stack
Overflow and they were of minimal help.

Trying to do a pip install and not successful. Have established that cannot
run that command within an interpreter, Understand that. Answer from Stack
Overflow talked of a Python Terminal to run command. Internet is of minimal
help in explaining what that is. Somewhere between a Python environment and
the interpreter is this magical place that will accept and process a pip
install command, and anything similar.

That is what I need to know.

Thanks.

From alan.gauld at yahoo.co.uk  Sat Feb 19 20:02:36 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 20 Feb 2022 01:02:36 +0000
Subject: [Tutor] pip install issues
In-Reply-To: <CAFZvtV0una_74XFwvev0QxpeKX8FZX7nGWMy3Pa08Byka-wB3g@mail.gmail.com>
References: <CAFZvtV0una_74XFwvev0QxpeKX8FZX7nGWMy3Pa08Byka-wB3g@mail.gmail.com>
Message-ID: <sus3vd$16c6$1@ciao.gmane.io>

On 19/02/2022 20:34, ShockTube wrote:

> Trying to do a pip install and not successful. Have established that cannot
> run that command within an interpreter, Understand that. Answer from Stack
> Overflow talked of a Python Terminal to run command. 

That usually just means the Python interactive prompt.
Or within an IDE it might mean a Python prompt window.
There is really no such thing as a python terminal.

> the interpreter is this magical place that will accept and process a pip
> install command, and anything similar.

pip was originally intended to be run from the OS shell prompt.
But that  an lead to some issues and most folks today recommend running
it from python using the -m(module) flag:

$ python -m pip install somepackage

That should ensure that everything gets installed in the right
place and you see meaningful error messages if it doesn't.

If it doesn't work and you can't see what's wrong come back
with an error trace and we'll see what we can do.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From mats at wichmann.us  Sat Feb 19 20:15:53 2022
From: mats at wichmann.us (Mats Wichmann)
Date: Sat, 19 Feb 2022 18:15:53 -0700
Subject: [Tutor] pip install issues
In-Reply-To: <CAFZvtV0una_74XFwvev0QxpeKX8FZX7nGWMy3Pa08Byka-wB3g@mail.gmail.com>
References: <CAFZvtV0una_74XFwvev0QxpeKX8FZX7nGWMy3Pa08Byka-wB3g@mail.gmail.com>
Message-ID: <ab079d9e-5f9c-1ba3-245d-920ff353115d@wichmann.us>

On 2/19/22 13:34, ShockTube wrote:
> Hello:
> 
> Very new to python. Have programming background but in RPG, Bought a Python
> book, ran into a roadblock, reached out to publishers, who
> contacted author, who never bothered to reply. Reached out to Stack
> Overflow and they were of minimal help.
> 
> Trying to do a pip install and not successful. Have established that cannot
> run that command within an interpreter, Understand that. Answer from Stack
> Overflow talked of a Python Terminal to run command. Internet is of minimal
> help in explaining what that is. Somewhere between a Python environment and
> the interpreter is this magical place that will accept and process a pip
> install command, and anything similar.
> 
> That is what I need to know.
> 

It just means your operating system's "terminal" or "console".  It's a
shell like bash on Linux, or (since 2019 I think) the quite similar zsh
on Mac, or cmd.exe or PowerShell on Windows.  Since these days all three
of those systems are windowed environments, you also need something to
create a window on your screen to run that in.  On the Mac that's called
Terminal, on Linux some graphical environments call it that, some may
call it something slightly different.  On Windows cmd and powershell
open a terminal, there's also a newer application called Windows
Terminal you can use.

Wasn't anything more complex than that - there's no magical place, it's
just the system facility for typing at a command line.

You might benfit from looking for a video (youtube would be the obvious
place since it's so popular) that shows some initial Python steps.  You
could look for some videos by Corey Schafer just to give you one pointer
- I'm not making any claims they're the best out there or anything.
He's got one that's perhaps more than you want "Python Tutorial: pip -
an in-depth look at the package management system", but maybe even the
first few minutes of watching things run is more illustrative than
hundreds of words.



From flpasana at outlook.com  Sat Feb 19 22:19:43 2022
From: flpasana at outlook.com (Erick Pasana)
Date: Sun, 20 Feb 2022 03:19:43 +0000
Subject: [Tutor] pip install issues
In-Reply-To: <ab079d9e-5f9c-1ba3-245d-920ff353115d@wichmann.us>
References: <CAFZvtV0una_74XFwvev0QxpeKX8FZX7nGWMy3Pa08Byka-wB3g@mail.gmail.com>
 <ab079d9e-5f9c-1ba3-245d-920ff353115d@wichmann.us>
Message-ID: <PH0PR02MB7223CE6A35F579B6C93BACF5DA399@PH0PR02MB7223.namprd02.prod.outlook.com>

I too have been in your situation a year ago. Just go click this link, it?s a YouTube lesson about Python Basics. You can easily solve your predicament there if you haven?t yet?Python 3 Programming Tutorials for Beginners<https://youtube.com/playlist?list=PLeo1K3hjS3uv5U-Lmlnucd7gqF-3ehIh0> . And a piece of advice with regards to choosing a code editor which we all need to make learning easier, try VS CODE. It has a ton of tutorials in YouTube.


Erick

From: Mats Wichmann<mailto:mats at wichmann.us>
Sent: Sunday, 20 February 2022 9:17 am
To: tutor at python.org<mailto:tutor at python.org>
Subject: Re: [Tutor] pip install issues

On 2/19/22 13:34, ShockTube wrote:
> Hello:
>
> Very new to python. Have programming background but in RPG, Bought a Python
> book, ran into a roadblock, reached out to publishers, who
> contacted author, who never bothered to reply. Reached out to Stack
> Overflow and they were of minimal help.
>
> Trying to do a pip install and not successful. Have established that cannot
> run that command within an interpreter, Understand that. Answer from Stack
> Overflow talked of a Python Terminal to run command. Internet is of minimal
> help in explaining what that is. Somewhere between a Python environment and
> the interpreter is this magical place that will accept and process a pip
> install command, and anything similar.
>
> That is what I need to know.
>

It just means your operating system's "terminal" or "console".  It's a
shell like bash on Linux, or (since 2019 I think) the quite similar zsh
on Mac, or cmd.exe or PowerShell on Windows.  Since these days all three
of those systems are windowed environments, you also need something to
create a window on your screen to run that in.  On the Mac that's called
Terminal, on Linux some graphical environments call it that, some may
call it something slightly different.  On Windows cmd and powershell
open a terminal, there's also a newer application called Windows
Terminal you can use.

Wasn't anything more complex than that - there's no magical place, it's
just the system facility for typing at a command line.

You might benfit from looking for a video (youtube would be the obvious
place since it's so popular) that shows some initial Python steps.  You
could look for some videos by Corey Schafer just to give you one pointer
- I'm not making any claims they're the best out there or anything.
He's got one that's perhaps more than you want "Python Tutorial: pip -
an in-depth look at the package management system", but maybe even the
first few minutes of watching things run is more illustrative than
hundreds of words.


_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fmail.python.org%2Fmailman%2Flistinfo%2Ftutor&amp;data=04%7C01%7C%7C7ea15195410e4c1348fc08d9f40eb384%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637809166236641660%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000&amp;sdata=VZCk%2F1jBsOBtOObrNK%2B29aRe2MzUQqObcDSDjcl9oU8%3D&amp;reserved=0


From manpritsinghece at gmail.com  Mon Feb 21 06:29:44 2022
From: manpritsinghece at gmail.com (Manprit Singh)
Date: Mon, 21 Feb 2022 16:59:44 +0530
Subject: [Tutor] Getting greatest 3 numbers from list
Message-ID: <CAO1OCwaeHiQQ6MGWt86V-2nRYmH2m+gB4icPCadOODTUWrk7+g@mail.gmail.com>

Dear Sir,

My problem is to get greatest 3 numbers from list, list ls  along with
solution given below:
ls = [2, 4, 9, 6, 3, 9, 6, 1]
sorted(set(ls))[-3:]

gives the right answer

[4, 6, 9]

Tried it with a for loop, just thinking why i am producing  a sorted list , for

only getting largest 3 items

lmax = []
ls = [2, 4, 9, 6, 3, 9, 6, 1]
for _ in range(3):
    mx = ls[0]
    for ele in ls[1:]:
        if ele > mx and ele not in lmax:
            mx = ele
    lmax.append(mx)
print(lmax)

gives the correct answer

[9, 6, 4]

This problem be done with a for loop more easily ? i know it is not a good

question - my apologies

Regards

Manprit Singh

From hannah.jones at ebcbrakesuk.com  Mon Feb 21 07:13:02 2022
From: hannah.jones at ebcbrakesuk.com (Hannah Jones)
Date: Mon, 21 Feb 2022 12:13:02 +0000
Subject: [Tutor] pip install issues
In-Reply-To: <CAFZvtV0una_74XFwvev0QxpeKX8FZX7nGWMy3Pa08Byka-wB3g@mail.gmail.com>
References: <CAFZvtV0una_74XFwvev0QxpeKX8FZX7nGWMy3Pa08Byka-wB3g@mail.gmail.com>
Message-ID: <LOYP123MB270304FC475632F0DB9B164D903A9@LOYP123MB2703.GBRP123.PROD.OUTLOOK.COM>

Hello,

You can run a pip install on the command prompt (type CMD) in the windows bar

In command prompt; (I would download to my downloads so use CD (change directory))  cd downloads

Then use the pip install command.

Pip install blahblah

That should work.

Thanks 



-----Original Message-----
From: Tutor <tutor-bounces+hannah.jones=ebcbrakesuk.com at python.org> On Behalf Of ShockTube
Sent: 19 February 2022 20:35
To: tutor at python.org
Subject: [Tutor] pip install issues

Hello:

Very new to python. Have programming background but in RPG, Bought a Python book, ran into a roadblock, reached out to publishers, who contacted author, who never bothered to reply. Reached out to Stack Overflow and they were of minimal help.

Trying to do a pip install and not successful. Have established that cannot run that command within an interpreter, Understand that. Answer from Stack Overflow talked of a Python Terminal to run command. Internet is of minimal help in explaining what that is. Somewhere between a Python environment and the interpreter is this magical place that will accept and process a pip install command, and anything similar.

That is what I need to know.

Thanks.
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

From alan.gauld at yahoo.co.uk  Mon Feb 21 08:23:05 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 21 Feb 2022 13:23:05 +0000
Subject: [Tutor] Getting greatest 3 numbers from list
In-Reply-To: <CAO1OCwaeHiQQ6MGWt86V-2nRYmH2m+gB4icPCadOODTUWrk7+g@mail.gmail.com>
References: <CAO1OCwaeHiQQ6MGWt86V-2nRYmH2m+gB4icPCadOODTUWrk7+g@mail.gmail.com>
Message-ID: <sv03nt$vji$1@ciao.gmane.io>

On 21/02/2022 11:29, Manprit Singh wrote:

> solution given below:
> ls = [2, 4, 9, 6, 3, 9, 6, 1]
> sorted(set(ls))[-3:]
> 
> gives the right answer
> 
> [4, 6, 9]

Yes, and that's almost certainly the best way to do it.


> Tried it with a for loop, just thinking why i am producing  a sorted list , for
> only getting largest 3 items

Why not, it is the simplest approach?

> lmax = []
> ls = [2, 4, 9, 6, 3, 9, 6, 1]
> for _ in range(3):
>     mx = ls[0]
>     for ele in ls[1:]:
>         if ele > mx and ele not in lmax:
>             mx = ele
>     lmax.append(mx)
> print(lmax)

This loops over ls 3 times. That's not necessary.
One alternative is:

>>> ls = [2, 4, 9, 6, 3, 9, 6, 1]
>>> lmax = ls[:3]
>>> for n in ls[3:]:
       if n in lmax: continue
       for i,j in enumerate(lmax):
           if n > j:
              lmax[i] = n
              break

Which should be faster, and at least no slower.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From __peter__ at web.de  Mon Feb 21 08:21:57 2022
From: __peter__ at web.de (Peter Otten)
Date: Mon, 21 Feb 2022 14:21:57 +0100
Subject: [Tutor] Getting greatest 3 numbers from list
In-Reply-To: <CAO1OCwaeHiQQ6MGWt86V-2nRYmH2m+gB4icPCadOODTUWrk7+g@mail.gmail.com>
References: <CAO1OCwaeHiQQ6MGWt86V-2nRYmH2m+gB4icPCadOODTUWrk7+g@mail.gmail.com>
Message-ID: <ca9cb851-d0f8-5a7a-63f2-0e623c334d47@web.de>

On 21/02/2022 12:29, Manprit Singh wrote:
> Dear Sir,
>
> My problem is to get greatest 3 numbers from list, list ls  along with
> solution given below:
> ls = [2, 4, 9, 6, 3, 9, 6, 1]
> sorted(set(ls))[-3:]
>
> gives the right answer
>
> [4, 6, 9]
>
> Tried it with a for loop, just thinking why i am producing  a sorted list , for
>
> only getting largest 3 items
>
> lmax = []
> ls = [2, 4, 9, 6, 3, 9, 6, 1]
> for _ in range(3):
>      mx = ls[0]
>      for ele in ls[1:]:
>          if ele > mx and ele not in lmax:
>              mx = ele
>      lmax.append(mx)
> print(lmax)
>
> gives the correct answer
>
> [9, 6, 4]
>
> This problem be done with a for loop more easily ? i know it is not a good
>
> question - my apologies
>

I don't think it's a bad question. One answer is to keep the 3 largest
values in a heap starting with the first three in the sequence.
Then remove the smallest value and insert the current value from the
iteration whenever it is larger than the smallest value in the heap.

See the source and docs for the heapq.nlargest() function for a detailed
explanation. If the current implementation looks too complicated start
with an older version (before 3.5) of the module where nlargest()
doesn't accept a 'key' parameter.

https://docs.python.org/3/library/heapq.html#heapq.nlargest
https://docs.python.org/3/library/heapq.html#theory

PS: Here's an implementation that uses a sorted list to keep the largest
n items:

 >>> def nlargest(n, items):
	items = iter(items)
	result = sorted(islice(items, n))
	for item in items:
		if item > result[0]:
			result[0] = item
			result.sort()
	return result

 >>> from itertools import islice
 >>> from random import shuffle
 >>> items = list(range(10))
 >>> shuffle(items)
 >>> items
[1, 0, 9, 3, 4, 6, 7, 5, 2, 8]
 >>> nlargest(3, items)
[7, 8, 9]

From manpritsinghece at gmail.com  Mon Feb 21 08:46:29 2022
From: manpritsinghece at gmail.com (Manprit Singh)
Date: Mon, 21 Feb 2022 19:16:29 +0530
Subject: [Tutor] Getting greatest 3 numbers from list
In-Reply-To: <ca9cb851-d0f8-5a7a-63f2-0e623c334d47@web.de>
References: <CAO1OCwaeHiQQ6MGWt86V-2nRYmH2m+gB4icPCadOODTUWrk7+g@mail.gmail.com>
 <ca9cb851-d0f8-5a7a-63f2-0e623c334d47@web.de>
Message-ID: <CAO1OCwb2tXt-j0_Jg0quUQsdRJOvz3tON+PYWZfGeSefk=KOhg@mail.gmail.com>

Dear Sir ,

This is not related to python, but a general question, in c++ we have sets
in standard template library and iterators, and sets are basically sorted,
So doing the same problem in c++ using sets is a bad idea ?

#include<iostream>
#include<set>
#include<functional>
using namespace std;

int main()
{
    int arry[6] = {2, 4, 9, 2, 4, 1};
    set<int> second(arry, arry+6);
    auto itr = second.end();
    itr--;
    auto greatest = *itr;
    itr--;
    auto seclargest = *itr;
    itr--;
    auto thirdlargest = *itr;
    cout << greatest << " " << seclargest << " "<<thirdlargest;
    return 0;
}

Gives the right answer

My apologies for posting c++ code if it is against the rule of python
mailing list

Regards
Manprit Singh




On Mon, Feb 21, 2022 at 6:58 PM Peter Otten <__peter__ at web.de> wrote:

> On 21/02/2022 12:29, Manprit Singh wrote:
> > Dear Sir,
> >
> > My problem is to get greatest 3 numbers from list, list ls  along with
> > solution given below:
> > ls = [2, 4, 9, 6, 3, 9, 6, 1]
> > sorted(set(ls))[-3:]
> >
> > gives the right answer
> >
> > [4, 6, 9]
> >
> > Tried it with a for loop, just thinking why i am producing  a sorted
> list , for
> >
> > only getting largest 3 items
> >
> > lmax = []
> > ls = [2, 4, 9, 6, 3, 9, 6, 1]
> > for _ in range(3):
> >      mx = ls[0]
> >      for ele in ls[1:]:
> >          if ele > mx and ele not in lmax:
> >              mx = ele
> >      lmax.append(mx)
> > print(lmax)
> >
> > gives the correct answer
> >
> > [9, 6, 4]
> >
> > This problem be done with a for loop more easily ? i know it is not a
> good
> >
> > question - my apologies
> >
>
> I don't think it's a bad question. One answer is to keep the 3 largest
> values in a heap starting with the first three in the sequence.
> Then remove the smallest value and insert the current value from the
> iteration whenever it is larger than the smallest value in the heap.
>
> See the source and docs for the heapq.nlargest() function for a detailed
> explanation. If the current implementation looks too complicated start
> with an older version (before 3.5) of the module where nlargest()
> doesn't accept a 'key' parameter.
>
> https://docs.python.org/3/library/heapq.html#heapq.nlargest
> https://docs.python.org/3/library/heapq.html#theory
>
> PS: Here's an implementation that uses a sorted list to keep the largest
> n items:
>
>  >>> def nlargest(n, items):
>         items = iter(items)
>         result = sorted(islice(items, n))
>         for item in items:
>                 if item > result[0]:
>                         result[0] = item
>                         result.sort()
>         return result
>
>  >>> from itertools import islice
>  >>> from random import shuffle
>  >>> items = list(range(10))
>  >>> shuffle(items)
>  >>> items
> [1, 0, 9, 3, 4, 6, 7, 5, 2, 8]
>  >>> nlargest(3, items)
> [7, 8, 9]
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From __peter__ at web.de  Mon Feb 21 09:13:12 2022
From: __peter__ at web.de (Peter Otten)
Date: Mon, 21 Feb 2022 15:13:12 +0100
Subject: [Tutor] Getting greatest 3 numbers from list
In-Reply-To: <CAO1OCwb2tXt-j0_Jg0quUQsdRJOvz3tON+PYWZfGeSefk=KOhg@mail.gmail.com>
References: <CAO1OCwaeHiQQ6MGWt86V-2nRYmH2m+gB4icPCadOODTUWrk7+g@mail.gmail.com>
 <ca9cb851-d0f8-5a7a-63f2-0e623c334d47@web.de>
 <CAO1OCwb2tXt-j0_Jg0quUQsdRJOvz3tON+PYWZfGeSefk=KOhg@mail.gmail.com>
Message-ID: <888a5d99-6b4f-8680-e33b-88a146f63d81@web.de>

On 21/02/2022 14:46, Manprit Singh wrote:
> Dear Sir ,
>
> This is not related to python, but a general question, in c++ we have sets
> in standard template library and iterators, and sets are basically sorted,
> So doing the same problem in c++ using sets is a bad idea ?
>
> #include<iostream>
> #include<set>
> #include<functional>
> using namespace std;
>
> int main()
> {
>      int arry[6] = {2, 4, 9, 2, 4, 1};
>      set<int> second(arry, arry+6);
>      auto itr = second.end();
>      itr--;
>      auto greatest = *itr;
>      itr--;
>      auto seclargest = *itr;
>      itr--;
>      auto thirdlargest = *itr;
>      cout << greatest << " " << seclargest << " "<<thirdlargest;
>      return 0;
> }
>
> Gives the right answer
>
> My apologies for posting c++ code if it is against the rule of python
> mailing list

Well, don't make it a habit ;)

I suppose the above is roughly equivalent to

 >>> sorted(set([2, 4, 9, 2, 4, 1]))[-3:]
[2, 4, 9]

This produces different results when the list contains duplicates:

 >>> items = [1, 2, 3, 3, 2, 1]
 >>> sorted(set(items))[-3:]
[1, 2, 3]
 >>> sorted(items)[-3:]
[2, 3, 3]

Also, can the C++ code cope with input consisting of less than three
different values?

Finally, when you pick a complex tool like C++ you usually want
something algorithmically efficient -- which reminds me of the heap I
mentioned above...

From __peter__ at web.de  Mon Feb 21 09:13:12 2022
From: __peter__ at web.de (Peter Otten)
Date: Mon, 21 Feb 2022 15:13:12 +0100
Subject: [Tutor] Getting greatest 3 numbers from list
In-Reply-To: <CAO1OCwb2tXt-j0_Jg0quUQsdRJOvz3tON+PYWZfGeSefk=KOhg@mail.gmail.com>
References: <CAO1OCwaeHiQQ6MGWt86V-2nRYmH2m+gB4icPCadOODTUWrk7+g@mail.gmail.com>
 <ca9cb851-d0f8-5a7a-63f2-0e623c334d47@web.de>
 <CAO1OCwb2tXt-j0_Jg0quUQsdRJOvz3tON+PYWZfGeSefk=KOhg@mail.gmail.com>
Message-ID: <888a5d99-6b4f-8680-e33b-88a146f63d81@web.de>

On 21/02/2022 14:46, Manprit Singh wrote:
> Dear Sir ,
> 
> This is not related to python, but a general question, in c++ we have sets
> in standard template library and iterators, and sets are basically sorted,
> So doing the same problem in c++ using sets is a bad idea ?
> 
> #include<iostream>
> #include<set>
> #include<functional>
> using namespace std;
> 
> int main()
> {
>      int arry[6] = {2, 4, 9, 2, 4, 1};
>      set<int> second(arry, arry+6);
>      auto itr = second.end();
>      itr--;
>      auto greatest = *itr;
>      itr--;
>      auto seclargest = *itr;
>      itr--;
>      auto thirdlargest = *itr;
>      cout << greatest << " " << seclargest << " "<<thirdlargest;
>      return 0;
> }
> 
> Gives the right answer
> 
> My apologies for posting c++ code if it is against the rule of python
> mailing list

Well, don't make it a habit ;)

I suppose the above is roughly equivalent to

 >>> sorted(set([2, 4, 9, 2, 4, 1]))[-3:]
[2, 4, 9]

This produces different results when the list contains duplicates:

 >>> items = [1, 2, 3, 3, 2, 1]
 >>> sorted(set(items))[-3:]
[1, 2, 3]
 >>> sorted(items)[-3:]
[2, 3, 3]

Also, can the C++ code cope with input consisting of less than three 
different values?

Finally, when you pick a complex tool like C++ you usually want 
something algorithmically efficient -- which reminds me of the heap I 
mentioned above...


From alan.gauld at yahoo.co.uk  Mon Feb 21 09:35:31 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 21 Feb 2022 14:35:31 +0000
Subject: [Tutor] Getting greatest 3 numbers from list
In-Reply-To: <CAO1OCwb2tXt-j0_Jg0quUQsdRJOvz3tON+PYWZfGeSefk=KOhg@mail.gmail.com>
References: <CAO1OCwaeHiQQ6MGWt86V-2nRYmH2m+gB4icPCadOODTUWrk7+g@mail.gmail.com>
 <ca9cb851-d0f8-5a7a-63f2-0e623c334d47@web.de>
 <CAO1OCwb2tXt-j0_Jg0quUQsdRJOvz3tON+PYWZfGeSefk=KOhg@mail.gmail.com>
Message-ID: <sv07vl$3s4$1@ciao.gmane.io>

On 21/02/2022 13:46, Manprit Singh wrote:

> This is not related to python, but a general question, in c++ we have sets
> in standard template library and iterators, and sets are basically sorted,
> So doing the same problem in c++ using sets is a bad idea ?

No, it would seem to be an excellent idea, taking advantage
of a feature of the standard library.

> My apologies for posting c++ code if it is against the rule of python
> mailing list

It's allowed for comparison purposes or if you have a problem
interfacing C++ with Python. But be aware that most readers
probably won't be able to understand it and even fewer will
be in a position to offer meaningful critique.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From bossladyofthefuture at gmail.com  Mon Feb 21 16:04:54 2022
From: bossladyofthefuture at gmail.com (Fatima Mehak)
Date: Mon, 21 Feb 2022 15:04:54 -0600
Subject: [Tutor] Fwd: You know python?
In-Reply-To: <CAMDQkAfAWvOgU09spzt07DSTgRr_ZLykwuq7uv7nwsMQwprqFw@mail.gmail.com>
References: <CAMDQkAfAWvOgU09spzt07DSTgRr_ZLykwuq7uv7nwsMQwprqFw@mail.gmail.com>
Message-ID: <CAMDQkAfaYzc1=50CxigWC+g=F1=veFb7ufD1omU3Jgox=Dmc+Q@mail.gmail.com>

Let me know if you know how to fix the code below to include house numbers
without generating a whole new code altogether. When I got it done it
didn't include the house numbers but included the street names only. I hope
I'm making coding sense here. Thanks.

def format_address(address_string):
# Declare variables
house_no = ""
street_no = ""
# Separate the address string into parts
sep_addr = address_string.split()
# Traverse through the address parts
for addr in sep_addr:
# Determine if the address part is the
if addr.isdigit():
house_no = addr
else:
street_no = street_no+addr
street_no = street_no + " "
# house number or part of the street name
# Does anything else need to be done
# before returning the result?
# Return the formatted string
return "house number {} on street named {}".format(house_no,street_no)
print(format_address("123 Main Street"))
# Should print: "house number 123 on street named Main Street"
print(format_address("1001 1st Ave"))
# Should print: "house number 1001 on street named 1st Ave"
print(format_address("55 North Center Drive"))
# Should print "house number 55 on street named North Center Drive"

From wlfraed at ix.netcom.com  Tue Feb 22 14:11:14 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Tue, 22 Feb 2022 14:11:14 -0500
Subject: [Tutor] Fwd: You know python?
References: <CAMDQkAfAWvOgU09spzt07DSTgRr_ZLykwuq7uv7nwsMQwprqFw@mail.gmail.com>
 <CAMDQkAfaYzc1=50CxigWC+g=F1=veFb7ufD1omU3Jgox=Dmc+Q@mail.gmail.com>
Message-ID: <qaba1htmfktbhnbujfcrf88b6qevfo20rk@4ax.com>

On Mon, 21 Feb 2022 15:04:54 -0600, Fatima Mehak
<bossladyofthefuture at gmail.com> declaimed the following:

>Let me know if you know how to fix the code below to include house numbers
>without generating a whole new code altogether. When I got it done it
>didn't include the house numbers but included the street names only. I hope
>I'm making coding sense here. Thanks.
>

	Please post with a client that doesn't trash indentation. Indentation
is critical in Python, and what got sent by your client is invalid.

>def format_address(address_string):
># Declare variables
>house_no = ""
>street_no = ""

	First: one does not "declare variables" in Python. You've created two
empty strings, and bound names to those strings (Python attaches names to
objects, names don't represent some address in memory into which objects
get placed). It is also common to use None rather than empty strings to
indicate something that doesn't (yet) have a value.

	Second: "street_no" is misleading if it is supposed to be a street NAME
(to many of us, street NUMBER and house number would be the same --
ignoring the confusion of things like "4 Mile Road").

># Separate the address string into parts
>sep_addr = address_string.split()
># Traverse through the address parts
>for addr in sep_addr:
># Determine if the address part is the
>if addr.isdigit():
>house_no = addr
>else:
>street_no = street_no+addr
>street_no = street_no + " "

	The above loop and conditional will take

		123 some 99 street

and first bind "house_no" to 123; second pass will add "some" to an empty
string and bind "street_no" to it; third pass will bind "house_no" to 99
completely losing the 123 value; fourth pass will add "street" to the
previous "some". The end result is

		99
		some street

	IS THAT WHAT IS DESIRED? Or is the "house number" presumed to be the
first item on the input IF and ONLY IF it is all numeric? If so, there is
no need for a loop: the first "word" either is or is not a house number,
and the street name is everything that is not a house number -- just
.join() with space separator.


># house number or part of the street name
># Does anything else need to be done
># before returning the result?

	It's your problem -- does it do what your description says it is
supposed to do?

># Return the formatted string
>return "house number {} on street named {}".format(house_no,street_no)
>print(format_address("123 Main Street"))
># Should print: "house number 123 on street named Main Street"
>print(format_address("1001 1st Ave"))
># Should print: "house number 1001 on street named 1st Ave"
>print(format_address("55 North Center Drive"))
># Should print "house number 55 on street named North Center Drive"


>>> parse_address("123 Main Street")
'House number 123 on street named Main Street'
>>> parse_address("1001 1st Ave")
'House number 1001 on street named 1st Ave'
>>> parse_address("55 North Center Drive")
'House number 55 on street named North Center Drive'
>>> parse_address("28th Street SE")
'House number None on street named 28th Street SE'
>>> parse_address("4 Mile Road")
'House number 4 on street named Mile Road'
>>> 

	Obviously my function has no way of knowing that the last one is
supposed to be a street called "4 Mile Road"

	There is NO LOOP in my function. There is a .split(), a .isdigit() test
(if True it binds house_number and removes the first word from the split),
and a .join() operation to combine the street name parts.

>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>To unsubscribe or change subscription options:
>https://mail.python.org/mailman/listinfo/tutor


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From alan.gauld at yahoo.co.uk  Tue Feb 22 14:32:46 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Tue, 22 Feb 2022 19:32:46 +0000
Subject: [Tutor] Fwd: You know python?
In-Reply-To: <CAMDQkAfaYzc1=50CxigWC+g=F1=veFb7ufD1omU3Jgox=Dmc+Q@mail.gmail.com>
References: <CAMDQkAfAWvOgU09spzt07DSTgRr_ZLykwuq7uv7nwsMQwprqFw@mail.gmail.com>
 <CAMDQkAfaYzc1=50CxigWC+g=F1=veFb7ufD1omU3Jgox=Dmc+Q@mail.gmail.com>
Message-ID: <sv3dov$4p5$1@ciao.gmane.io>

On 21/02/2022 21:04, Fatima Mehak wrote:
> Let me know if you know how to fix the code below to include house numbers
> without generating a whole new code altogether. When I got it done it
> didn't include the house numbers but included the street names only. I hope
> I'm making coding sense here. Thanks.

Your code lost all indentation, be sure to post in plain text.
I'll try to guess what it might look like and remove some
of the irrelevant bits...

> def format_address(address_string):
>    sep_addr = address_string.split()
>    for addr in sep_addr:
>        if addr.isdigit():
>           house_no = addr
>        else:
>           street_name += addr
>           street_name += " "
            # Or replace above lines with:
            # street_name = "{} {}".format(streetname, addr)
> >    return "house number {} on street named {}".format(house_no,street_no)

Perhaps a better way still is to only use the first field for the house
Then use join() to put the subsequent fields in a string. Thus replace
the whole for loop with:

if sep_addr[0].isdigit(): house_no = sep_address[0]
else: house_no = ""
street_name = " ".join(sep.addr[1:])

I hope I guessed right and I hope my suggestions make sense.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From kp64junk at gmail.com  Tue Feb 22 18:27:31 2022
From: kp64junk at gmail.com (hs ghs)
Date: Tue, 22 Feb 2022 23:27:31 +0000
Subject: [Tutor] Python Error Message
Message-ID: <CA+ky=GQf3QrKyGS7g+kSpjLR=W0v96iWMBq5SmGUDkgAK2uO7w@mail.gmail.com>

Hi, I've just upgraded to Python 3 and now when I try to run scripts that
use tkinter I get the following error message:-

_tkinter.TclError: error getting working directory name: not owner

The error is when I run the scripts using IDLE. When I run from the.
terminal they are fine.

All this is being done on a Mac.

Any help gratefully received. Oh, and I am very much a computer novice so
please keep it very simple.

Thanks.

From phillor9 at gmail.com  Tue Feb 22 19:11:40 2022
From: phillor9 at gmail.com (Phil)
Date: Wed, 23 Feb 2022 11:11:40 +1100
Subject: [Tutor] Tkinter grid manager
Message-ID: <bd39e3c1-e112-64dd-c95f-0133b03f472d@gmail.com>

I think I've misunderstood the purpose of the grid manager. The pack 
manager does exactly what I have in mind, but I'll continue with my 
question anyway.

Looking at the following abbreviated code, the "on" and "off" buttons 
are always located on row 0 and column 0 no matter what the row and 
column settings are. Adding a third button means that I can now locate a 
button on column 3, which does make sense. Excessive use of padx and 
pady does place the buttons where I'd like them but I don't think that's 
the correct use of the grid manager.

I'd like to locate the "on" and "off" buttons at the bottom right corner 
of the frame and the pack manager does that so I suppose the pack 
manager is the correct choice in this instance. I think the grid manager 
is more suited to placing a label beside a widget rather that the exact 
placement of a widget.

import tkinter as tk


class Root(tk.Tk):
 ??? def __init__(self):
 ??????? super().__init__()
 ??????? self.title("Template")
 ??????? self.geometry("300x200")

 ??????? self.frame = tk.Frame(bg='light blue')

 ??????? self.frame.grid(row=0, column=0, sticky='nsew')??? # I found 
that I had to add these lines so that
 ??????? self.grid_rowconfigure(0, weight = 1) ?? # the frame would fill 
the main window.
 ??????? self.grid_columnconfigure(0, weight = 1)??? ??? ??? ???? # 
Could there be a problem here?

 ??????? self.create_widgets()

 ??? def create_widgets(self):

 ??????? self.on_button = tk.Button(self.frame,
 ????????????????????????????????? text="On",
 ????????????????????????????????? command=self.on_on_button_press)

 ??????? self.off_button = tk.Button(self.frame,
 ?????????????????????????????????? text="Off",
command=self.on_off_button_press)

 ??????? self.on_button.grid(row=5, column=0, padx=10, pady=10) # row 
can be any value, the result is
 ??????? self.off_button.grid(row=5, column=1, padx=10, pady=10) # 
always row 0.

 ??????? self.another_button = tk.Button(self.frame,
 ?????????????????????????????????? text="another")

 ??????? self.another_button.grid(row=8, column=3, padx=0, pady=60)


 ??? def on_on_button_press(self):
 ??????? print('on')

 ??? def on_off_button_press(self):
 ??????? print('off')

if __name__ == "__main__":
 ??? root = Root()
 ??? root.mainloop()

-- 
Regards,
Phil


From alan.gauld at yahoo.co.uk  Tue Feb 22 19:31:59 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 23 Feb 2022 00:31:59 +0000
Subject: [Tutor] Python Error Message
In-Reply-To: <CA+ky=GQf3QrKyGS7g+kSpjLR=W0v96iWMBq5SmGUDkgAK2uO7w@mail.gmail.com>
References: <CA+ky=GQf3QrKyGS7g+kSpjLR=W0v96iWMBq5SmGUDkgAK2uO7w@mail.gmail.com>
Message-ID: <sv3va2$p6v$1@ciao.gmane.io>

On 22/02/2022 23:27, hs ghs wrote:
> Hi, I've just upgraded to Python 3 and now when I try to run scripts that
> use tkinter I get the following error message:-
> 
> _tkinter.TclError: error getting working directory name: not owner

Can you post a short piece of example code that gives the error.
Its much easier to debug real code than hypothetical.

Also if you have any more to the error message please post
it in its entirety. They usually contain quite a lot of
useful data.

> The error is when I run the scripts using IDLE. When I run from the.
> terminal they are fine.
> 
> All this is being done on a Mac.

I'm not currently a Mac user so I'll refrain on making any guesses.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Tue Feb 22 19:45:39 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 23 Feb 2022 00:45:39 +0000
Subject: [Tutor] Tkinter grid manager
In-Reply-To: <bd39e3c1-e112-64dd-c95f-0133b03f472d@gmail.com>
References: <bd39e3c1-e112-64dd-c95f-0133b03f472d@gmail.com>
Message-ID: <sv403m$ltt$1@ciao.gmane.io>

On 23/02/2022 00:11, Phil wrote:
> I think I've misunderstood the purpose of the grid manager. 

Its purpose is quite simple, to put widgets into boxes
in a grid. The grid can be as big or little as needed.

> The pack manager does exactly what I have in mind, 

It's very common to use both in the same app.
pack is great for positioning the bigger panels/frames
within your overall app. grid is great for positioning
widgets within a frame or panel.

> Looking at the following abbreviated code, the "on" and "off" buttons 
> are always located on row 0 and column 0 no matter what the row and 
> column settings are. 

They shouldn't be. And its very unusual to position two
widgets in the same grid cell!

> Adding a third button means that I can now locate a 
> button on column 3, which does make sense. 

> pady does place the buttons where I'd like them but I don't think that's 
> the correct use of the grid manager.

Almost certainly not.

> I'd like to locate the "on" and "off" buttons at the bottom right corner 

So the columns should be N-1 and N respectively
And the row should be M.
for an MxN grid.
The cells number from top-left to bottom-right.

> is more suited to placing a label beside a widget rather that the exact 
> placement of a widget.

Neither Pack nor grid are good at exact placement, for that you
use the place() manager. But only if you turn of resizing of
your app, otherwise it will all go horribly wrong very quickly.
Both pack() and grid() provide relative placement which is
dynamically calculated as the window is moved/resized.
You can also use the form() manager which is specifically
designed for building business app style forms and dialogs
with label/entry pairs etc. (but I confess I've never used
it beyond following a tutorial)

> import tkinter as tk
> 
> 
> class Root(tk.Tk):
>  ??? def __init__(self):
>  ??????? super().__init__()
>  ??????? self.title("Template")
>  ??????? self.geometry("300x200")
> 
>  ??????? self.frame = tk.Frame(bg='light blue')
> 
>  ??????? self.frame.grid(row=0, column=0, sticky='nsew')??? # I found 
> that I had to add these lines so that
>  ??????? self.grid_rowconfigure(0, weight = 1) ?? # the frame would fill 
> the main window.
>  ??????? self.grid_columnconfigure(0, weight = 1)??? ??? ??? ???? # 
> Could there be a problem here?

You are basically creating a single frame widget that fills
the main window, so I'd probably just use pack() here and
fill/expand the widget to fill the window.

Then you can use grid to manage the widgets inside the frame
if you wish.


>  ??????? self.create_widgets()
> 
>  ??? def create_widgets(self):
> 
>  ??????? self.on_button = tk.Button(self.frame,
>  ????????????????????????????????? text="On",
>  ????????????????????????????????? command=self.on_on_button_press)
> 
>  ??????? self.off_button = tk.Button(self.frame,
>  ?????????????????????????????????? text="Off",
> command=self.on_off_button_press)
> 
>  ??????? self.on_button.grid(row=5, column=0, padx=10, pady=10) # row 
> can be any value, the result is
>  ??????? self.off_button.grid(row=5, column=1, padx=10, pady=10) # 
> always row 0.

That should put the two buttons in the bottom-left corner.


> 
>  ??????? self.another_button = tk.Button(self.frame,
>  ?????????????????????????????????? text="another")
> 
>  ??????? self.another_button.grid(row=8, column=3, padx=0, pady=60)

But this will now be below them.

But notice you don't have anything in rows 0-4 or 6 and 7.
Thus the grid will be empty and it will look like you only
have 2 rows, with on/off on the top one and another on the
bottom. An empty row has no size.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From phillor9 at gmail.com  Tue Feb 22 19:56:08 2022
From: phillor9 at gmail.com (Phil)
Date: Wed, 23 Feb 2022 11:56:08 +1100
Subject: [Tutor] Tkinter grid manager
In-Reply-To: <sv403m$ltt$1@ciao.gmane.io>
References: <bd39e3c1-e112-64dd-c95f-0133b03f472d@gmail.com>
 <sv403m$ltt$1@ciao.gmane.io>
Message-ID: <9ff5a55b-a047-6f80-4a86-c169f22faed9@gmail.com>


On 23/2/22 11:45, Alan Gauld via Tutor wrote:

Thank you Alan for your detailed reply, you've given me something to 
think about.
>
> An empty row has no size.

I was wondering about some sort of sizer that could be placed in a cell 
but not be visible?

-- 

Regards,
Phil


From __peter__ at web.de  Wed Feb 23 04:37:18 2022
From: __peter__ at web.de (Peter Otten)
Date: Wed, 23 Feb 2022 10:37:18 +0100
Subject: [Tutor] Tkinter grid manager
In-Reply-To: <9ff5a55b-a047-6f80-4a86-c169f22faed9@gmail.com>
References: <bd39e3c1-e112-64dd-c95f-0133b03f472d@gmail.com>
 <sv403m$ltt$1@ciao.gmane.io> <9ff5a55b-a047-6f80-4a86-c169f22faed9@gmail.com>
Message-ID: <3831a517-c2fe-4d4e-b549-af891fd96088@web.de>

On 23/02/2022 01:56, Phil wrote:
>
> On 23/2/22 11:45, Alan Gauld via Tutor wrote:
>
> Thank you Alan for your detailed reply, you've given me something to
> think about.
>>
>> An empty row has no size.
>
> I was wondering about some sort of sizer that could be placed in a cell
> but not be visible?
>

You can define the minimum size of a row/column, or you can give the
row/column a weight to have it consume all or some extra space. I prefer
the latter.

import tkinter as tk

root = tk.Tk()
for row in (0, 2):
     for column in (0, 2):
         button = tk.Button(root, text=f"{column=}/{row=}")
         button.grid(row=row, column=column)

# row 1 will be at least 200 units high
root.rowconfigure(1, minsize=200)

# column 1 will consume any extra space
root.columnconfigure(1, weight=1)

root.geometry("400x200")
root.mainloop()

From alan.gauld at yahoo.co.uk  Wed Feb 23 09:54:40 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 23 Feb 2022 14:54:40 +0000
Subject: [Tutor] Tkinter grid manager
In-Reply-To: <9ff5a55b-a047-6f80-4a86-c169f22faed9@gmail.com>
References: <bd39e3c1-e112-64dd-c95f-0133b03f472d@gmail.com>
 <sv403m$ltt$1@ciao.gmane.io> <9ff5a55b-a047-6f80-4a86-c169f22faed9@gmail.com>
Message-ID: <sv5hrj$ars$1@ciao.gmane.io>

On 23/02/2022 00:56, Phil wrote:

>> An empty row has no size.
> 
> I was wondering about some sort of sizer that could be placed in a cell 
> but not be visible?
> 
Anything in the cell(an empty label, frame or panel) will fill it and
you can configure the row height as needed.

But why do you have empty rows to start with? What purpose do the
empty cells have? If it is just blank space you require then any
empty widget will do the trick. Or if you are going to put other
widgets in there later an empty frame might be best, then you
can insert the new widgets into the frame.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alexkleider at gmail.com  Wed Feb 23 14:37:59 2022
From: alexkleider at gmail.com (Alex Kleider)
Date: Wed, 23 Feb 2022 11:37:59 -0800
Subject: [Tutor] problem with back slash
Message-ID: <CAMCEyD7Z=CS2bsVRmGHX7ooNpaAnYket3oGke=_f5CwOX4VHSQ@mail.gmail.com>

I've written myself a little utility that accepts a text file which
might have very long lines and returns a file with the same text but
(as much as possible) with the lines no longer than MAX_LEN
characters. (I've chosen 70.)
It seems to work except when the the source file contains back
slashes! (Presence of a back slash appears to cause the program
to go into an endless loop.)
I've tried converting to raw strings but to no avail.

Here's the code, followed by an example source file.

'''
#!/usr/bin/env python3
# file: limit_line_length.py
"""
Accepts a text file and tries to shorten lines to MAX characters.
First parameter must be a file name.
Optional second parameter can be the output file's name.
If 2nd param is not specified, output will go to "new_<1stParam>".
"""

import sys

MAX = 70


def split_on_space_closest_to_max_len(line, max_len=MAX):
    """
    Returns a tuple of two (possibly empty) strings.
    If the line is <= <max_len>: it is returned as t[0] & t[1] as ''.
    If indented beyond <max_len> t[0] as '' & t[1] as line[max_len:]
    If there are no spaces then t[0] as <line> and t[1] as ''.
    If the first space is beyond <max_len>: t[0] is what is up to the
    space and t[1] what was after the space.
    Otherwise t[0] is the longest it can be up to max_len up to a
    space and t[1] is what comes after the space.
    Trailing spaces are stripped.
    """
    line = line.rstrip()
    line_length = len(line)
    if line_length <= max_len:  # simplest scenario
        return (line, '')       # empty lines included
    original_line = line[:]
    unindented_line = line.lstrip()
    n_leading_spaces = line_length - len(unindented_line)
    if n_leading_spaces > max_len:  # big indentation!!!
        return ('', line[max_len:])
    indentation = ' ' * n_leading_spaces
    max_len -= n_leading_spaces
    i_last_space = unindented_line.rfind(' ')
    if i_last_space == -1:  # no spaces on which to split
        return (line, '')
    i_space = unindented_line.find(' ')
    if i_space > max_len:
        return (indentation + unindented_line[:i_space],
                unindented_line[i_space+1])
    while True:
        next_space = unindented_line.find(' ', i_space+1)
        if next_space > max_len: break
        else: i_space =next_space
    return (indentation + unindented_line[:i_space],
            unindented_line[i_space +1:])

args = sys.argv
arglen = len(args)
infile = args[1]
if arglen > 2: dest_file = args[2]
else: dest_file = "new_{}".format(infile)
with open(infile, 'r') as source:
    with open(dest_file, 'w') as dest:
        for line in source:
#           line = repr(line.rstrip())
            print("line: '{}'".format(line))  # for debugging
            while line:
                line2write, line = split_on_space_closest_to_max_len(
                        line)
                print("writing: '{}'".format(line2write))  # for debugging
                print("remaining: '{}'".format(line))  # for debugging
#               dest.write(repr(line2write) + '\n')
                dest.write(line2write + '\n')
'''

Example text file:
"""
https://superuser.com/questions/1313241/install-windows-10-from-an-unbooted-oem-drive-into-virtualbox/1329935#1329935

You can activate Windows 10 using the product key for your hardware which
is embedded in the BIOS in an ACPI table called MSDM (Microsoft Data
Management). You can get it like this (from Linux, of course!):

$ sudo tail -c +56 /sys/firmware/acpi/tables/MSDM
ABA2D-TEFJ4-D97PT-9B42Y-H3U5E

You can apply the OEM Windows license to a VirtualBox guest like this (from
the Linux host - assuming VM is called win10):

$ sudo cat /sys/firmware/acpi/tables/MSDM > ~/VirtualBox\ VMs/win10/msdm.bin
$ VBoxManage setextradata win10 \
               "VBoxInternal/Devices/acpi/0/Config/CustomTable" \
               ~/VirtualBox\ VMs/win10/msdm.bin

With that in place, Windows will not ask for a product key during
installation, it will activate automatically. If you want to verify that it
does indeed use the correct key you can use a tool like ShowKeyPlus to
check it. You can read about ShowKeyPlus on TenForums or download it here.
"""

Thanks in advance for any advice.
PS Running Python 10 within virtualenvwrapper on Debian/11.

From marcus.luetolf at bluewin.ch  Wed Feb 23 15:11:56 2022
From: marcus.luetolf at bluewin.ch (marcus.luetolf at bluewin.ch)
Date: Wed, 23 Feb 2022 21:11:56 +0100
Subject: [Tutor] dealing with lists
Message-ID: <000001d828f1$9e890980$db9b1c80$@bluewin.ch>

Hello Experts, 

I try to solve the following problem:

 

I'd like to create  5 lists, each containing 4 sublists : f1, f2, f3, f4,
f5, a total of 20 sublists.

I have a list (named all_letters) contaning 16 characters a, b, c, ...p.

 

I  would liketo  distribute all 16 characters to the 4 sublists 5 times in 5
iterations respectivly  so that

as a condition a pair of characters, p.e. ['a', 'b', .]  or ['a', 'c'.] or
['n', 'p' .] can appear only once in all 20 sublists.

 

To find the sublists fullfilling this condition I designed the following
code with the intention to change the indices

defined by the variables n and p til the condition is met :

 

all_letters = list('abcdefghijklmnop')

f1 = []

f2 = []

f3 = []

f4 = []

n = 0

p = 1

for dummy_i in range(5):  

    copy_all_letters = all_letters[:]

    lst = 16*copy_all_letters

    f1.append(lst[n+0])

    f1.append(lst[n+p])

    f1.append(lst[n+2*p])

    f1.append(lst[n+3*p])

    f1.sort()

    f2.append(lst[n+4*p])

    f2.append(lst[n+5*p])

    f2.append(lst[n+6*p])

    f2.append(lst[n+7*p])

    f2.sort()

    f3.append(lst[n+8*p])

    f3.append(lst[n+9*p])

    f3.append(lst[n+10*p])

    f3.append(lst[n+11*p])

    f3.sort()

    f4.append(lst[n+12*p])

    f4.append(lst[n+13*p])

    f4.append(lst[n+14*p])

    f4.append(lst[n+15*p])

    f4.sort()

       

    print('f1: ', f1)

    print('f2: ', f2)

    print('f3: ', f3)

    print('f4: ', f4)

    n += 4

    p += 1

    f1 = []

    f2 = []

    f3 = []

    f4 = []

    f5 = []

 

But I'm unable to define the condition mentioned above and asking for your
help.

 

 

 

 

 

.


From mats at wichmann.us  Wed Feb 23 15:40:54 2022
From: mats at wichmann.us (Mats Wichmann)
Date: Wed, 23 Feb 2022 13:40:54 -0700
Subject: [Tutor] problem with back slash
In-Reply-To: <CAMCEyD7Z=CS2bsVRmGHX7ooNpaAnYket3oGke=_f5CwOX4VHSQ@mail.gmail.com>
References: <CAMCEyD7Z=CS2bsVRmGHX7ooNpaAnYket3oGke=_f5CwOX4VHSQ@mail.gmail.com>
Message-ID: <982d6eff-fe0f-3920-350a-28914e35d247@wichmann.us>

On 2/23/22 12:37, Alex Kleider wrote:
> I've written myself a little utility that accepts a text file which
> might have very long lines and returns a file with the same text but
> (as much as possible) with the lines no longer than MAX_LEN
> characters. (I've chosen 70.)
> It seems to work except when the the source file contains back
> slashes! (Presence of a back slash appears to cause the program
> to go into an endless loop.)
> I've tried converting to raw strings but to no avail.

If you just want to solve the problem, see the textwrap module from the
standard library.

I'm sure someone will look at and make comments on the code...



From alan.gauld at yahoo.co.uk  Wed Feb 23 17:21:56 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 23 Feb 2022 22:21:56 +0000
Subject: [Tutor] dealing with lists
In-Reply-To: <000001d828f1$9e890980$db9b1c80$@bluewin.ch>
References: <000001d828f1$9e890980$db9b1c80$@bluewin.ch>
Message-ID: <sv6c24$c32$1@ciao.gmane.io>

On 23/02/2022 20:11, marcus.luetolf at bluewin.ch wrote:

> I'd like to create  5 lists, each containing 4 sublists : f1, f2, f3, f4,
> f5, a total of 20 sublists.

That's not what your code below does. It only creates the 4 sublists.
But then it throws them away and creates another 4 and starts again.

> I have a list (named all_letters) contaning 16 characters a, b, c, ...p.
> 
> I  would liketo  distribute all 16 characters to the 4 sublists 5 times in 5
> iterations respectivly  so that as a condition a pair of characters, 
> p.e. ['a', 'b', .]  or ['a', 'c'.] or ['n', 'p' .] can appear only once 
> in all 20 sublists.

You can probably use some of the python modules to do that
for you as a set of combinations or permutations or whatever
you actually want.

> To find the sublists fullfilling this condition I designed the following
> code with the intention to change the indices
> defined by the variables n and p til the condition is met :
> 
>  
> 
> all_letters = list('abcdefghijklmnop')
> 
> f1 = []
> 
> f2 = []
> 
> f3 = []
> 
> f4 = []

Why not just define these at the top of the function
so you only have to do it once?

> n = 0
> p = 1
> for dummy_i in range(5):  
>     copy_all_letters = all_letters[:]
>     lst = 16*copy_all_letters
> 
>     f1.append(lst[n+0])
>     f1.append(lst[n+p])
>     f1.append(lst[n+2*p])
>     f1.append(lst[n+3*p])
>     f1.sort()

You could do that all in one line:

f1 = sorted([ lst[n],lst[n+p],lst[n+2*p], lst[n+3*p] ])

...
>     f2.sort()
> 
...
>     f3.sort()
...>     f4.sort()

>     print('f1: ', f1)
>     print('f2: ', f2)
>     print('f3: ', f3)
>     print('f4: ', f4)
> 
>     n += 4
>     p += 1
> 
>     f1 = []
> 
>     f2 = []
> 
>     f3 = []
> 
>     f4 = []
> 
>     f5 = []

Where did f5 come from? You only build 4 lists?
And you've now thrown them away and are staring
from scratch with new indices.

> But I'm unable to define the condition mentioned 
> above and asking for your help.

I don't understand that comment. Can you be more
specific about what you expect and what you get?


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Wed Feb 23 17:31:52 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Wed, 23 Feb 2022 22:31:52 +0000
Subject: [Tutor] problem with back slash
In-Reply-To: <CAMCEyD7Z=CS2bsVRmGHX7ooNpaAnYket3oGke=_f5CwOX4VHSQ@mail.gmail.com>
References: <CAMCEyD7Z=CS2bsVRmGHX7ooNpaAnYket3oGke=_f5CwOX4VHSQ@mail.gmail.com>
Message-ID: <sv6cko$krc$1@ciao.gmane.io>

On 23/02/2022 19:37, Alex Kleider wrote:
> I've written myself a little utility that accepts a text file which
> might have very long lines and returns a file with the same text but
> (as much as possible) with the lines no longer than MAX_LEN
> characters. (I've chosen 70.)
> It seems to work except when the the source file contains back
> slashes! (Presence of a back slash appears to cause the program
> to go into an endless loop.)
> I've tried converting to raw strings but to no avail.
> 
> Here's the code, followed by an example source file.
> 
> '''
> #!/usr/bin/env python3
> # file: limit_line_length.py
> """
> Accepts a text file and tries to shorten lines to MAX characters.
> First parameter must be a file name.
> Optional second parameter can be the output file's name.
> If 2nd param is not specified, output will go to "new_<1stParam>".
> """
> 
> import sys
> 
> MAX = 70
> 
> 
> def split_on_space_closest_to_max_len(line, max_len=MAX):
>     """
>     Returns a tuple of two (possibly empty) strings.
>     If the line is <= <max_len>: it is returned as t[0] & t[1] as ''.
>     If indented beyond <max_len> t[0] as '' & t[1] as line[max_len:]
>     If there are no spaces then t[0] as <line> and t[1] as ''.
>     If the first space is beyond <max_len>: t[0] is what is up to the
>     space and t[1] what was after the space.
>     Otherwise t[0] is the longest it can be up to max_len up to a
>     space and t[1] is what comes after the space.
>     Trailing spaces are stripped.
>     """
>     line = line.rstrip()
>     line_length = len(line)
>     if line_length <= max_len:  # simplest scenario
>         return (line, '')       # empty lines included
>     original_line = line[:]
>     unindented_line = line.lstrip()
>     n_leading_spaces = line_length - len(unindented_line)
>     if n_leading_spaces > max_len:  # big indentation!!!
>         return ('', line[max_len:])
>     indentation = ' ' * n_leading_spaces
>     max_len -= n_leading_spaces
>     i_last_space = unindented_line.rfind(' ')
>     if i_last_space == -1:  # no spaces on which to split
>         return (line, '')
>     i_space = unindented_line.find(' ')
>     if i_space > max_len:
>         return (indentation + unindented_line[:i_space],
>                 unindented_line[i_space+1])

Missing colon on that line? See below for comparison...

>     while True:
>         next_space = unindented_line.find(' ', i_space+1)
>         if next_space > max_len: break
>         else: i_space =next_space

I think this loop could be replaced with a rfind()
on a slice upto max_space?

>     return (indentation + unindented_line[:i_space],
>             unindented_line[i_space +1:])

But I doubt that's the cause of the backslash issue.
And I have no idea what is. :-(

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From phillor9 at gmail.com  Wed Feb 23 18:07:04 2022
From: phillor9 at gmail.com (Phil)
Date: Thu, 24 Feb 2022 10:07:04 +1100
Subject: [Tutor] Tkinter grid manager
In-Reply-To: <3831a517-c2fe-4d4e-b549-af891fd96088@web.de>
References: <bd39e3c1-e112-64dd-c95f-0133b03f472d@gmail.com>
 <sv403m$ltt$1@ciao.gmane.io> <9ff5a55b-a047-6f80-4a86-c169f22faed9@gmail.com>
 <3831a517-c2fe-4d4e-b549-af891fd96088@web.de>
Message-ID: <77daae8c-13bd-a746-7a47-4c88849aa775@gmail.com>


On 23/2/22 20:37, Peter Otten wrote:

Thank you Peter and Alan.

> # column 1 will consume any extra space
> root.columnconfigure(1, weight=1)

I did experiment with this and I now see the error that I'd made; the 
wrong column.

The aim of this project was to build a template that I could use to 
build something semi-useful in the future. More a learning exercise at 
the moment than anything else.

What I did in this case was to shrink the height of the window rather 
than try to push the buttons to the bottom of the window.

-- 

Regards,
Phil


From cs at cskk.id.au  Wed Feb 23 16:41:36 2022
From: cs at cskk.id.au (Cameron Simpson)
Date: Thu, 24 Feb 2022 08:41:36 +1100
Subject: [Tutor] problem with back slash
In-Reply-To: <CAMCEyD7Z=CS2bsVRmGHX7ooNpaAnYket3oGke=_f5CwOX4VHSQ@mail.gmail.com>
References: <CAMCEyD7Z=CS2bsVRmGHX7ooNpaAnYket3oGke=_f5CwOX4VHSQ@mail.gmail.com>
Message-ID: <YhaqEOO21xosdwew@cskk.homeip.net>

On 23Feb2022 11:37, Alex Kleider <alexkleider at gmail.com> wrote:
>I've written myself a little utility that accepts a text file which
>might have very long lines and returns a file with the same text but
>(as much as possible) with the lines no longer than MAX_LEN
>characters. (I've chosen 70.)
>It seems to work except when the the source file contains back
>slashes! (Presence of a back slash appears to cause the program
>to go into an endless loop.)

There's _nothing_ in your code which cares about backslashes.

>I've tried converting to raw strings but to no avail.

I have no idea what you mean here - all the strings you're manipulating 
come from the text file. They're just "strings". A Python "raw string" 
is just a _syntactic_ way to express a string in a programme, eg:

    r'some regexp maybe \n foo'

After that's evaluated, it is just a string.

>Here's the code, followed by an example source file.

Thank you. This shows the bug. Here's me running it:

    [~/tmp/p1]fleet2*> py3 foo.py input.txt
    line: 'https://superuser.com/questions/1313241/install-windows-10-from-an-unbooted-oem-drive-into-virtualbox/1329935#1329935
    '
    writing: 'https://superuser.com/questions/1313241/install-windows-10-from-an-unbooted-oem-drive-into-virtualbox/1329935#1329935'
    remaining: ''
    line: '
    '
    writing: ''
    remaining: ''
    line: 'You can activate Windows 10 using the product key for your hardware which
    '

    ^CTraceback (most recent call last):
      File "/Users/cameron/tmp/p1/foo.py", line 63, in <module>
        line2write, line = split_on_space_closest_to_max_len(
      File "/Users/cameron/tmp/p1/foo.py", line 47, in 
    split_on_space_closest_to_max_len
        if next_space > max_len: break
    KeyboardInterrupt

It hung just before the traceback, where I interrupted it with ^C.

Now, that tells me where in the code it was - the programme is not hung, 
it is spinning. When interrupted it was in this loop:

    while True:
        next_space = unindented_line.find(' ', i_space+1)
        if next_space > max_len: break
        else: i_space =next_space

On the face of that loop should always advance i_space and therefore 
exit. But find() can return -1:

    >>> help(str.find)
    Help on method_descriptor:

    find(...)
        S.find(sub[, start[, end]]) -> int

        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.

i.e. when there is no space from the search point onward. So this could 
spin out. Let's see with modified code:

    print("LOOP1")
    while True:
        assert ' ' in unindented_line[i_space+1:], (
            "no space in unindented_line[i_space(%d)+1:]: %r"
            % (i_space, unindented_line[i_space+1:])
        )
        next_space = unindented_line.find(' ', i_space+1)
        if next_space > max_len: break
        else: i_space =next_space
    print("LOOP1 DONE")

thus:

    [~/tmp/p1]fleet2*> py3 foo.py input.txt
    line: 'https://superuser.com/questions/1313241/install-windows-10-from-an-unbooted-oem-drive-into-virtualbox/1329935#1329935
    '
    writing: 'https://superuser.com/questions/1313241/install-windows-10-from-an-unbooted-oem-drive-into-virtualbox/1329935#1329935'
    remaining: ''
    line: '
    '
    writing: ''
    remaining: ''
    line: 'You can activate Windows 10 using the product key for your hardware which
    '
    LOOP1
    Traceback (most recent call last):
      File "/Users/cameron/tmp/p1/foo.py", line 69, in <module>
        line2write, line = split_on_space_closest_to_max_len(
      File "/Users/cameron/tmp/p1/foo.py", line 47, in 
    split_on_space_closest_to_max_len
        assert ' ' in unindented_line[i_space+1:], (
    AssertionError: no space in unindented_line[i_space(67)+1:]: 'which'

As suspected. Commenting out the assert and printing next_space shows 
the cycle, with this code:

    print("LOOP1")
    while True:
        ##assert ' ' in unindented_line[i_space+1:], (
        ##    "no space in unindented_line[i_space(%d)+1:]: %r"
        ##    % (i_space, unindented_line[i_space+1:])
        ##)
        next_space = unindented_line.find(' ', i_space+1)
        print("next_space =", next_space)
        if next_space > max_len: break
        else: i_space =next_space
    print("LOOP1 DONE")

which outputs this:

    [~/tmp/p1]fleet2*> py3 foo.py input.txt 2>&1 | sed 50q
    line: 'https://superuser.com/questions/1313241/install-windows-10-from-an-unbooted-oem-drive-into-virtualbox/1329935#1329935
    '
    writing: 'https://superuser.com/questions/1313241/install-windows-10-from-an-unbooted-oem-drive-into-virtualbox/1329935#1329935'
    remaining: ''
    line: '
    '
    writing: ''
    remaining: ''
    line: 'You can activate Windows 10 using the product key for your hardware which
    '
    LOOP1
    next_space = 7
    next_space = 16
    next_space = 24
    next_space = 27
    next_space = 33
    next_space = 37
    next_space = 45
    next_space = 49
    next_space = 53
    next_space = 58
    next_space = 67
    next_space = -1
    next_space = 3
    next_space = 7
    next_space = 16
    next_space = 24
    next_space = 27
    next_space = 33

and so on indefinitely. You can see next_space reset to -1.

Which I'm here, some random remarks about the code:

>    original_line = line[:]

There's no need for this. Because strings are immutable, you can just 
go:

    original_line = line

All the other operations on "line" return new strings (because strings 
are immutable), leaving original_line untouched.

>    unindented_line = line.lstrip()
>    n_leading_spaces = line_length - len(unindented_line)
>    if n_leading_spaces > max_len:  # big indentation!!!
>        return ('', line[max_len:])
>    indentation = ' ' * n_leading_spaces

Isn't this also unindented_line[:n_leading_spaces]? I would be inclined 
to use that in case the whitespace isn't just spaces (eg TABs).  Because 
"line.lstrip()" strips leading whitespace, not leading spaces. This 
would preserve whetever was there.

Howvere your code is focussed on the space character, so maybe a more 
precise lstip() would be better:

    line.lstrip(' ')

stripping only space characters.

[...]
>    while True:
>        next_space = unindented_line.find(' ', i_space+1)
>        if next_space > max_len: break
>        else: i_space =next_space

A lot of us might write this:

    while True:
        next_space = unindented_line.find(' ', i_space+1)
        if next_space > max_len:
            break
        i_space =next_space

dropping the "else:". It is just style, but to my eye it is more clear 
that the "i_space =next_space" is an "uncodnitional" part of the normal 
loop iteration.

>        for line in source:
>#           line = repr(line.rstrip())

The commented out line above would damage "line" (by adding quotes and 
stuff to it), if uncommented.

>            print("line: '{}'".format(line))  # for debugging

You know you can just write?

    print("line:", line)

Cheers,
Cameron Simpson <cs at cskk.id.au>

From breamoreboy at gmail.com  Wed Feb 23 17:56:22 2022
From: breamoreboy at gmail.com (Mark Lawrence)
Date: Wed, 23 Feb 2022 22:56:22 +0000
Subject: [Tutor] dealing with lists
In-Reply-To: <sv6c24$c32$1@ciao.gmane.io>
References: <000001d828f1$9e890980$db9b1c80$@bluewin.ch>
 <sv6c24$c32$1@ciao.gmane.io>
Message-ID: <e3b7d3d7-75f8-a181-46d9-cc525476ce6f@gmail.com>

On 23/02/2022 22:21, Alan Gauld via Tutor wrote:
> On 23/02/2022 20:11, marcus.luetolf at bluewin.ch wrote:

[snipped to hell]

>>
>> I  would liketo  distribute all 16 characters to the 4 sublists 5 times in 5
>> iterations respectivly  so that as a condition a pair of characters,
>> p.e. ['a', 'b', .]  or ['a', 'c'.] or ['n', 'p' .] can appear only once
>> in all 20 sublists.
> 
> You can probably use some of the python modules to do that
> for you as a set of combinations or permutations or whatever
> you actually want.
> 

https://docs.python.org/3/library/itertools.html#itertools.combinations
https://docs.python.org/3/library/itertools.html#itertools.permutations

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence


From wlfraed at ix.netcom.com  Wed Feb 23 20:18:24 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Wed, 23 Feb 2022 20:18:24 -0500
Subject: [Tutor] problem with back slash
References: <CAMCEyD7Z=CS2bsVRmGHX7ooNpaAnYket3oGke=_f5CwOX4VHSQ@mail.gmail.com>
Message-ID: <cskd1h5vg7ck2i7iml4j94u688h0k71sa7@4ax.com>

On Wed, 23 Feb 2022 11:37:59 -0800, Alex Kleider <alexkleider at gmail.com>
declaimed the following:

>I've written myself a little utility that accepts a text file which
>might have very long lines and returns a file with the same text but
>(as much as possible) with the lines no longer than MAX_LEN
>characters. (I've chosen 70.)

	"\" would be a problem for string literals, but shouldn't matter for
text read from an external file.

	<SNIP>

	Seems rather complex to be working with individual lines. I'd probably
start with the standard library textwrap module, though you may need to add
some detection for indented lines to be handled special.

	Compare

"""
mport textwrap

with open("Example.txt", "r") as fin:
    with open("Output.txt", "w") as fout:
        paragraph = []
        for ln in fin:
            ln = ln.rstrip()
            paragraph.append(ln)
            if not ln:
                paragraph = " ".join(paragraph)
                paragraph = textwrap.fill(paragraph, width=50)
                fout.write("%s\n\n" % paragraph)
                paragraph = []

        if paragraph:
            paragraph = " ".join(paragraph)
            paragraph = textwrap.fill(paragraph, width=50)
            fout.write("%s\n\n" % paragraph)
"""
Input file
"""

https://superuser.com/questions/1313241/install-windows-10-from-an-unbooted-oem-drive-into-virtualbox/1329935#1329935

You can activate Windows 10 using the product key for your hardware which
is embedded in the BIOS in an ACPI table called MSDM (Microsoft Data
Management). You can get it like this (from Linux, of course!):

$ sudo tail -c +56 /sys/firmware/acpi/tables/MSDM
ABA2D-TEFJ4-D97PT-9B42Y-H3U5E

You can apply the OEM Windows license to a VirtualBox guest like this (from
the Linux host - assuming VM is called win10):

$ sudo cat /sys/firmware/acpi/tables/MSDM > ~/VirtualBox\
VMs/win10/msdm.bin
$ VBoxManage setextradata win10 \
               "VBoxInternal/Devices/acpi/0/Config/CustomTable" \
               ~/VirtualBox\ VMs/win10/msdm.bin

With that in place, Windows will not ask for a product key during
installation, it will activate automatically. If you want to verify that it
does indeed use the correct key you can use a tool like ShowKeyPlus to
check it. You can read about ShowKeyPlus on TenForums or download it here.
"""
Output file
"""


https://superuser.com/questions/1313241/install-
windows-10-from-an-unbooted-oem-drive-into-
virtualbox/1329935#1329935

You can activate Windows 10 using the product key
for your hardware which is embedded in the BIOS in
an ACPI table called MSDM (Microsoft Data
Management). You can get it like this (from Linux,
of course!):

$ sudo tail -c +56 /sys/firmware/acpi/tables/MSDM
ABA2D-TEFJ4-D97PT-9B42Y-H3U5E

You can apply the OEM Windows license to a
VirtualBox guest like this (from the Linux host -
assuming VM is called win10):

$ sudo cat /sys/firmware/acpi/tables/MSDM >
~/VirtualBox\ VMs/win10/msdm.bin $ VBoxManage
setextradata win10 \
"VBoxInternal/Devices/acpi/0/Config/CustomTable" \
~/VirtualBox\ VMs/win10/msdm.bin

With that in place, Windows will not ask for a
product key during installation, it will activate
automatically. If you want to verify that it does
indeed use the correct key you can use a tool like
ShowKeyPlus to check it. You can read about
ShowKeyPlus on TenForums or download it here.

"""





-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From alexkleider at gmail.com  Wed Feb 23 22:33:28 2022
From: alexkleider at gmail.com (Alex Kleider)
Date: Wed, 23 Feb 2022 19:33:28 -0800
Subject: [Tutor] problem with back slash
In-Reply-To: <YhaqEOO21xosdwew@cskk.homeip.net>
References: <CAMCEyD7Z=CS2bsVRmGHX7ooNpaAnYket3oGke=_f5CwOX4VHSQ@mail.gmail.com>
 <YhaqEOO21xosdwew@cskk.homeip.net>
Message-ID: <CAMCEyD4g0w34KQr5xA+q+HQufR1JucKQaj_9sQzAxZL46_k6vg@mail.gmail.com>

Thank you, Cameron, for pointing me in the correct direction- it's just
coincidence that the program failed on the line that happened to contain
backslashes!
Changing the conditional for the 'break' solved the problem:
        if (next_space == -1) or (next_space > max_len):
            break
And thank you for your other suggestions as well.

 Thanks to Dennis and Matts for drawing my attention to the textwrap
module; I was not aware of its existence.


On Wed, Feb 23, 2022 at 3:30 PM Cameron Simpson <cs at cskk.id.au> wrote:

> On 23Feb2022 11:37, Alex Kleider <alexkleider at gmail.com> wrote:
> >I've written myself a little utility that accepts a text file which
> >might have very long lines and returns a file with the same text but
> >(as much as possible) with the lines no longer than MAX_LEN
> >characters. (I've chosen 70.)
> >It seems to work except when the the source file contains back
> >slashes! (Presence of a back slash appears to cause the program
> >to go into an endless loop.)
>
> There's _nothing_ in your code which cares about backslashes.
>
> >I've tried converting to raw strings but to no avail.
>
> I have no idea what you mean here - all the strings you're manipulating
> come from the text file. They're just "strings". A Python "raw string"
> is just a _syntactic_ way to express a string in a programme, eg:
>
>     r'some regexp maybe \n foo'
>
> After that's evaluated, it is just a string.
>
> >Here's the code, followed by an example source file.
>
> Thank you. This shows the bug. Here's me running it:
>
>     [~/tmp/p1]fleet2*> py3 foo.py input.txt
>     line: '
> https://superuser.com/questions/1313241/install-windows-10-from-an-unbooted-oem-drive-into-virtualbox/1329935#1329935
>     '
>     writing: '
> https://superuser.com/questions/1313241/install-windows-10-from-an-unbooted-oem-drive-into-virtualbox/1329935#1329935
> '
>     remaining: ''
>     line: '
>     '
>     writing: ''
>     remaining: ''
>     line: 'You can activate Windows 10 using the product key for your
> hardware which
>     '
>
>     ^CTraceback (most recent call last):
>       File "/Users/cameron/tmp/p1/foo.py", line 63, in <module>
>         line2write, line = split_on_space_closest_to_max_len(
>       File "/Users/cameron/tmp/p1/foo.py", line 47, in
>     split_on_space_closest_to_max_len
>         if next_space > max_len: break
>     KeyboardInterrupt
>
> It hung just before the traceback, where I interrupted it with ^C.
>
> Now, that tells me where in the code it was - the programme is not hung,
> it is spinning. When interrupted it was in this loop:
>
>     while True:
>         next_space = unindented_line.find(' ', i_space+1)
>         if next_space > max_len: break
>         else: i_space =next_space
>
> On the face of that loop should always advance i_space and therefore
> exit. But find() can return -1:
>
>     >>> help(str.find)
>     Help on method_descriptor:
>
>     find(...)
>         S.find(sub[, start[, end]]) -> int
>
>         Return the lowest index in S where substring sub is found,
>         such that sub is contained within S[start:end].  Optional
>         arguments start and end are interpreted as in slice notation.
>
>         Return -1 on failure.
>
> i.e. when there is no space from the search point onward. So this could
> spin out. Let's see with modified code:
>
>     print("LOOP1")
>     while True:
>         assert ' ' in unindented_line[i_space+1:], (
>             "no space in unindented_line[i_space(%d)+1:]: %r"
>             % (i_space, unindented_line[i_space+1:])
>         )
>         next_space = unindented_line.find(' ', i_space+1)
>         if next_space > max_len: break
>         else: i_space =next_space
>     print("LOOP1 DONE")
>
> thus:
>
>     [~/tmp/p1]fleet2*> py3 foo.py input.txt
>     line: '
> https://superuser.com/questions/1313241/install-windows-10-from-an-unbooted-oem-drive-into-virtualbox/1329935#1329935
>     '
>     writing: '
> https://superuser.com/questions/1313241/install-windows-10-from-an-unbooted-oem-drive-into-virtualbox/1329935#1329935
> '
>     remaining: ''
>     line: '
>     '
>     writing: ''
>     remaining: ''
>     line: 'You can activate Windows 10 using the product key for your
> hardware which
>     '
>     LOOP1
>     Traceback (most recent call last):
>       File "/Users/cameron/tmp/p1/foo.py", line 69, in <module>
>         line2write, line = split_on_space_closest_to_max_len(
>       File "/Users/cameron/tmp/p1/foo.py", line 47, in
>     split_on_space_closest_to_max_len
>         assert ' ' in unindented_line[i_space+1:], (
>     AssertionError: no space in unindented_line[i_space(67)+1:]: 'which'
>
> As suspected. Commenting out the assert and printing next_space shows
> the cycle, with this code:
>
>     print("LOOP1")
>     while True:
>         ##assert ' ' in unindented_line[i_space+1:], (
>         ##    "no space in unindented_line[i_space(%d)+1:]: %r"
>         ##    % (i_space, unindented_line[i_space+1:])
>         ##)
>         next_space = unindented_line.find(' ', i_space+1)
>         print("next_space =", next_space)
>         if next_space > max_len: break
>         else: i_space =next_space
>     print("LOOP1 DONE")
>
> which outputs this:
>
>     [~/tmp/p1]fleet2*> py3 foo.py input.txt 2>&1 | sed 50q
>     line: '
> https://superuser.com/questions/1313241/install-windows-10-from-an-unbooted-oem-drive-into-virtualbox/1329935#1329935
>     '
>     writing: '
> https://superuser.com/questions/1313241/install-windows-10-from-an-unbooted-oem-drive-into-virtualbox/1329935#1329935
> '
>     remaining: ''
>     line: '
>     '
>     writing: ''
>     remaining: ''
>     line: 'You can activate Windows 10 using the product key for your
> hardware which
>     '
>     LOOP1
>     next_space = 7
>     next_space = 16
>     next_space = 24
>     next_space = 27
>     next_space = 33
>     next_space = 37
>     next_space = 45
>     next_space = 49
>     next_space = 53
>     next_space = 58
>     next_space = 67
>     next_space = -1
>     next_space = 3
>     next_space = 7
>     next_space = 16
>     next_space = 24
>     next_space = 27
>     next_space = 33
>
> and so on indefinitely. You can see next_space reset to -1.
>
> Which I'm here, some random remarks about the code:
>
> >    original_line = line[:]
>
> There's no need for this. Because strings are immutable, you can just
> go:
>
>     original_line = line
>
> All the other operations on "line" return new strings (because strings
> are immutable), leaving original_line untouched.
>
> >    unindented_line = line.lstrip()
> >    n_leading_spaces = line_length - len(unindented_line)
> >    if n_leading_spaces > max_len:  # big indentation!!!
> >        return ('', line[max_len:])
> >    indentation = ' ' * n_leading_spaces
>
> Isn't this also unindented_line[:n_leading_spaces]? I would be inclined
> to use that in case the whitespace isn't just spaces (eg TABs).  Because
> "line.lstrip()" strips leading whitespace, not leading spaces. This
> would preserve whetever was there.
>
> Howvere your code is focussed on the space character, so maybe a more
> precise lstip() would be better:
>
>     line.lstrip(' ')
>
> stripping only space characters.
>
> [...]
> >    while True:
> >        next_space = unindented_line.find(' ', i_space+1)
> >        if next_space > max_len: break
> >        else: i_space =next_space
>
> A lot of us might write this:
>
>     while True:
>         next_space = unindented_line.find(' ', i_space+1)
>         if next_space > max_len:
>             break
>         i_space =next_space
>
> dropping the "else:". It is just style, but to my eye it is more clear
> that the "i_space =next_space" is an "uncodnitional" part of the normal
> loop iteration.
>
> >        for line in source:
> >#           line = repr(line.rstrip())
>
> The commented out line above would damage "line" (by adding quotes and
> stuff to it), if uncommented.
>
> >            print("line: '{}'".format(line))  # for debugging
>
> You know you can just write?
>
>     print("line:", line)
>
> Cheers,
> Cameron Simpson <cs at cskk.id.au>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>

From phillor9 at gmail.com  Wed Feb 23 22:41:04 2022
From: phillor9 at gmail.com (Phil)
Date: Thu, 24 Feb 2022 14:41:04 +1100
Subject: [Tutor] Tkinter checkbutton
Message-ID: <705e65c2-698e-bbbe-eff2-da459666fd6b@gmail.com>

Out of curiosity, I'm wondering if the select area (the area where the 
tick is displayed when the button is selected) can be set when the 
checkbutton is selected? According to the documentation the default 
colour is red but in my case it's white and doesn't change colour when 
the checkbutton is selected.

This is from the tk docs. "selectcolor The color of the checkbutton when 
it is set. By default, it is red."

This is one of my checkbuttons:

 ??????? self.red_check_button = ttk.Checkbutton(self.frame,
 ?????????????????????????????????????????????? text='Red LED',
 ?????????????????????????????????????????????? selectcolor='red',
variable=self.red_value)

This causes the select area to be red whether the checkbutton is 
selected or not and it's the same for a tk or ttk checkbutton. The way 
the checkbutton behaves could possibly depend on the OS used.

-- 
Regards,
Phil


From alan.gauld at yahoo.co.uk  Thu Feb 24 05:25:26 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 24 Feb 2022 10:25:26 +0000
Subject: [Tutor] Tkinter checkbutton
In-Reply-To: <705e65c2-698e-bbbe-eff2-da459666fd6b@gmail.com>
References: <705e65c2-698e-bbbe-eff2-da459666fd6b@gmail.com>
Message-ID: <sv7men$1463$1@ciao.gmane.io>

On 24/02/2022 03:41, Phil wrote:
> Out of curiosity, I'm wondering if the select area (the area where the 
> tick is displayed when the button is selected) can be set when the 
> checkbutton is selected? 

Yes, you can supply a command function which is called whenever the
button is selected or deselected:

cb = tk.Checkbutton(top)
cb.pack()

def f():
	if cb['selectcolor'] != 'red':
		cb['selectcolor'] = 'red'
	else: cb['selectcolor'] = 'white'

	
>>> cb['command'] = f


> According to the documentation the default 
> colour is red but in my case it's white and doesn't change colour when 
> the checkbutton is selected.

It doesn't seem to change colour. It's just the colour of
the part of the widget that you select.

> This is from the tk docs. "selectcolor The color of the checkbutton when 
> it is set. By default, it is red."

I think the wording is misleading. I think it means
when the colour is set by the programmer not by the user.
But the default is definitely white, on Linux at least.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From marcus.luetolf at bluewin.ch  Thu Feb 24 14:42:54 2022
From: marcus.luetolf at bluewin.ch (marcus.luetolf at bluewin.ch)
Date: Thu, 24 Feb 2022 20:42:54 +0100
Subject: [Tutor] dealing with lists (2)
Message-ID: <003101d829b6$bff375e0$3fda61a0$@bluewin.ch>

Hello Experts, 

I try to solve the following problem:

 

I'd like to create  5 lists, each containing 4 sublists : f1, f2, f3, f4,
f5, a total of 20 sublists.

I have a list (named all_letters) contaning 16 characters a, b, c, ...p.

 

I  would liketo  distribute all 16 characters to the 4 sublists 5 times in 5
iterations respectivly  so that

as a condition a pair of characters, p.e. ['a', 'b', .]  or ['a', 'c'.] or
[.'n', 'p'] can appear only once in all 20 sublists.

 

To find the sublists fullfilling this condition I designed the following
code with the intention to change the indices

defined by the variables n and p til the condition is met :

 

all_letters = list('abcdefghijklmnop')

f1 = []

f2 = []

f3 = []

f4 = []

n = 0

p = 1

for dummy_i in range(5):  

    copy_all_letters = all_letters[:]

    lst = 16*copy_all_letters

    f1.append(lst[n+0])

    f1.append(lst[n+p])

    f1.append(lst[n+2*p])

    f1.append(lst[n+3*p])

    f1.sort()

    f2.append(lst[n+4*p])

    f2.append(lst[n+5*p])

    f2.append(lst[n+6*p])

    f2.append(lst[n+7*p])

    f2.sort()

    f3.append(lst[n+8*p])

    f3.append(lst[n+9*p])

    f3.append(lst[n+10*p])

    f3.append(lst[n+11*p])

    f3.sort()

    f4.append(lst[n+12*p])

    f4.append(lst[n+13*p])

    f4.append(lst[n+14*p])

    f4.append(lst[n+15*p])

    f4.sort()

       

    print('f1: ', f1)

    print('f2: ', f2)

    print('f3: ', f3)

    print('f4: ', f4)

    n += 4

    p += 1

    f1 = []

    f2 = []

    f3 = []

    f4 = []

    f5 = []

 

But I'm unable to define the condition mentioned above and asking for your
help.

 


From alan.gauld at yahoo.co.uk  Thu Feb 24 17:04:45 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Thu, 24 Feb 2022 22:04:45 +0000
Subject: [Tutor] dealing with lists (2)
In-Reply-To: <003101d829b6$bff375e0$3fda61a0$@bluewin.ch>
References: <003101d829b6$bff375e0$3fda61a0$@bluewin.ch>
Message-ID: <sv8vdu$hp1$1@ciao.gmane.io>

On 24/02/2022 19:42, marcus.luetolf at bluewin.ch wrote:

> I'd like to create  5 lists, each containing 4 sublists : f1, f2, f3, f4,
> f5, a total of 20 sublists.

Isn't this identical to what you posted a couple of days ago?
Have you tried the suggestions made then?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From phillor9 at gmail.com  Thu Feb 24 17:30:01 2022
From: phillor9 at gmail.com (Phil)
Date: Fri, 25 Feb 2022 09:30:01 +1100
Subject: [Tutor] Tkinter checkbutton
In-Reply-To: <sv7men$1463$1@ciao.gmane.io>
References: <705e65c2-698e-bbbe-eff2-da459666fd6b@gmail.com>
 <sv7men$1463$1@ciao.gmane.io>
Message-ID: <19faccf0-dceb-211f-da97-ca34e52b87d8@gmail.com>


On 24/2/22 21:25, Alan Gauld via Tutor wrote:

> def f():
> 	if cb['selectcolor'] != 'red':
> 		cb['selectcolor'] = 'red'
> 	else: cb['selectcolor'] = 'white'

I did something like that but, for some reason, it didn't occur to me 
change the colour back to white after the checkbutton was deselected. 
What a dill!


> I think the wording is misleading. I think it means
> when the colour is set by the programmer not by the user.
> But the default is definitely white, on Linux at least.

I also use Linux and the desk top environment is XFCE which is built on 
GTK so the default tk widgets have a native look. I only have one 
application that use a checkbutton and it shows the indicator box to be 
larger than the checkbutton that I have created using ttk. The buttons 
look the same but not the checkbutton. I suppose It's possible that this 
application wasn't built with tkinter.

Getting back to ttk. The theme 'alt' closely matches the native look and 
so I thought I'd have a play with the other themes. I like the look of 
'clam'. Unfortunately, I didn't get past the first step:

 >>> import tkinter as ttk
 >>>
 >>> style = ttk.Style()
Traceback (most recent call last):
 ? File "<stdin>", line 1, in <module>
AttributeError: module 'tkinter' has no attribute 'Style'
 >>>

No doubt this is a dummy's error.

-- 

Regards,
Phil


From nathan-tech at hotmail.com  Thu Feb 24 17:35:53 2022
From: nathan-tech at hotmail.com (Nathan Smith)
Date: Thu, 24 Feb 2022 22:35:53 +0000
Subject: [Tutor] theory: geography and python
Message-ID: <DB7PR07MB50931C159B5E803E718E9F04E43D9@DB7PR07MB5093.eurprd07.prod.outlook.com>

Hi folks,


This is more of a theory based discussion topic (with luck). Off and on 
I've been considering geography in python for a while, more 
specifically, how you would go about positioning countries and borders.


Countries are, by their nature, rarely nice squares, so you could hardly 
say:

England=(left lat, right lat)

ireland = (left lat, right lat).


Is there an industry standard for this sort of thing to get the shapes 
of countries semi accurate in terms of coordinates and borders? What 
sources should be looked at?


Thanks in advance for any ideas.

Nathan

-- 

Best Wishes,

Nathan Smith, BSC


My Website: https://nathantech.net



From robertvstepp at gmail.com  Thu Feb 24 18:06:41 2022
From: robertvstepp at gmail.com (boB Stepp)
Date: Thu, 24 Feb 2022 17:06:41 -0600
Subject: [Tutor] Tkinter checkbutton
In-Reply-To: <19faccf0-dceb-211f-da97-ca34e52b87d8@gmail.com>
References: <705e65c2-698e-bbbe-eff2-da459666fd6b@gmail.com>
 <sv7men$1463$1@ciao.gmane.io>
 <19faccf0-dceb-211f-da97-ca34e52b87d8@gmail.com>
Message-ID: <YhgPgX6ewPT+7kXE@Dream-Machine1>

On 22/02/25 09:30AM, Phil wrote:
>
>Getting back to ttk. The theme 'alt' closely matches the native look 
>and so I thought I'd have a play with the other themes. I like the 
>look of 'clam'. Unfortunately, I didn't get past the first step:
>
>>>> import tkinter as ttk

Try instead:

>>>> from tkinter import ttk


-- 
Wishing you only the best,
boB Stepp

"Do not act as if you were going to live ten thousand years.  Death hangs over
you.  While you live, while it is in your power, be good."
     -- Roman emperor Marcus Aurelius

From phillor9 at gmail.com  Thu Feb 24 18:12:57 2022
From: phillor9 at gmail.com (Phil)
Date: Fri, 25 Feb 2022 10:12:57 +1100
Subject: [Tutor] Tkinter checkbutton
In-Reply-To: <YhgPgX6ewPT+7kXE@Dream-Machine1>
References: <705e65c2-698e-bbbe-eff2-da459666fd6b@gmail.com>
 <sv7men$1463$1@ciao.gmane.io>
 <19faccf0-dceb-211f-da97-ca34e52b87d8@gmail.com>
 <YhgPgX6ewPT+7kXE@Dream-Machine1>
Message-ID: <0fcec257-6483-dec1-317b-715a02fb3215@gmail.com>


On 25/2/22 10:06, boB Stepp wrote:
Try instead:
>
>>>>> from tkinter import ttk

Thanks Bob. I found the answer through a bit of trial-and-error but 
because I cannot answer my own question I couldn't let the group know.

-- 

Regards,
Phil


From breamoreboy at gmail.com  Thu Feb 24 17:59:10 2022
From: breamoreboy at gmail.com (Mark Lawrence)
Date: Thu, 24 Feb 2022 22:59:10 +0000
Subject: [Tutor] theory: geography and python
In-Reply-To: <DB7PR07MB50931C159B5E803E718E9F04E43D9@DB7PR07MB5093.eurprd07.prod.outlook.com>
References: <DB7PR07MB50931C159B5E803E718E9F04E43D9@DB7PR07MB5093.eurprd07.prod.outlook.com>
Message-ID: <5d637e20-aa19-5408-cf78-eb3771b3eee4@gmail.com>

On 24/02/2022 22:35, Nathan Smith wrote:
> Hi folks,
> 
> This is more of a theory based discussion topic (with luck). Off and on 
> I've been considering geography in python for a while, more 
> specifically, how you would go about positioning countries and borders.
> 
> Countries are, by their nature, rarely nice squares, so you could hardly 
> say:
> 
> England=(left lat, right lat)
> 
> ireland = (left lat, right lat).
> 
> Is there an industry standard for this sort of thing to get the shapes 
> of countries semi accurate in terms of coordinates and borders? What 
> sources should be looked at?
> 
> Thanks in advance for any ideas.
> 
> Nathan
> 

I'd start here 
https://towardsdatascience.com/mapping-with-matplotlib-pandas-geopandas-and-basemap-in-python-d11b57ab5dac

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence


From hannah.jones at ebcbrakesuk.com  Fri Feb 25 07:00:37 2022
From: hannah.jones at ebcbrakesuk.com (Hannah Jones)
Date: Fri, 25 Feb 2022 12:00:37 +0000
Subject: [Tutor] Excel to SQL DB using Python
Message-ID: <LO3P123MB2697E03A051D5B0B99C38280903E9@LO3P123MB2697.GBRP123.PROD.OUTLOOK.COM>

Hello,

I need help with some code if possible please.

I am trying to convert an excel file to a list and then iterate over the list and add to an SQL database.

I am having trouble adding the data to the database.

I have already established the connection - all good.

My code is:

Locations = []
filename = input("Enter Filename Containing your Locations:  ")

with open(filename, "r") as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    #skips the header from the excel file
    next(csv_reader)
    for lines in csv_reader:
        Locations.append(lines)
# SQL Statements
sqlDELETE = "DELETE FROM dbo.GeocodingLocations"
cursor.execute(sqlDELETE)
sqlINSERTBase = "INSERT INTO dbo.GeocodingLocations (SageCode, Name, AddressLine1, AddressLine2, AddressLine3, AddressLine4, City, CountryName) VALUES "
sqlVALUES = ""

# Iteration to add to Studio DB
for x in Locations:
    SageCode = x[0] ; Name = x[1] ; AddressLine1 = x[2] ; AddressLine2 = x[3] ; AddressLine3 = x[4] ; AddressLine4 = x[5] ; City = x[6] ; CountryName = x[7]
    sqlVALUES = sqlVALUES + "( '" + SageCode + "', '" + Name + "', '" + AddressLine1 + "', '" + AddressLine2 + "', '" + AddressLine3 + "', '" + AddressLine4 + "', '" + City + "', '" + CountryName +  "' ), '"
    sqlINSERT = sqlINSERTBase + sqlVALUES
    sqlINSERT = sqlINSERT
    cursor.execute(sqlINSERT)


cursor.commit()
con.close()


however I keep receiving this error; pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near 'S'. (102) (SQLExecDirectW)")

I know my error is in this line;



sqlVALUES = sqlVALUES + "( '" + SageCode + "', '" + Name + "', '" + AddressLine1 + "', '" + AddressLine2 + "', '" + AddressLine3 + "', '" + AddressLine4 + "', '" + City + "', '" + CountryName +  "' ), '"


but I am not sure where exactly, any help is highly appreciated.

Thank you
Hannah

From alan.gauld at yahoo.co.uk  Fri Feb 25 08:34:57 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Fri, 25 Feb 2022 13:34:57 +0000
Subject: [Tutor] Excel to SQL DB using Python
In-Reply-To: <LO3P123MB2697E03A051D5B0B99C38280903E9@LO3P123MB2697.GBRP123.PROD.OUTLOOK.COM>
References: <LO3P123MB2697E03A051D5B0B99C38280903E9@LO3P123MB2697.GBRP123.PROD.OUTLOOK.COM>
Message-ID: <svalu1$t5q$1@ciao.gmane.io>

On 25/02/2022 12:00, Hannah Jones wrote:
> Hello,
> 
> I need help with some code if possible please.
> 
> I am trying to convert an excel file to a list and then iterate over the list and add to an SQL database.

It's worth checking your database tools. Most have import facilities for
CSV files, even Sqlite can do very basic CSV imports(but not with
embedded commas etc) But Oracle, for example, can import all manner
of file formats.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From joel.goldstick at gmail.com  Fri Feb 25 09:09:02 2022
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Fri, 25 Feb 2022 09:09:02 -0500
Subject: [Tutor] Excel to SQL DB using Python
In-Reply-To: <LO3P123MB2697E03A051D5B0B99C38280903E9@LO3P123MB2697.GBRP123.PROD.OUTLOOK.COM>
References: <LO3P123MB2697E03A051D5B0B99C38280903E9@LO3P123MB2697.GBRP123.PROD.OUTLOOK.COM>
Message-ID: <CAPM-O+zM0XTjCROOtsmWsemJYsQ3maiJw9s9vsZXkdT=LsP7zQ@mail.gmail.com>

On Fri, Feb 25, 2022 at 8:16 AM Hannah Jones
<hannah.jones at ebcbrakesuk.com> wrote:
>
> Hello,
>
> I need help with some code if possible please.
>
> I am trying to convert an excel file to a list and then iterate over the list and add to an SQL database.
>
> I am having trouble adding the data to the database.
>
> I have already established the connection - all good.
>
> My code is:
>
> Locations = []
> filename = input("Enter Filename Containing your Locations:  ")
>
> with open(filename, "r") as csv_file:
>     csv_reader = csv.reader(csv_file, delimiter=',')
>     #skips the header from the excel file
>     next(csv_reader)
>     for lines in csv_reader:
>         Locations.append(lines)
> # SQL Statements
> sqlDELETE = "DELETE FROM dbo.GeocodingLocations"
> cursor.execute(sqlDELETE)
> sqlINSERTBase = "INSERT INTO dbo.GeocodingLocations (SageCode, Name, AddressLine1, AddressLine2, AddressLine3, AddressLine4, City, CountryName) VALUES "
> sqlVALUES = ""
>
> # Iteration to add to Studio DB
> for x in Locations:
>     SageCode = x[0] ; Name = x[1] ; AddressLine1 = x[2] ; AddressLine2 = x[3] ; AddressLine3 = x[4] ; AddressLine4 = x[5] ; City = x[6] ; CountryName = x[7]
>     sqlVALUES = sqlVALUES + "( '" + SageCode + "', '" + Name + "', '" + AddressLine1 + "', '" + AddressLine2 + "', '" + AddressLine3 + "', '" + AddressLine4 + "', '" + City + "', '" + CountryName +  "' ), '"
>     sqlINSERT = sqlINSERTBase + sqlVALUES
>     sqlINSERT = sqlINSERT
>     cursor.execute(sqlINSERT)
>
>
> cursor.commit()
> con.close()
>
>
> however I keep receiving this error; pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near 'S'. (102) (SQLExecDirectW)")
>
> I know my error is in this line;
>
>
>
> sqlVALUES = sqlVALUES + "( '" + SageCode + "', '" + Name + "', '" + AddressLine1 + "', '" + AddressLine2 + "', '" + AddressLine3 + "', '" + AddressLine4 + "', '" + City + "', '" + CountryName +  "' ), '"
>
>
> but I am not sure where exactly, any help is highly appreciated.
 you could print sqlVALUES.  Then take the statement produced and
interactively see what happens with your sqlserver.

> https://mail.python.org/mailman/listinfo/tutor



-- 
Joel Goldstick

From __peter__ at web.de  Fri Feb 25 09:29:48 2022
From: __peter__ at web.de (Peter Otten)
Date: Fri, 25 Feb 2022 15:29:48 +0100
Subject: [Tutor] Excel to SQL DB using Python
In-Reply-To: <LO3P123MB2697E03A051D5B0B99C38280903E9@LO3P123MB2697.GBRP123.PROD.OUTLOOK.COM>
References: <LO3P123MB2697E03A051D5B0B99C38280903E9@LO3P123MB2697.GBRP123.PROD.OUTLOOK.COM>
Message-ID: <9b318ab2-5df0-93e9-49a0-f8fc1be91cab@web.de>

On 25/02/2022 13:00, Hannah Jones wrote:
> Hello,
>
> I need help with some code if possible please.
>
> I am trying to convert an excel file to a list and then iterate over the list and add to an SQL database.
>
> I am having trouble adding the data to the database.
>
> I have already established the connection - all good.
>
> My code is:
>
> Locations = []
> filename = input("Enter Filename Containing your Locations:  ")
>
> with open(filename, "r") as csv_file:
>      csv_reader = csv.reader(csv_file, delimiter=',')
>      #skips the header from the excel file
>      next(csv_reader)
>      for lines in csv_reader:
>          Locations.append(lines)
> # SQL Statements
> sqlDELETE = "DELETE FROM dbo.GeocodingLocations"
> cursor.execute(sqlDELETE)
> sqlINSERTBase = "INSERT INTO dbo.GeocodingLocations (SageCode, Name, AddressLine1, AddressLine2, AddressLine3, AddressLine4, City, CountryName) VALUES "
> sqlVALUES = ""
>
> # Iteration to add to Studio DB
> for x in Locations:
>      SageCode = x[0] ; Name = x[1] ; AddressLine1 = x[2] ; AddressLine2 = x[3] ; AddressLine3 = x[4] ; AddressLine4 = x[5] ; City = x[6] ; CountryName = x[7]
>      sqlVALUES = sqlVALUES + "( '" + SageCode + "', '" + Name + "', '" + AddressLine1 + "', '" + AddressLine2 + "', '" + AddressLine3 + "', '" + AddressLine4 + "', '" + City + "', '" + CountryName +  "' ), '"
>      sqlINSERT = sqlINSERTBase + sqlVALUES
>      sqlINSERT = sqlINSERT
>      cursor.execute(sqlINSERT)
>
>
> cursor.commit()
> con.close()
>
>
> however I keep receiving this error; pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near 'S'. (102) (SQLExecDirectW)")
>
> I know my error is in this line;
>
>
>
> sqlVALUES = sqlVALUES + "( '" + SageCode + "', '" + Name + "', '" + AddressLine1 + "', '" + AddressLine2 + "', '" + AddressLine3 + "', '" + AddressLine4 + "', '" + City + "', '" + CountryName +  "' ), '"
>
>
> but I am not sure where exactly, any help is highly appreciated.

You are constructing the insertion statement manually, like in the
example below:

first, second = "Hannah",  "Jones"
sql = "insert into people (first, second) values ('" + first + "', '" +
  + second + "');"

cursor.execute(sql)

This is error prone and even dangerous when the name is entered/provided
by an untrusted user/source. A classic example:

https://xkcd.com/327/

You can avoid this problem dubbed "sql injection" by using a fixed query:

sql = "insert into people (first, second) values (?, ?);"
cursor.execute(sql, (first, second))

In the example I use the question mark as a placeholder; you can find
the actual placeholder in the paramstyle attribute. See

https://www.python.org/dev/peps/pep-0249/#paramstyle

for the details.

From marcus.luetolf at bluewin.ch  Fri Feb 25 09:45:53 2022
From: marcus.luetolf at bluewin.ch (marcus.luetolf at bluewin.ch)
Date: Fri, 25 Feb 2022 15:45:53 +0100
Subject: [Tutor] dealing with lists (2)
Message-ID: <000901d82a56$662870b0$32795210$@bluewin.ch>

Sorry, I sent my following comment to the wrong address :

 

Yes, you are right. 

 

But but my final goal is to create 20 sublistst with item-pairs (16 items
total) appearing only once.

I found that my initial approach to which I postet questions a few days ago
lead to a dead end.

 

So I used a simpler way tro create those 20 sublists as posted more
recently.

 

I am still working on a way to change the sequence of items in those 20
sublists til the condition concerning the pairs of items is met.

 

I know that my goal is  mathematically possible with 16 items in 20 sublists
from a discussion a couple of years ago.

 

I refined my code below but with changing the indices of f1, f2, f3, f4 and
by n manually I'am unable to avoid double pairings.

I think I reached another dead end.

Bur mybe someone could give me an idea for a different approach before
giving up.

 

 

>comb_list = []

f>or dummy_i in range(4):  

    >copy_all_letters = all_letters[:]

    >lst = (16*16)*copy_all_letters

    >f1 = []

    >f2 = []

    >f3 = []

    >f4 = []

   > f1.append(lst[0+n])

    >f1.append(lst[2+n])

    >f1.append(lst[4+n])

    >f1.append(lst[6+n])

   > f1.sort()

    >comb_list.append(f1)

    >f2.append(lst[8+n])

    >f2.append(lst[10+n])

    >f2.append(lst[12+n])

    >f2.append(lst[14+n])

    >f2.sort()

    >comb_list.append(f2)

   > f3.append(lst[1+n])

    >f3.append(lst[3+n])

    >f3.append(lst[5+n])

    >f3.append(lst[7+n])

    >f3.sort()

    >comb_list.append(f3)

   > f4.append(lst[9+n])

    >f4.append(lst[11+n])

   > f4.append(lst[13+n])

   > f4.append(lst[15+n])

    >f4.sort()

   > comb_list.append(f4)

   > print(f1, f2, f4, f4)

   > print(comb_list)

   > n += 3

 

 

Hello Experts, 

I try to solve the following problem:

 

I'd like to create  5 lists, each containing 4 sublists : f1, f2, f3, f4,
f5, a total of 20 sublists.

I have a list (named all_letters) contaning 16 characters a, b, c, ...p.

 

I  would liketo  distribute all 16 characters to the 4 sublists 5 times in 5
iterations respectivly  so that

as a condition a pair of characters, p.e. ['a', 'b', .]  or ['a', 'c'.] or
[.'n', 'p'] can appear only once in all 20 sublists.

 

To find the sublists fullfilling this condition I designed the following
code with the intention to change the indices

defined by the variables n and p til the condition is met :

 

all_letters = list('abcdefghijklmnop')

f1 = []

f2 = []

f3 = []

f4 = []

n = 0

p = 1

for dummy_i in range(5):  

    copy_all_letters = all_letters[:]

    lst = 16*copy_all_letters

    f1.append(lst[n+0])

    f1.append(lst[n+p])

    f1.append(lst[n+2*p])

    f1.append(lst[n+3*p])

    f1.sort()

    f2.append(lst[n+4*p])

    f2.append(lst[n+5*p])

    f2.append(lst[n+6*p])

    f2.append(lst[n+7*p])

    f2.sort()

    f3.append(lst[n+8*p])

    f3.append(lst[n+9*p])

    f3.append(lst[n+10*p])

    f3.append(lst[n+11*p])

    f3.sort()

    f4.append(lst[n+12*p])

    f4.append(lst[n+13*p])

    f4.append(lst[n+14*p])

    f4.append(lst[n+15*p])

    f4.sort()

       

    print('f1: ', f1)

    print('f2: ', f2)

    print('f3: ', f3)

    print('f4: ', f4)

    n += 4

    p += 1

    f1 = []

    f2 = []

    f3 = []

    f4 = []

    f5 = []

 

But I'm unable to define the condition mentioned above and asking for your
help.

 


From wlfraed at ix.netcom.com  Fri Feb 25 12:14:00 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Fri, 25 Feb 2022 12:14:00 -0500
Subject: [Tutor] theory: geography and python
References: <DB7PR07MB50931C159B5E803E718E9F04E43D9@DB7PR07MB5093.eurprd07.prod.outlook.com>
Message-ID: <e53i1hh9fp3emjab1mpk0gq9t1rnlkkgag@4ax.com>

On Thu, 24 Feb 2022 22:35:53 +0000, Nathan Smith <nathan-tech at hotmail.com>
declaimed the following:

>
>Is there an industry standard for this sort of thing to get the shapes 
>of countries semi accurate in terms of coordinates and borders? What 
>sources should be looked at?
>

	Rather out-of-date by now but the CIA World Databank II had been
commonly used.

https://www.google.com/search?q=cia+world+databank+II

	I'm sure there are more modernized sources (WDB likely still has West &
East Germany, along with the Berlin air corridors), but they may be as part
of some $$$ GIS package.


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From wlfraed at ix.netcom.com  Fri Feb 25 12:38:34 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Fri, 25 Feb 2022 12:38:34 -0500
Subject: [Tutor] Excel to SQL DB using Python
References: <LO3P123MB2697E03A051D5B0B99C38280903E9@LO3P123MB2697.GBRP123.PROD.OUTLOOK.COM>
Message-ID: <ms3i1h95qmqstkrckdsa9l2v5oegc2plp5@4ax.com>

On Fri, 25 Feb 2022 12:00:37 +0000, Hannah Jones
<hannah.jones at ebcbrakesuk.com> declaimed the following:

>for x in Locations:
>    SageCode = x[0] ; Name = x[1] ; AddressLine1 = x[2] ; AddressLine2 = x[3] ; AddressLine3 = x[4] ; AddressLine4 = x[5] ; City = x[6] ; CountryName = x[7]

	<ugh>

	for (SageCode, Name, AddressLine1, ..., CountryName) in Locations:


>    sqlVALUES = sqlVALUES + "( '" + SageCode + "', '" + Name + "', '" + AddressLine1 + "', '" + AddressLine2 + "', '" + AddressLine3 + "', '" + AddressLine4 + "', '" + City + "', '" + CountryName +  "' ), '"

	Never do that -- especially if the data comes from an external source!
All it would take is for one data item to have a " in it to turn that into
a mess -- not to mention having a ";SOMESQL in a value executing things you
don't expect..

	Check the documentation for the DB-API adapter you are using to
determine what style of parameter it wants, and parameterize the
SQL/.execute() lines. It is the responsibility of the adapter to examine
each data item and properly escape any dangerous characters.


	{I also ponder why you are reading the entire CSV file into a list
first, only to then iterate over that list to do SQL INSERT statements --
rather than do the insert at the time you read the CSV lines. OR -- once
you parameterize the query, you could use .executemany() to process the
entire list as one transaction.

cursor.commit() is a convenience function that just turns into
connection.commit()

https://github.com/mkleehammer/pyodbc/wiki/Cursor
}


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From nathan-tech at hotmail.com  Fri Feb 25 13:13:54 2022
From: nathan-tech at hotmail.com (Nathan Smith)
Date: Fri, 25 Feb 2022 18:13:54 +0000
Subject: [Tutor] theory: geography and python
In-Reply-To: <e53i1hh9fp3emjab1mpk0gq9t1rnlkkgag@4ax.com>
References: <DB7PR07MB50931C159B5E803E718E9F04E43D9@DB7PR07MB5093.eurprd07.prod.outlook.com>
 <e53i1hh9fp3emjab1mpk0gq9t1rnlkkgag@4ax.com>
Message-ID: <DB7PR07MB5093357B91EF67A63341B26CE43E9@DB7PR07MB5093.eurprd07.prod.outlook.com>

Hi there,


thanks a lot for this!


Nathan

On 25/02/2022 17:14, Dennis Lee Bieber wrote:
> On Thu, 24 Feb 2022 22:35:53 +0000, Nathan Smith <nathan-tech at hotmail.com>
> declaimed the following:
>
>> Is there an industry standard for this sort of thing to get the shapes
>> of countries semi accurate in terms of coordinates and borders? What
>> sources should be looked at?
>>
> 	Rather out-of-date by now but the CIA World Databank II had been
> commonly used.
>
> https://nam12.safelinks.protection.outlook.com/?url=https%3A%2F%2Fwww.google.com%2Fsearch%3Fq%3Dcia%2Bworld%2Bdatabank%2BII&amp;data=04%7C01%7C%7Cb5389b1849aa4c55d8ee08d9f882770d%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637814061488668137%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000&amp;sdata=Mvr%2BBTOV%2Blh67qDFswB%2FNxQ%2FXNi1jfwokfCF81AQQok%3D&amp;reserved=0
>
> 	I'm sure there are more modernized sources (WDB likely still has West &
> East Germany, along with the Berlin air corridors), but they may be as part
> of some $$$ GIS package.
>
>
-- 

Best Wishes,

Nathan Smith, BSC


My Website: https://nathantech.net



From trent.shipley at gmail.com  Fri Feb 25 16:59:35 2022
From: trent.shipley at gmail.com (trent shipley)
Date: Fri, 25 Feb 2022 14:59:35 -0700
Subject: [Tutor] Tutoring co-workers.
Message-ID: <CAEFLybKx2D=zZO-fUEraak-T1Q9w6UfL0FR3fRLQc98OCZq=DA@mail.gmail.com>

I'm looking at the possibility of teaching programming to a couple of
coworkers.  Python is an excellent pedagogical programming language, with
the added benefit of what you learn being directly applicable and
marketable in many work contexts.

First, I was wondering if you could recommend any good, accessible
textbooks with many exercises for brand new and C+/B- level programmers new
to Python which could segue into Python plus statistics or Python plus
reporting, and beyond that into very early Python plus data science.

Second, and more important, I took BASIC in high school.  When I went to a
little liberal arts college in central Kansas in the late 1980s, I took
computer science 110 and 210 in Pascal and turned in the code for my
assignments on fan-fold paper hard copy.  My professor (with an actual PhD)
graded the code in beautiful red ink with all the care and attention of a
composition instructor for college freshmen.  I didn't realize how much I
got out of it, until I realized how much I missed that kind of feedback
when I take computer classes at a community college, especially when the
classes are self-paced distance learning classes.  I also can tell younger
programmers have never had the same academic formation I did.

I would like a coding environment where I can comment and edit code and
other text like it was Microsoft Word in draft mode.  In fact, I want to be
able to comment on comments.  You should be able to do remote, real-time
Talmudic disputation in this development environment, and go back through
versions with all the text changes and evolution of comments graphically
illustrated with popup "tooltips", and you should be able to drill down for
change metadata.

My goal is to use it for teaching coding by giving the same attention to my
students' feedback which Marrion Deckert gave to my ealy software writing
education, but without paper and at a distance.  How close can I come to
this vaporware ideal?

(Oh yes, and a student should be able to drop their corrected code, with
all the history and comments hidden, straight into a syntax checker, REPL,
interpreter, or compiler.)

Trent

From alan.gauld at yahoo.co.uk  Fri Feb 25 19:57:18 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sat, 26 Feb 2022 00:57:18 +0000
Subject: [Tutor] Tutoring co-workers.
In-Reply-To: <CAEFLybKx2D=zZO-fUEraak-T1Q9w6UfL0FR3fRLQc98OCZq=DA@mail.gmail.com>
References: <CAEFLybKx2D=zZO-fUEraak-T1Q9w6UfL0FR3fRLQc98OCZq=DA@mail.gmail.com>
Message-ID: <svbtte$11fe$1@ciao.gmane.io>

On 25/02/2022 21:59, trent shipley wrote:

> First, I was wondering if you could recommend any good, accessible
> textbooks with many exercises for brand new and C+/B- level programmers new
> to Python which could segue into Python plus statistics or Python plus
> reporting, and beyond that into very early Python plus data science.

There are fewer books around for that audience these days, most
things are now online. That was why I wrote my first python book
20 years ago and things are even worse today.


> assignments on fan-fold paper hard copy.  My professor (with an actual PhD)
> graded the code in beautiful red ink with all the care and attention of a
> composition instructor for college freshmen.  

Yes, I had one of those two. (And ironically, wound up working
with him a few years later!)


> programmers have never had the same academic formation I did.

Indeed, I think that's something most old school programmers
can recognize. There seems to be a lack of focus on computing
and more on just programming practice.

> I would like a coding environment where I can comment and edit code and
> other text like it was Microsoft Word in draft mode.  
<snip>

Nice idea but I don't know of any environment for any language like
that. Even dedicated teaching environments like the DRscheme etc
don't offer that.

With Agile programming promoting pair programming there might
be something of the sort out there, but I'm not aware of it.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From leamhall at gmail.com  Fri Feb 25 20:04:53 2022
From: leamhall at gmail.com (Leam Hall)
Date: Fri, 25 Feb 2022 19:04:53 -0600
Subject: [Tutor] Tutoring co-workers.
In-Reply-To: <CAEFLybKx2D=zZO-fUEraak-T1Q9w6UfL0FR3fRLQc98OCZq=DA@mail.gmail.com>
References: <CAEFLybKx2D=zZO-fUEraak-T1Q9w6UfL0FR3fRLQc98OCZq=DA@mail.gmail.com>
Message-ID: <c42cab7f-fe67-ce81-de80-8008a0cb1edd@gmail.com>

Guttag's "Introduction to Computation and Programming Using Python" should be interesting enough for decent programmers but not too simplistic. It's not the high end stuff, but it sounds like your crew will burn through it and be doing good python shortly. My guess is that it would tie into the MIT course on edx.org, since Guttag is one of the instructors.

https://www.edx.org/xseries/mitx-computational-thinking-using-python

For tracking comments, I'd simply suggest github. Keep all your code there, and the entire team can see it, and comment. Snarky comments, maybe, but still comments.  :)

Leam



On 2/25/22 15:59, trent shipley wrote:
> I'm looking at the possibility of teaching programming to a couple of
> coworkers.  Python is an excellent pedagogical programming language, with
> the added benefit of what you learn being directly applicable and
> marketable in many work contexts.
> 
> First, I was wondering if you could recommend any good, accessible
> textbooks with many exercises for brand new and C+/B- level programmers new
> to Python which could segue into Python plus statistics or Python plus
> reporting, and beyond that into very early Python plus data science.
> 
> Second, and more important, I took BASIC in high school.  When I went to a
> little liberal arts college in central Kansas in the late 1980s, I took
> computer science 110 and 210 in Pascal and turned in the code for my
> assignments on fan-fold paper hard copy.  My professor (with an actual PhD)
> graded the code in beautiful red ink with all the care and attention of a
> composition instructor for college freshmen.  I didn't realize how much I
> got out of it, until I realized how much I missed that kind of feedback
> when I take computer classes at a community college, especially when the
> classes are self-paced distance learning classes.  I also can tell younger
> programmers have never had the same academic formation I did.
> 
> I would like a coding environment where I can comment and edit code and
> other text like it was Microsoft Word in draft mode.  In fact, I want to be
> able to comment on comments.  You should be able to do remote, real-time
> Talmudic disputation in this development environment, and go back through
> versions with all the text changes and evolution of comments graphically
> illustrated with popup "tooltips", and you should be able to drill down for
> change metadata.
> 
> My goal is to use it for teaching coding by giving the same attention to my
> students' feedback which Marrion Deckert gave to my ealy software writing
> education, but without paper and at a distance.  How close can I come to
> this vaporware ideal?
> 
> (Oh yes, and a student should be able to drop their corrected code, with
> all the history and comments hidden, straight into a syntax checker, REPL,
> interpreter, or compiler.)
> 
> Trent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

-- 
Site Automation Engineer   (reuel.net/resume)
Scribe: The Domici War     (domiciwar.net)
General Ne'er-do-well      (github.com/LeamHall)

From leamhall at gmail.com  Fri Feb 25 20:07:08 2022
From: leamhall at gmail.com (Leam Hall)
Date: Fri, 25 Feb 2022 19:07:08 -0600
Subject: [Tutor] Tutoring co-workers.
In-Reply-To: <svbtte$11fe$1@ciao.gmane.io>
References: <CAEFLybKx2D=zZO-fUEraak-T1Q9w6UfL0FR3fRLQc98OCZq=DA@mail.gmail.com>
 <svbtte$11fe$1@ciao.gmane.io>
Message-ID: <afb2ed89-9b2d-d812-1999-ef00527b14f2@gmail.com>

On 2/25/22 18:57, Alan Gauld via Tutor wrote:
> On 25/02/2022 21:59, trent shipley wrote:

>> assignments on fan-fold paper hard copy.  My professor (with an actual PhD)
>> graded the code in beautiful red ink with all the care and attention of a
>> composition instructor for college freshmen.
> 
> Yes, I had one of those two. (And ironically, wound up working
> with him a few years later!)

Pascal was one of the two programming languages I've taken a regular class for. I recall the graph paper writing too...

Leam

-- 
Site Automation Engineer   (reuel.net/resume)
Scribe: The Domici War     (domiciwar.net)
General Ne'er-do-well      (github.com/LeamHall)

From mats at wichmann.us  Sat Feb 26 10:06:45 2022
From: mats at wichmann.us (Mats Wichmann)
Date: Sat, 26 Feb 2022 08:06:45 -0700
Subject: [Tutor] Tutoring co-workers.
In-Reply-To: <CAEFLybKx2D=zZO-fUEraak-T1Q9w6UfL0FR3fRLQc98OCZq=DA@mail.gmail.com>
References: <CAEFLybKx2D=zZO-fUEraak-T1Q9w6UfL0FR3fRLQc98OCZq=DA@mail.gmail.com>
Message-ID: <c7633c31-a0e6-65cf-ea8a-8861f1d32ec9@wichmann.us>

On 2/25/22 14:59, trent shipley wrote:
> I'm looking at the possibility of teaching programming to a couple of
> coworkers.  Python is an excellent pedagogical programming language, with
> the added benefit of what you learn being directly applicable and
> marketable in many work contexts.
> 
> in the late 1980s, I took
> computer science 110 and 210 in Pascal and turned in the code for my
> assignments on fan-fold paper hard copy.  

My first "formal" language was also Pascal (had previously learned
Fortran and Basic outside an academic setting). It was the era of
Pascal, I guess (mine was a little earlier, we had to jockey for the
very small number of cursor-addressable ADM 3a terminals that made
screen-based editing possible).

> 
> My goal is to use it for teaching coding by giving the same attention to my
> students' feedback which Marrion Deckert gave to my ealy software writing
> education, but without paper and at a distance.  How close can I come to
> this vaporware ideal?
> 
> (Oh yes, and a student should be able to drop their corrected code, with
> all the history and comments hidden, straight into a syntax checker, REPL,
> interpreter, or compiler.)

There are some new and shiny ways to maybe get some of the spirit of
this with some of the online collaborative editing environments, when
combined with a github repo.  It would be very different than red pen on
fanfold paper, but...  I don't know too many of the entrants in this
exploding field, but take a look at Gipod, Replit or Codeshare.

From georgenikil at outlook.com  Sat Feb 26 11:12:58 2022
From: georgenikil at outlook.com (Nikil George)
Date: Sat, 26 Feb 2022 16:12:58 +0000
Subject: [Tutor] Tutoring co-workers.
In-Reply-To: <c7633c31-a0e6-65cf-ea8a-8861f1d32ec9@wichmann.us>
References: <CAEFLybKx2D=zZO-fUEraak-T1Q9w6UfL0FR3fRLQc98OCZq=DA@mail.gmail.com>
 <c7633c31-a0e6-65cf-ea8a-8861f1d32ec9@wichmann.us>
Message-ID: <BN7PR07MB4737057A13C27E06406A2683A83F9@BN7PR07MB4737.namprd07.prod.outlook.com>

Thank you!!

Get Outlook for Android<https://aka.ms/AAb9ysg>
________________________________
From: Tutor <tutor-bounces+georgenikil=outlook.com at python.org> on behalf of Mats Wichmann <mats at wichmann.us>
Sent: Saturday, February 26, 2022 10:06:45 AM
To: tutor at python.org <tutor at python.org>
Subject: Re: [Tutor] Tutoring co-workers.

On 2/25/22 14:59, trent shipley wrote:
> I'm looking at the possibility of teaching programming to a couple of
> coworkers.  Python is an excellent pedagogical programming language, with
> the added benefit of what you learn being directly applicable and
> marketable in many work contexts.
>
> in the late 1980s, I took
> computer science 110 and 210 in Pascal and turned in the code for my
> assignments on fan-fold paper hard copy.

My first "formal" language was also Pascal (had previously learned
Fortran and Basic outside an academic setting). It was the era of
Pascal, I guess (mine was a little earlier, we had to jockey for the
very small number of cursor-addressable ADM 3a terminals that made
screen-based editing possible).

>
> My goal is to use it for teaching coding by giving the same attention to my
> students' feedback which Marrion Deckert gave to my ealy software writing
> education, but without paper and at a distance.  How close can I come to
> this vaporware ideal?
>
> (Oh yes, and a student should be able to drop their corrected code, with
> all the history and comments hidden, straight into a syntax checker, REPL,
> interpreter, or compiler.)

There are some new and shiny ways to maybe get some of the spirit of
this with some of the online collaborative editing environments, when
combined with a github repo.  It would be very different than red pen on
fanfold paper, but...  I don't know too many of the entrants in this
exploding field, but take a look at Gipod, Replit or Codeshare.
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

From phillor9 at gmail.com  Sat Feb 26 23:55:43 2022
From: phillor9 at gmail.com (Phil)
Date: Sun, 27 Feb 2022 15:55:43 +1100
Subject: [Tutor] Tkinter canvas on frame
Message-ID: <6b3c4594-14a3-5363-5fa3-6e990bf213f7@gmail.com>

This is part of a project I was working on a couple of months ago and I 
didn't notice that there is a problem until today when I added some colours.

The question is, how can I site the canvas on the frame so that the blue 
frame surrounds the canvas? Without the canvas the whole frame is blue. 
I suspect that it's to do with the pack manager.

import tkinter as tk


class Root(tk.Tk):
 ??? def __init__(self):
 ??????? super().__init__()
 ??????? self.title("Canvas Template")
 ??????? self.geometry("400x300")

 ??????? self.frame = tk.Frame(background='cornflowerblue')

 ??????? self.frame.pack(fill=tk.BOTH, expand=1)

 ??????? canvas = tk.Canvas(self, relief='flat', background='lightgrey',
 ?????????????????????????? width=200, height=200)
 ??????? canvas.pack(side=tk.TOP, anchor='nw', padx=10, pady=10)

 ??????? quit_button = tk.Button(self, text="Quit", command=self.quit)
 ??????? quit_button.pack(side=tk.BOTTOM, anchor='se', padx=10, pady=10)


if __name__ == "__main__":
 ??? root = Root()
 ??? root.mainloop()

-- 
Regards,
Phil


From alan.gauld at yahoo.co.uk  Sun Feb 27 03:35:31 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 27 Feb 2022 08:35:31 +0000
Subject: [Tutor] Tkinter canvas on frame
In-Reply-To: <6b3c4594-14a3-5363-5fa3-6e990bf213f7@gmail.com>
References: <6b3c4594-14a3-5363-5fa3-6e990bf213f7@gmail.com>
Message-ID: <svfd4j$p16$1@ciao.gmane.io>

On 27/02/2022 04:55, Phil wrote:

> class Root(tk.Tk):
>  ??? def __init__(self):
>  ??????? super().__init__()
>  ??????? self.title("Canvas Template")
>  ??????? self.geometry("400x300")
> 
>  ??????? self.frame = tk.Frame(background='cornflowerblue')
> 
>  ??????? self.frame.pack(fill=tk.BOTH, expand=1)
> 
>  ??????? canvas = tk.Canvas(self, relief='flat', background='lightgrey',
>  ?????????????????????????? width=200, height=200)
>  ??????? canvas.pack(side=tk.TOP, anchor='nw', padx=10, pady=10)

Try changing the anchor from Northwest('nw') to 'center'


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From alan.gauld at yahoo.co.uk  Sun Feb 27 12:01:33 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Sun, 27 Feb 2022 17:01:33 +0000
Subject: [Tutor] Tkinter canvas on frame
In-Reply-To: <svfd4j$p16$1@ciao.gmane.io>
References: <6b3c4594-14a3-5363-5fa3-6e990bf213f7@gmail.com>
 <svfd4j$p16$1@ciao.gmane.io>
Message-ID: <svgapd$tbb$1@ciao.gmane.io>

On 27/02/2022 08:35, Alan Gauld via Tutor wrote:
> On 27/02/2022 04:55, Phil wrote:
> 
>> class Root(tk.Tk):
>>  ??? def __init__(self):
>>  ??????? super().__init__()
>>  ??????? self.title("Canvas Template")
>>  ??????? self.geometry("400x300")
>>
>>  ??????? self.frame = tk.Frame(background='cornflowerblue')
>>
>>  ??????? self.frame.pack(fill=tk.BOTH, expand=1)
>>
>>  ??????? canvas = tk.Canvas(self, relief='flat', background='lightgrey',
>>  ?????????????????????????? width=200, height=200)
>>  ??????? canvas.pack(side=tk.TOP, anchor='nw', padx=10, pady=10)
> 
> Try changing the anchor from Northwest('nw') to 'center'
> 
> 
I meant to add, if you want a colour border why not just
set the border of the frame? Then you can make the canvas fill it.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From phillor9 at gmail.com  Sun Feb 27 15:26:34 2022
From: phillor9 at gmail.com (Phil)
Date: Mon, 28 Feb 2022 07:26:34 +1100
Subject: [Tutor] Tkinter canvas on frame
In-Reply-To: <svgapd$tbb$1@ciao.gmane.io>
References: <6b3c4594-14a3-5363-5fa3-6e990bf213f7@gmail.com>
 <svfd4j$p16$1@ciao.gmane.io> <svgapd$tbb$1@ciao.gmane.io>
Message-ID: <0bb1f92c-0e59-cfcb-dcdb-bfde65db3b1c@gmail.com>


On 28/2/22 04:01, Alan Gauld via Tutor wrote:

>> Try changing the anchor from Northwest('nw') to 'center'
>>
>>
> I meant to add, if you want a colour border why not just
> set the border of the frame? Then you can make the canvas fill it.

Thank you once again Alan for your helpful replies.

-- 

Regards,
Phil


From george at fischhof.hu  Sun Feb 27 15:45:06 2022
From: george at fischhof.hu (George Fischhof)
Date: Sun, 27 Feb 2022 21:45:06 +0100
Subject: [Tutor] theory: geography and python
In-Reply-To: <DB7PR07MB5093357B91EF67A63341B26CE43E9@DB7PR07MB5093.eurprd07.prod.outlook.com>
References: <DB7PR07MB50931C159B5E803E718E9F04E43D9@DB7PR07MB5093.eurprd07.prod.outlook.com>
 <e53i1hh9fp3emjab1mpk0gq9t1rnlkkgag@4ax.com>
 <DB7PR07MB5093357B91EF67A63341B26CE43E9@DB7PR07MB5093.eurprd07.prod.outlook.com>
Message-ID: <CAFwcP0gLNC9A7oRX8J82Btsf5J46RUOUez1qX4itpZxL+Jd9pg@mail.gmail.com>

Nathan Smith <nathan-tech at hotmail.com> ezt ?rta (id?pont: 2022. febr. 25.,
P, 19:29):

> Hi there,
>
>
> thanks a lot for this!
>
>
> Nathan
>
> On 25/02/2022 17:14, Dennis Lee Bieber wrote:
> > On Thu, 24 Feb 2022 22:35:53 +0000, Nathan Smith <
> nathan-tech at hotmail.com>
> > declaimed the following:
> >
> >> Is there an industry standard for this sort of thing to get the shapes
> >> of countries semi accurate in terms of coordinates and borders? What
> >> sources should be looked at?
> >>
> >       Rather out-of-date by now but the CIA World Databank II had been
> > commonly used.
> >
> >
> https://nam12.safelinks.protection.outlook.com/?url=https%3A%2F%2Fwww.google.com%2Fsearch%3Fq%3Dcia%2Bworld%2Bdatabank%2BII&amp;data=04%7C01%7C%7Cb5389b1849aa4c55d8ee08d9f882770d%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C637814061488668137%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000&amp;sdata=Mvr%2BBTOV%2Blh67qDFswB%2FNxQ%2FXNi1jfwokfCF81AQQok%3D&amp;reserved=0
> >
> >       I'm sure there are more modernized sources (WDB likely still has
> West &
> > East Germany, along with the Berlin air corridors), but they may be as
> part
> > of some $$$ GIS package.
> >
> >
> --
>
> Best Wishes,
>
> Nathan Smith, BSC
>
>
> My Website: https://nathantech.net
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


Hi,

there are some packages which contain country info, also they can be
downloaded from several places

packages:
https://github.com/manumanoj0010/countrydetails
rectangle
https://pypi.org/project/countryinfo/
geojson

https://geopy.readthedocs.io/en/latest/
retrieves data from several map providers

download:
http://download.geonames.org/export/dump/
rectangle


some place contains geojson which contains borders not as a rectangle, but
as line of several points, if you need that.
the standard:
https://geojson.org/


also you can search for download geojson ...

BR,
George

From phillor9 at gmail.com  Sun Feb 27 18:00:31 2022
From: phillor9 at gmail.com (Phil)
Date: Mon, 28 Feb 2022 10:00:31 +1100
Subject: [Tutor] Tkinter canvas on frame
In-Reply-To: <svgapd$tbb$1@ciao.gmane.io>
References: <6b3c4594-14a3-5363-5fa3-6e990bf213f7@gmail.com>
 <svfd4j$p16$1@ciao.gmane.io> <svgapd$tbb$1@ciao.gmane.io>
Message-ID: <6e521b71-3d97-7029-d165-e4504b143edf@gmail.com>


On 28/2/22 04:01, Alan Gauld via Tutor wrote:

> I meant to add, if you want a colour border why not just
> set the border of the frame? Then you can make the canvas fill it.

I've experimented with highlightbackground, highlightthickness, 
borderwidth and various pack options but still the coloured frame sits 
above the canvas rather than surrounding the canvas. I've copied the 
code from several examples but still the same result.

I've seen images showing what I have in mind but I have not discovered 
how it's achieved.

-- 
Regards,
Phil


From alan.gauld at yahoo.co.uk  Sun Feb 27 19:22:22 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 28 Feb 2022 00:22:22 +0000
Subject: [Tutor] Tkinter canvas on frame
In-Reply-To: <6e521b71-3d97-7029-d165-e4504b143edf@gmail.com>
References: <6b3c4594-14a3-5363-5fa3-6e990bf213f7@gmail.com>
 <svfd4j$p16$1@ciao.gmane.io> <svgapd$tbb$1@ciao.gmane.io>
 <6e521b71-3d97-7029-d165-e4504b143edf@gmail.com>
Message-ID: <svh4jv$a3f$1@ciao.gmane.io>

On 27/02/2022 23:00, Phil wrote:

> borderwidth and various pack options but still the coloured frame sits 
> above the canvas rather than surrounding the canvas. I've copied the 
> code from several examples but still the same result.
> 
> I've seen images showing what I have in mind but I have not discovered 
> how it's achieved.
> 
>>> from tkinter import *
>>> top = Tk()
>>> f = Frame(top,background="blue")
>>> f.pack(expand=True)
>>> b = Button(f, text='Hello World')
>>> b.pack(anchor='center', padx=10,pady=10)

Is that what you mean?

It seems I mis-spoke when I suggested a colored border,
you only get the default frame colour

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From andre at fournerat.fr  Sun Feb 27 15:53:13 2022
From: andre at fournerat.fr (=?utf-8?Q?Andr=C3=A9_FOURNERAT?=)
Date: Sun, 27 Feb 2022 21:53:13 +0100
Subject: [Tutor] Use of Python 3 on a Mac
Message-ID: <99835B26-7A10-4D49-9966-DC2BC88AAB92@fournerat.fr>

Hello,

I use a Mac under OS 10.11.6.
I have downloaded Python
I use a book in French ? Apprendre ? programmer avec Python 3 ? (Learning to program with Python 3).
one of the first exercises should read this
>>> a=20
>>> if (a>100):
?		print (? a is more than a hundred ?)
?	else:
?		print (? a is less than a hundred ?)
?
but the result is this with Python 3.9.0
-------------- next part --------------


and it is this with Python 3.10.2
-------------- next part --------------


With earlier version, the result is the same.
What could be the appropriate Python version to work on my Mac?

Best regards
Andr?


From tlinsenmeyer at gmail.com  Sun Feb 27 15:09:28 2022
From: tlinsenmeyer at gmail.com (Tom Linsenmeyer)
Date: Sun, 27 Feb 2022 14:09:28 -0600
Subject: [Tutor] I am having trouble getting some associations to work
Message-ID: <CAEH+u9AtP=muRzy9VSjtb1ExMnS4+YT0+s+ORiQV_Vzu9dXPnw@mail.gmail.com>

I cannot get either self or getmakecar and getmaketruck to associate with
self or def getmakecar() and getmaketruck(). I can get one or the other not
both

Can you please help me
Thank you


import sys
import time


#A program to make a virtual garage

class Vehicles:


  def __init__(self, fueltype, make, carmodel, truckmodel, color):
        """ initialize attributes."""
        self.carmodel = carmodel
        self.truckmodel= truckmodel
        self.Make_ = make
        self.Color_ = color
        self.fueltype_ = fueltype
        make = {'Make1' : 'Chevrolet', 'Make2' : 'Dodge', 'Make3' : 'Ford'}
        carmodel = {'Cmodel' : 'Camaro', "Cmodel2" : 'Corvette',
'Cmodel3' : 'Charger', 'Cmodel4' : 'Challenger'}
        truckmodel = {'Tmodel1' : 'Silverado', 'Tmodel2' :
'Tahoe','Tmodel3' : 'Ram-1500', 'Tmodel4' :'Ram-2500',' Tmodel5' :'F-150',
'Model_' : 'F-250'}
        fueltype = {'fuelType1' : 'Gasoline', 'fuelType2' : 'Diesel',
'fuelType3' : 'FlexFuel'}
        color = {'Color1' : 'White', 'Color2' : 'Black', 'Color3' : 'Blue',
'Color4' : 'Red', 'Color5' : 'Yellow'}

  def mainmenu(self):

          print("Welcome to your garage! Please make a selection")
          print("1: Car")
          print("2: Truck")
          print("3: Quit")
          choice = int(input())
          if choice == 1:
            print("Car")
            getmaker()
          #elif choice == 2:
           # getmakeTruck()
          elif choice == 3:
              quit()
          else:
              print ("Select either Car, Truck or Quit")


  def getmakecar(self):
        print('Pick from cars')
        #self.make#[Make1],[Make2],[Make3]

  def quit(self):
      print("Leaving your garage")
      time.sleep(2)
      sys.exit()



  def getmaketruck(self):
                pass
#class Car(Vehicles):
#  def carmenu():
  #      print("Car Menu")
   # choice = int(input("""
    #                        1: Make
     #                       2: Model
      #                      3: Color
       #                     4: Fuel Type
        #                    5: Options
         #                   6: Quit
          #                          """))


   # if choice == 1:
    #      make()
    #elif choice == 2:
   #     model()
    #elif choice == 3:
     #   color()
    #elif choice == 4:
  #      fueltype()
    #elif choice == 5:
 #    3   options()
   # elif choice == 6:
    #    else:
    #car_menu()

 #   def make(Vehicles):





#options = ['powerlocks', 'powerwindows','powermirrors', 'powerseat',
'premium_sound', 'back_up_camera', 'leather_seats','trailer_package']
#print (make)

-- 
Tom Linsenmeyer
https://emrisinternational.com/Robin

From alan.gauld at yahoo.co.uk  Sun Feb 27 19:49:02 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 28 Feb 2022 00:49:02 +0000
Subject: [Tutor] Use of Python 3 on a Mac
In-Reply-To: <99835B26-7A10-4D49-9966-DC2BC88AAB92@fournerat.fr>
References: <99835B26-7A10-4D49-9966-DC2BC88AAB92@fournerat.fr>
Message-ID: <svh65v$aao$1@ciao.gmane.io>

On 27/02/2022 20:53, Andr? FOURNERAT wrote:

> I use a Mac under OS 10.11.6.
> I have downloaded Python
> I use a book in French ? Apprendre ? programmer avec Python 3 ? (Learning to program with Python 3).
> one of the first exercises should read this
>>>> a=20
>>>> if (a>100):
> ?		print (? a is more than a hundred ?)
> ?	else:
> ?		print (? a is less than a hundred ?)
> ?

I'm guessing the French book uses << >>  as quotes
but your locale uses something different.
Use whatever quote symbols are correct in your locale.

> but the result is this with Python 3.9.0
> 
> and it is this with Python 3.10.2

Unfortunately this is a text only mailing list(for
security and compatibility reasons) so your (presumably)
screenshots got stripped by the server. Please post
all output using plain text only.

Assuming you have a Mac version of python installed
then 3.9 at least should work just fine. 3.10 may
well do too.

Finally, in the line

if (a>100):

The brackets are not needed in Python.

if a>100:

would be the normal way to write it.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From phillor9 at gmail.com  Sun Feb 27 19:51:50 2022
From: phillor9 at gmail.com (Phil)
Date: Mon, 28 Feb 2022 11:51:50 +1100
Subject: [Tutor] Tkinter canvas on frame
In-Reply-To: <svh4jv$a3f$1@ciao.gmane.io>
References: <6b3c4594-14a3-5363-5fa3-6e990bf213f7@gmail.com>
 <svfd4j$p16$1@ciao.gmane.io> <svgapd$tbb$1@ciao.gmane.io>
 <6e521b71-3d97-7029-d165-e4504b143edf@gmail.com> <svh4jv$a3f$1@ciao.gmane.io>
Message-ID: <792f6090-2a71-a88f-dfb2-bf142c4ada1f@gmail.com>


On 28/2/22 11:22, Alan Gauld via Tutor wrote:
>>>> from tkinter import *
>>>> top = Tk()
>>>> f = Frame(top,background="blue")
>>>> f.pack(expand=True)
>>>> b = Button(f, text='Hello World')
>>>> b.pack(anchor='center', padx=10,pady=10)
> Is that what you mean?

Yes, so long as fill=both is include which is what I already have and I 
cannot see where my code differs from yours except for the inclusion of 
canvas. I wonder if canvas is the problem? I'll work on and see.

-- 

Regards,
Phil


From alan.gauld at yahoo.co.uk  Sun Feb 27 19:57:22 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 28 Feb 2022 00:57:22 +0000
Subject: [Tutor] I am having trouble getting some associations to work
In-Reply-To: <CAEH+u9AtP=muRzy9VSjtb1ExMnS4+YT0+s+ORiQV_Vzu9dXPnw@mail.gmail.com>
References: <CAEH+u9AtP=muRzy9VSjtb1ExMnS4+YT0+s+ORiQV_Vzu9dXPnw@mail.gmail.com>
Message-ID: <svh6lj$arb$1@ciao.gmane.io>

On 27/02/2022 20:09, Tom Linsenmeyer wrote:
> I cannot get either self or getmakecar and getmaketruck to associate with
> self or def getmakecar() and getmaketruck(). 

I don't really understand what you mean by that.
In what way does self not associate with self?

I do note that you are trying to call methods of
the class from inside other methods but not prefixing
them with self.

Is that what you mean? For example...

>   def mainmenu(self):
> 
>           print("Welcome to your garage! Please make a selection")
>           print("1: Car")
>           print("2: Truck")
>           print("3: Quit")
>           choice = int(input())
>           if choice == 1:
>             print("Car")
>             getmaker()
>           #elif choice == 2:
>            # getmakeTruck()

Should be

self.getmakeTruck()

Also, you don't seem to have a method or function called getmaker()?

Although, from an OOD point of view those are terrible methods
to have in a Vehicle class! There should be Vehicle sublasses
for both car and truck... But those are design choices.
You seem to be asking about code.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From phillor9 at gmail.com  Mon Feb 28 01:30:59 2022
From: phillor9 at gmail.com (Phil)
Date: Mon, 28 Feb 2022 17:30:59 +1100
Subject: [Tutor] Tkinter canvas on frame
In-Reply-To: <svh4jv$a3f$1@ciao.gmane.io>
References: <6b3c4594-14a3-5363-5fa3-6e990bf213f7@gmail.com>
 <svfd4j$p16$1@ciao.gmane.io> <svgapd$tbb$1@ciao.gmane.io>
 <6e521b71-3d97-7029-d165-e4504b143edf@gmail.com> <svh4jv$a3f$1@ciao.gmane.io>
Message-ID: <9e3b626d-2b4d-94dd-5046-01d87a15a81e@gmail.com>


On 28/2/22 11:22, Alan Gauld via Tutor wrote:

>>>> from tkinter import *
>>>> top = Tk()
>>>> f = Frame(top,background="blue")
>>>> f.pack(expand=True)
>>>> b = Button(f, text='Hello World')
>>>> b.pack(anchor='center', padx=10,pady=10)
> Is that what you mean?

I've modified Alan's code slightly so that it looks more like my own and 
it works perfectly.

import tkinter as tk

top = tk.Tk()
f = tk.Frame(top,background="blue", width = 400, height = 300)
f.pack(fill=tk.BOTH, expand=1)
f.pack_propagate(0)

c = tk.Canvas(f, width = 100, height = 100)
b = tk.Button(f, text='Hello World')

c.pack(anchor='center', padx=10, pady=10)

b.pack(side=tk.BOTTOM, anchor='se', padx=10,pady=10)

As far as I can see the following is substantially the same code except 
that I'm using a class and it displays the blue frame only above the 
canvas. I've played with this for hours and I cannot see why one works 
and the other doesn't.

import tkinter as tk


class Root(tk.Tk):
 ??? def __init__(self):
 ??????? super().__init__()
 ??????? self.title("Canvas Template")
 ??????? self.geometry("400x300")

 ??????? self.frame = tk.Frame(background='cornflowerblue')
 ??????? self.frame.pack(fill=tk.BOTH, expand=1)
 ??????? self.frame.pack_propagate(0)

 ??????? canvas = tk.Canvas(self, relief='flat', background='lightgrey',
 ?????????????????????????? width=200, height=200)

 ??????? canvas.pack(anchor='center', padx=10, pady=10)

 ??????? quit_button = tk.Button(self, text="Quit", command=self.quit)
 ??????? quit_button.pack(side=tk.BOTTOM, anchor='se', padx=10, pady=10)

-- 

Regards,
Phil


From alan.gauld at yahoo.co.uk  Mon Feb 28 05:03:06 2022
From: alan.gauld at yahoo.co.uk (Alan Gauld)
Date: Mon, 28 Feb 2022 10:03:06 +0000
Subject: [Tutor] Tkinter canvas on frame
In-Reply-To: <9e3b626d-2b4d-94dd-5046-01d87a15a81e@gmail.com>
References: <6b3c4594-14a3-5363-5fa3-6e990bf213f7@gmail.com>
 <svfd4j$p16$1@ciao.gmane.io> <svgapd$tbb$1@ciao.gmane.io>
 <6e521b71-3d97-7029-d165-e4504b143edf@gmail.com> <svh4jv$a3f$1@ciao.gmane.io>
 <9e3b626d-2b4d-94dd-5046-01d87a15a81e@gmail.com>
Message-ID: <svi6kq$16n0$1@ciao.gmane.io>

On 28/02/2022 06:30, Phil wrote:

> class Root(tk.Tk):
>  ??? def __init__(self):
>  ??????? super().__init__()
>  ??????? self.title("Canvas Template")
>  ??????? self.geometry("400x300")
> 
>  ??????? self.frame = tk.Frame(background='cornflowerblue')

You need a parent for the frame, which should be self.

>  ??????? self.frame.pack(fill=tk.BOTH, expand=1)
>  ??????? self.frame.pack_propagate(0)
> 
>  ??????? canvas = tk.Canvas(self, relief='flat', background='lightgrey',
>  ?????????????????????????? width=200, height=200)

And the parent of the canvas is the frame not self. This is why the
canvas is on top of the frame.

By making it a fixed size it will look weird when you resize the window.
Its the layout managers job to control size and position inside the
window. Just let it do its job.


>  ??????? canvas.pack(anchor='center', padx=10, pady=10)
> 
>  ??????? quit_button = tk.Button(self, text="Quit", command=self.quit)
>  ??????? quit_button.pack(side=tk.BOTTOM, anchor='se', padx=10, pady=10)

I did this and it seemed to work.


import tkinter as tk


class Root(tk.Tk):
     def __init__(self):
         super().__init__()
         self.title("Canvas Template")

         self.frame = tk.Frame(self, background='cornflowerblue')
         self.frame.pack(side='top', fill='both', expand=True)

         canvas = tk.Canvas(self.frame, relief='flat',
                            background='lightgrey')
         canvas.pack(side='top',anchor='center', fill='both',
                     expand=True, padx=10, pady=10)

         self.quit_button = tk.Button(self, text="Quit", command=self.quit)
         self.quit_button.pack(side=tk.BOTTOM, anchor='se', padx = 10,
pady=10)

r = Root()
r.mainloop()

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



From root.formula1 at gmail.com  Sun Feb 27 22:37:51 2022
From: root.formula1 at gmail.com (Formula Root)
Date: Sun, 27 Feb 2022 22:37:51 -0500
Subject: [Tutor] Tutoring co-workers.
In-Reply-To: <mailman.6.1645981202.28100.tutor@python.org>
References: <mailman.6.1645981202.28100.tutor@python.org>
Message-ID: <CAMOCmONvhrCXb_Kfow3RvcGRUjMpkSOczmyxPFLx+4bq7h1kog@mail.gmail.com>

Trent,

Try:
- replit.com
- codingrooms.com



On Sun, Feb 27, 2022 at 12:01 PM <tutor-request at python.org> wrote:

> Send Tutor mailing list submissions to
>         tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>         https://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>         tutor-request at python.org
>
> You can reach the person managing the list at
>         tutor-owner at python.org
>
> When replying, please edit your Subject line so it is more specific
> than "Re: Contents of Tutor digest..."
> Today's Topics:
>
>    1. Re: Tutoring co-workers. (Nikil George)
>    2. Tkinter canvas on frame (Phil)
>    3. Re: Tkinter canvas on frame (Alan Gauld)
>
>
>
> ---------- Forwarded message ----------
> From: Nikil George <georgenikil at outlook.com>
> To: Mats Wichmann <mats at wichmann.us>, "tutor at python.org" <tutor at python.org
> >
> Cc:
> Bcc:
> Date: Sat, 26 Feb 2022 16:12:58 +0000
> Subject: Re: [Tutor] Tutoring co-workers.
> Thank you!!
>
> Get Outlook for Android<https://aka.ms/AAb9ysg>
> ________________________________
> From: Tutor <tutor-bounces+georgenikil=outlook.com at python.org> on behalf
> of Mats Wichmann <mats at wichmann.us>
> Sent: Saturday, February 26, 2022 10:06:45 AM
> To: tutor at python.org <tutor at python.org>
> Subject: Re: [Tutor] Tutoring co-workers.
>
> On 2/25/22 14:59, trent shipley wrote:
> > I'm looking at the possibility of teaching programming to a couple of
> > coworkers.  Python is an excellent pedagogical programming language, with
> > the added benefit of what you learn being directly applicable and
> > marketable in many work contexts.
> >
> > in the late 1980s, I took
> > computer science 110 and 210 in Pascal and turned in the code for my
> > assignments on fan-fold paper hard copy.
>
> My first "formal" language was also Pascal (had previously learned
> Fortran and Basic outside an academic setting). It was the era of
> Pascal, I guess (mine was a little earlier, we had to jockey for the
> very small number of cursor-addressable ADM 3a terminals that made
> screen-based editing possible).
>
> >
> > My goal is to use it for teaching coding by giving the same attention to
> my
> > students' feedback which Marrion Deckert gave to my ealy software writing
> > education, but without paper and at a distance.  How close can I come to
> > this vaporware ideal?
> >
> > (Oh yes, and a student should be able to drop their corrected code, with
> > all the history and comments hidden, straight into a syntax checker,
> REPL,
> > interpreter, or compiler.)
>
> There are some new and shiny ways to maybe get some of the spirit of
> this with some of the online collaborative editing environments, when
> combined with a github repo.  It would be very different than red pen on
> fanfold paper, but...  I don't know too many of the entrants in this
> exploding field, but take a look at Gipod, Replit or Codeshare.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
>
>
>
> ---------- Forwarded message ----------
> From: Phil <phillor9 at gmail.com>
> To: tutor at python.org
> Cc:
> Bcc:
> Date: Sun, 27 Feb 2022 15:55:43 +1100
> Subject: [Tutor] Tkinter canvas on frame
> This is part of a project I was working on a couple of months ago and I
> didn't notice that there is a problem until today when I added some
> colours.
>
> The question is, how can I site the canvas on the frame so that the blue
> frame surrounds the canvas? Without the canvas the whole frame is blue.
> I suspect that it's to do with the pack manager.
>
> import tkinter as tk
>
>
> class Root(tk.Tk):
>      def __init__(self):
>          super().__init__()
>          self.title("Canvas Template")
>          self.geometry("400x300")
>
>          self.frame = tk.Frame(background='cornflowerblue')
>
>          self.frame.pack(fill=tk.BOTH, expand=1)
>
>          canvas = tk.Canvas(self, relief='flat', background='lightgrey',
>                             width=200, height=200)
>          canvas.pack(side=tk.TOP, anchor='nw', padx=10, pady=10)
>
>          quit_button = tk.Button(self, text="Quit", command=self.quit)
>          quit_button.pack(side=tk.BOTTOM, anchor='se', padx=10, pady=10)
>
>
> if __name__ == "__main__":
>      root = Root()
>      root.mainloop()
>
> --
> Regards,
> Phil
>
>
>
>
>
> ---------- Forwarded message ----------
> From: Alan Gauld <alan.gauld at yahoo.co.uk>
> To: tutor at python.org
> Cc:
> Bcc:
> Date: Sun, 27 Feb 2022 08:35:31 +0000
> Subject: Re: [Tutor] Tkinter canvas on frame
> On 27/02/2022 04:55, Phil wrote:
>
> > class Root(tk.Tk):
> >      def __init__(self):
> >          super().__init__()
> >          self.title("Canvas Template")
> >          self.geometry("400x300")
> >
> >          self.frame = tk.Frame(background='cornflowerblue')
> >
> >          self.frame.pack(fill=tk.BOTH, expand=1)
> >
> >          canvas = tk.Canvas(self, relief='flat', background='lightgrey',
> >                             width=200, height=200)
> >          canvas.pack(side=tk.TOP, anchor='nw', padx=10, pady=10)
>
> Try changing the anchor from Northwest('nw') to 'center'
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> https://mail.python.org/mailman/listinfo/tutor
>

From wlfraed at ix.netcom.com  Mon Feb 28 12:35:28 2022
From: wlfraed at ix.netcom.com (Dennis Lee Bieber)
Date: Mon, 28 Feb 2022 12:35:28 -0500
Subject: [Tutor] I am having trouble getting some associations to work
References: <CAEH+u9AtP=muRzy9VSjtb1ExMnS4+YT0+s+ORiQV_Vzu9dXPnw@mail.gmail.com>
Message-ID: <veup1hl9bdun67drnnpgkate7fs91oqubf@4ax.com>

On Sun, 27 Feb 2022 14:09:28 -0600, Tom Linsenmeyer
<tlinsenmeyer at gmail.com> declaimed the following:

>I cannot get either self or getmakecar and getmaketruck to associate with
>self or def getmakecar() and getmaketruck(). I can get one or the other not
>both
>
>Can you please help me
>Thank you

	Warning: I'm likely to get a bit advanced and picky over some this...

>
>
>import sys
>import time
>
>
>#A program to make a virtual garage
>

	So where is a Garage class? A garage /holds/ vehicles, it is not a
vehicle itself. Though you could get by with a list or dictionary as a
container of vehicles -- it depends upon what operations you need to
implement.

	What are the operations one performs with a garage instance?

>class Vehicles:

	Classes are commonly singular -- each instance of a class represents,
well ONE UNIQUE instance of the class...
>
>
>  def __init__(self, fueltype, make, carmodel, truckmodel, color):
>        """ initialize attributes."""
>        self.carmodel = carmodel
>        self.truckmodel= truckmodel
>        self.Make_ = make
>        self.Color_ = color
>        self.fueltype_ = fueltype

... and this part appears to represent ONE UNIQUE Vehicle. But what is with
both carmodel and truckmodel? A vehicle is one or the other, it does not
represent both at the same instant of time.

>        make = {'Make1' : 'Chevrolet', 'Make2' : 'Dodge', 'Make3' : 'Ford'}
>        carmodel = {'Cmodel' : 'Camaro', "Cmodel2" : 'Corvette',
>'Cmodel3' : 'Charger', 'Cmodel4' : 'Challenger'}
>        truckmodel = {'Tmodel1' : 'Silverado', 'Tmodel2' :
>'Tahoe','Tmodel3' : 'Ram-1500', 'Tmodel4' :'Ram-2500',' Tmodel5' :'F-150',
>'Model_' : 'F-250'}
>        fueltype = {'fuelType1' : 'Gasoline', 'fuelType2' : 'Diesel',
>'fuelType3' : 'FlexFuel'}
>        color = {'Color1' : 'White', 'Color2' : 'Black', 'Color3' : 'Blue',
>'Color4' : 'Red', 'Color5' : 'Yellow'}
>

	What are all these? Besides being local to __init__ (meaning they are
deleted when __init__ exits), they merely replace the input parameters
required when creating an instance (and which you've already saved /in/ the
instance). The use of a dictionary in which the keys are just "info#" is
also rather perplexing. Is someone actually going to input "Make1" on some
screen to select "Chevrolet"? A simple list ["Chevrolet", "Dodge", "Ford"]
can be indexed much faster than having to parse/validate string input (note
that your "Camaro" doesn't have a # on the key).

	Also note that there is nothing implicit in those that would prevent
one picking, say, "Dodge"/"Camaro"/"Diesel".


	These items look like they should be part of the user
interface/database of features, but are not, themselves, part of any
particular vehicle. Furthermore, they are not what I'd consider "vehicle"
nor "garage" -- they look more like some ordering system to specify a
vehicle, which may or may not be available in the "garage".

>  def mainmenu(self):
>
>          print("Welcome to your garage! Please make a selection")
>          print("1: Car")
>          print("2: Truck")
>          print("3: Quit")
>          choice = int(input())
>          if choice == 1:

	Note that, should you attempt to expand this later (say you add
motorcycles) you have to redo ALL the logic for your menu scheme. You might
want to consider designing a generic menu handler that works for all menus.
*** see bottom


>            print("Car")
>            getmaker()

	There is no getmaker() defined, but if it is supposed to be a method of
the Vehicles class, it needs to be called as

		self.getmaker()

	Same for anything else that is a method defined within the class.

>          #elif choice == 2:
>           # getmakeTruck()
>          elif choice == 3:
>              quit()
>          else:
>              print ("Select either Car, Truck or Quit")
>
>
>  def getmakecar(self):

	By the time you could use this method, you have already specified all
the information -- since the call to create an instance of Vehicles looks
like:

aVehicle = Vehicles(fueltype, make, carmodel, truckmodel, color)

{see my above comment about having both car and truck model AT THE SAME
TIME|


***
	Consider (not completely worked out or tested):


def doMenu(items):
	while True:
		for i, itm in enumerate(items):
			print("%5s: %s" % (i, itm[0]))
		inp = input("Enter selection number (blank line to exit)=>
").strip()
		if inp:
			#not a blank line
			chc = int(inp)
			if chc >= 0 and chc < len(items):
				#valid range for selection
				#call the handler function for the selected item
				thing = items[chc][1]()
				return (items[chc][0], thing)
			else:
				print("Selection is not valid -- try again\n\n")
		else:
			return None


def makeCar():
	makes = [ ("Chevrolet", makeChevy), ("Ford", makeFord), ("Dodge",
makeDodge) ]
	thing = doMenu(makes)
	if thing is None:
		print("User canceled procedure")
	else:
		print("Selected is %s" % thing[0])
		return thing[1]

def makeTruck():
	pass

categories = [ ("Car", makeCar), ("Truck", makeTruck) ]

selection = doMenu(categories)
if selection is None:
	print("User aborted operation")
else:
	print ("Selection is %s" % selection[0])
	vehicle = selection[1]
	


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/


From trent.shipley at gmail.com  Mon Feb 28 12:43:04 2022
From: trent.shipley at gmail.com (trent shipley)
Date: Mon, 28 Feb 2022 10:43:04 -0700
Subject: [Tutor] Tutoring co-workers.
In-Reply-To: <c7633c31-a0e6-65cf-ea8a-8861f1d32ec9@wichmann.us>
References: <CAEFLybKx2D=zZO-fUEraak-T1Q9w6UfL0FR3fRLQc98OCZq=DA@mail.gmail.com>
 <c7633c31-a0e6-65cf-ea8a-8861f1d32ec9@wichmann.us>
Message-ID: <CAEFLybLh+dM1bV_B_yCQ94VetMsnQ8WKC6jLu_qJoQ6otT3S=w@mail.gmail.com>

On Sat, Feb 26, 2022 at 8:08 AM Mats Wichmann <mats at wichmann.us> wrote:

> On 2/25/22 14:59, trent shipley wrote:
> > I'm looking at the possibility of teaching programming to a couple of
> > coworkers.  Python is an excellent pedagogical programming language, with
> > the added benefit of what you learn being directly applicable and
> > marketable in many work contexts.
> >
> > in the late 1980s, I took
> > computer science 110 and 210 in Pascal and turned in the code for my
> > assignments on fan-fold paper hard copy.
>
> My first "formal" language was also Pascal (had previously learned
> Fortran and Basic outside an academic setting). It was the era of
> Pascal, I guess (mine was a little earlier, we had to jockey for the
> very small number of cursor-addressable ADM 3a terminals that made
> screen-based editing possible).
>
> >
> > My goal is to use it for teaching coding by giving the same attention to
> my
> > students' feedback which Marrion Deckert gave to my ealy software writing
> > education, but without paper and at a distance.  How close can I come to
> > this vaporware ideal?
> >
> > (Oh yes, and a student should be able to drop their corrected code, with
> > all the history and comments hidden, straight into a syntax checker,
> REPL,
> > interpreter, or compiler.)
>
> There are some new and shiny ways to maybe get some of the spirit of
> this with some of the online collaborative editing environments, when
> combined with a github repo.  It would be very different than red pen on
> fanfold paper, but...  I don't know too many of the entrants in this
> exploding field, but take a look at Gipod, Replit or Codeshare.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor


Thanks Mat.  This looks useful.

From phillor9 at gmail.com  Mon Feb 28 17:43:03 2022
From: phillor9 at gmail.com (Phil)
Date: Tue, 1 Mar 2022 09:43:03 +1100
Subject: [Tutor] Tkinter canvas on frame
In-Reply-To: <svi6kq$16n0$1@ciao.gmane.io>
References: <6b3c4594-14a3-5363-5fa3-6e990bf213f7@gmail.com>
 <svfd4j$p16$1@ciao.gmane.io> <svgapd$tbb$1@ciao.gmane.io>
 <6e521b71-3d97-7029-d165-e4504b143edf@gmail.com> <svh4jv$a3f$1@ciao.gmane.io>
 <9e3b626d-2b4d-94dd-5046-01d87a15a81e@gmail.com>
 <svi6kq$16n0$1@ciao.gmane.io>
Message-ID: <48f3b252-fb3a-ce54-43a6-a5e072dc86cc@gmail.com>


On 28/2/22 21:03, Alan Gauld via Tutor wrote:

> And the parent of the canvas is the frame not self. This is why the
> canvas is on top of the frame.

Thank you very much Alan, that was the cure and it's always obvious once 
the error is pointed out.

> By making it a fixed size it will look weird when you resize the window.
> Its the layout managers job to control size and position inside the
> window. Just let it do its job.

True, I just experimenting with different options.

-- 

Regards,
Phil


From phillor9 at gmail.com  Mon Feb 28 18:52:32 2022
From: phillor9 at gmail.com (Phil)
Date: Tue, 1 Mar 2022 10:52:32 +1100
Subject: [Tutor] Tkinter canvas on frame
In-Reply-To: <svi6kq$16n0$1@ciao.gmane.io>
References: <6b3c4594-14a3-5363-5fa3-6e990bf213f7@gmail.com>
 <svfd4j$p16$1@ciao.gmane.io> <svgapd$tbb$1@ciao.gmane.io>
 <6e521b71-3d97-7029-d165-e4504b143edf@gmail.com> <svh4jv$a3f$1@ciao.gmane.io>
 <9e3b626d-2b4d-94dd-5046-01d87a15a81e@gmail.com>
 <svi6kq$16n0$1@ciao.gmane.io>
Message-ID: <2a8de7b4-a1c7-c740-e38f-b3093e872299@gmail.com>


On 28/2/22 21:03, Alan Gauld via Tutor wrote:

> By making it a fixed size it will look weird when you resize the window.
> Its the layout managers job to control size and position inside the
> window. Just let it do its job.

I understand that the pack manager should be left to automatically 
adjust the size of the window.? However, in the case of a drawn line or 
a shape that extends off the edge of the canvas, isn't it still 
necessary to specifically set the window geometry or is it simply left 
to the user to enlarge the window?

-- 

Regards,
Phil