Re: HEKLP

2021-01-15 Thread Terry Reedy

On 1/16/2021 12:23 AM, Z3PS1 wrote:

NEED HELP WITH MY IDLE
Sent from [1]Mail for Windows 10
References

Visible links
1. https://go.microsoft.com/fwlink/?LinkId=550986


I answer real IDLE questions, but this looks like spam to drive traffic 
to the hidden link, so I am ignoring it.


--
Terry Jan Reedy

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


HEKLP

2021-01-15 Thread Z3PS1
   NEED HELP WITH MY IDLE

    

   Sent from [1]Mail for Windows 10

    

References

   Visible links
   1. https://go.microsoft.com/fwlink/?LinkId=550986
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Exploring terminfo

2021-01-15 Thread Grant Edwards
My previous code didn't work if the terminfo entities contained delay
specifiers because the delay specifier was left in the output
datastream. The case where the terminfo description contains delays,
but the delays aren't needed can be handled by simply removing the delay
specifiers by wrapping ncurses.tigetstr as shown below.

If you really _are_ using a physical terminal which requires delays
and is connected to a real serial port, then I think the only
practical solution is to replace sys.stdout.buffer with something that
quacks like io.BufferedWriter and uses ctypes to call fwrite() and
fflush() on FILE *stdout. That means you've got to do all the ncurses
control via curses.putp() and you can't do things like embed control
sequences in python strings like print(f'{bold}Hi there{norm}')


#!/usr/bin/python

import curses,sys,re

curses.setupterm()

write = sys.stdout.write

def tigetstr(name):
seq = curses.tigetstr(name)
return re.sub(b'\$<[0-9.]+[\*/]{0,2}>', b'', seq)

bold = tigetstr('bold').decode('ascii')
norm = tigetstr('sgr0').decode('ascii')
cls = tigetstr('clear').decode('ascii')
cup = tigetstr('cup')

def goto(row,column):
write(curses.tparm(cup,row,column).decode('ascii'))

def clear():
write(cls)

clear()
name = input("enter name: ")

for row in [3,5,10,20]:
goto(row, row+5)
write(f'{bold}Hi there {name}{norm}')
goto(row+1, row+6)
write(f'Hi there {name}')

goto(24,0)
input("press enter to exit: ")
clear()

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


Re: count consecutive elements

2021-01-15 Thread Tim Chase
On 2021-01-16 03:32, Bischoop wrote:
>> The OP didn't specify what should happen in that case, so it would
>> need some clarification.
> 
> In that case maybe good solution would be to return three of them?

That's the solution I chose in my initial reply, you get a tuple back
of ([list of longest matches], length_of_longest_match)

-tkc


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


Re: binascii.b2a vs ord()

2021-01-15 Thread Bischoop
On 2021-01-10, Chris Angelico  wrote:
>
> Hope that helps!
>

Yep, now it seems more understandable what is going on.
Thanks for you time.

--
Thanks
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Exploring terminfo

2021-01-15 Thread Grant Edwards
On 2021-01-16, Cameron Simpson  wrote:
> On 15Jan2021 18:36, Alan Gauld  wrote:
>>> One difference is that the name prompt is being written to stdout in
>>> the C version and stderr in the Python version. But I don't see why
>>> that would matter.
>>
>>That could make a big difference, the putp() function specifically
>>states that it writes to stdout.
>
> If you want an example of code using the curses.ti* functions with 
> arbitrary Python files, have a gander at this:
>
> https://hg.sr.ht/~cameron-simpson/css/browse/lib/python/cs/upd.py?rev=tip

I don't see how it deals with terminfo strings that have delay
specifiers in them (e.g. vt100). Those delay specifiers need to be
replaced by 0 or more 'pad' characters (default is NUL, but that too
can be specified in the terminfo file).

My initial plan was to call ncurses tputs() function and pass it a
'putchar' callback that passes the output bytes to
sys.stdout.buffer.write(). I haven't gotten that working yet (it's
going to require some cytyptes magic).


--
Grant



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


Re: Exploring terminfo

2021-01-15 Thread Grant Edwards
On 2021-01-16, Greg Ewing  wrote:
> On 16/01/21 7:33 am, Grant Edwards wrote:
>
>> Starting in Python 3., python's stdio file objects are _not_
>> on top of the libc FILE streams: they're directly on top of the file
>> descriptor.
>
> This sounds like rather a bad situation, because it means that
> any C library using stdio is going to interact badly with Python
> stdio.

True, but how many Python programs use C libraries that write to FILE*
streams and need to mix in Python "standard output"?

> Can something be done about this? Maybe Python stdio objects
> should flush all the C stdio streams before writing anything?

There's probably a way to hack the sys.stdout object to make it write
data to the FILE* stream using fwrite(), but it'd be ugly.

--
Grant


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


Re: Exploring terminfo

2021-01-15 Thread Grant Edwards
On 2021-01-16, Chris Angelico  wrote:
> On Sat, Jan 16, 2021 at 1:36 PM Greg Ewing  
> wrote:
>
>> Can something be done about this? Maybe Python stdio objects
>> should flush all the C stdio streams before writing anything?
>>
>
> Surely it should be the other way around? If you use the C stdio
> streams, flush them after use. Like with everything else that you
> flush.

If you want to be able to mix Python output and FILE* output, you have
to flush either/both. You have to flush the Python output everytime
you do a FILE* output, and you have to fflush the FILE* stream every
time you do Python output. Or you have to keep track of which you did
last time.

It's very ugly.

--
Grant


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


Re: Exploring terminfo

2021-01-15 Thread Grant Edwards
On 2021-01-15, Grant Edwards  wrote:
> On 2021-01-15, Grant Edwards  wrote:
>
>> Entities that are parameterized (e.g. goto location) would need to be
>> passed through curses.tiparm() before they're decoded and printed. I'm
>> goign to try that next.
>
> The curses module doesn't expose tiparm, but you can use tparm
> instead

NB: The example code below may fail to work properly if all of the
below are true.

  * You're using a real, physical terminal
 
  * Connected to a real, physical serial port (not a pty)
 
  * Without flow control
 
  * And the terminal requires "pauses" to allow time for the
terminal to execute the some commands before it can accept
further data.

The functionality that is added by tputs() is to insert "padding"
(typically extra NUL bytes) before/after certain certain terminal
operations.

What I _don't_ know at this point is what happens if you're using a
terminfo description that specifies padding, but you're not connected
to a physical terminal via a real serial port.


> #!/usr/bin/python
> import curses,sys
> 
> curses.setupterm()
> 
> write = sys.stdout.write
> 
> bold = curses.tigetstr('bold').decode('ascii')
> norm = curses.tigetstr('sgr0').decode('ascii')
> cls = curses.tigetstr('clear').decode('ascii')
> cup = curses.tigetstr('cup')
> 
> def goto(row,column):
> write(curses.tparm(cup,row,column).decode('ascii'))
> 
> def clear():
> write(cls)
> 
> clear()
> name = input("enter name: ")
> 
> for row in [3,5,10,20]:
> goto(row, row+5)
> write(f'{bold}Hi there {name}{norm}')
> goto(row+1, row+6)
> write(f'Hi there {name}')
> 
> goto(24,0)
> input("press enter to exit: ")
> clear()
>


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


Re: Writing a Python3 ttk.Notebook

2021-01-15 Thread Rich Shepard

On Fri, 15 Jan 2021, Terry Reedy wrote:


IDLE's settings dialog uses a ttk.Notebook. The file is
Lib/idlelib/configdialog.py.


Thanks, Terry! I completely forgot that. I'll study the IDLE's code and
learn from that.

Stay well,

Rich
--
https://mail.python.org/mailman/listinfo/python-list


Re: count consecutive elements

2021-01-15 Thread Bischoop
On 2021-01-14, Tim Chase  wrote:
>
> seems to only return one value so seems to get odd results if I
> specify something like
>
>   get_longest("aaabcccbbb")
>
> which at least here tells me that "c" is the longest run, even though
> aaa, bbb, and ccc are all runs of length 3.  The OP didn't specify
> what should happen in that case, so it would need some clarification.
>
>

In that case maybe good solution would be to return three of them?

--
Thanks

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


Re: Exploring terminfo

2021-01-15 Thread Chris Angelico
On Sat, Jan 16, 2021 at 2:16 PM Greg Ewing  wrote:
>
> On 16/01/21 3:37 pm, Chris Angelico wrote:
> > Surely it should be the other way around? If you use the C stdio
> > streams, flush them after use.
>
> 1. You might not know that you're (implicitly) using C stdio.
>
> 2. There doesn't seem to be an easy way to flush C stdio from
> Python any more.
>

But somewhere along the way, you're finding that there's a problem,
which implies that SOMETHING is calling on C stdio. That thing,
surely, should be the thing responsible for flushing?

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Exploring terminfo

2021-01-15 Thread Greg Ewing

On 16/01/21 3:37 pm, Chris Angelico wrote:

Surely it should be the other way around? If you use the C stdio
streams, flush them after use.


1. You might not know that you're (implicitly) using C stdio.

2. There doesn't seem to be an easy way to flush C stdio from
Python any more.

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


Re: Exploring terminfo

2021-01-15 Thread Cameron Simpson
On 15Jan2021 18:36, Alan Gauld  wrote:
>> One difference is that the name prompt is being written to stdout in
>> the C version and stderr in the Python version. But I don't see why
>> that would matter.
>
>That could make a big difference, the putp() function specifically
>states that it writes to stdout.

If you want an example of code using the curses.ti* functions with 
arbitrary Python files, have a gander at this:

https://hg.sr.ht/~cameron-simpson/css/browse/lib/python/cs/upd.py?rev=tip

It's on PyPI if you want easy installation in addition to the source:

https://pypi.org/project/cs.upd/

I'm not (yet) doing colour with that, but I _am_ doing cursor motions 
etc, since that supports multiple lines of display (typical use case is 
multiple progress bars for parallel tasks).

It looks up and uses a few things, like insert_line etc, since the 
interface with my logging goes: go to the top status line, insert a 
line, write the error message, resume.

>> Now the question: is there a way to tell the curses module to flush
>> its stdout FILE stream?
>
>Indeed. But unless it's trivial it rather defeats the concept of
>using the terminfo functions to create text effects without
>diving into full curses screen control! And that was what I
>was hoping to uncover.
>
>I wonder if I can use the os module to mess with the
>file descriptors hmmm.

That is massive overkill. It is enough to write various strings to your 
desired output and flush it. As encountered earlier, curses strings are 
bytes, and need to be decodes as ASCII for str use.

>Thanks for that snippet, I had no idea that input() wrote
>to stderr

Lots of things like to do that. It is a hack, but it does avoid 
polluting your stdout with prompts. (Taxonomy of Bugs: "plug: a message 
dropped in the middle of the output data stream".)

>nor that Python added a stdout layer on top of libc.

It might put its stdout layer directly on top of fd 1, rather than the C 
stdout system. That rings a bell with me.

>Do you know where that is documented? I'd be interested in
>reading more.

The io module?

Cheers,
Cameron Simpson 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Greg Ewing

On 16/01/21 10:14 am, Michael F. Stemper wrote:

I had no idea that syntax existed, and find it completely at odds
with The Zen of Python.


It's not an *obvious* way, so there's no Zen conflict.

As for why it exists, it's part of the mechanism that implements
imports -- 'import' statements get compiled into a call to
__import__.

It also provides a way of importing something specifed by a
string at runtime, so it can be useful.

--
Greg

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


Re: Exploring terminfo

2021-01-15 Thread Chris Angelico
On Sat, Jan 16, 2021 at 1:36 PM Greg Ewing  wrote:
>
> On 16/01/21 7:33 am, Grant Edwards wrote:
> > Starting in Python 3., python's stdio file objects are _not_
> > on top of the libc FILE streams: they're directly on top of the file
> > descriptor.
>
> This sounds like rather a bad situation, because it means that
> any C library using stdio is going to interact badly with Python
> stdio.
>
> Can something be done about this? Maybe Python stdio objects
> should flush all the C stdio streams before writing anything?
>

Surely it should be the other way around? If you use the C stdio
streams, flush them after use. Like with everything else that you
flush.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Exploring terminfo

2021-01-15 Thread Greg Ewing

On 16/01/21 7:33 am, Grant Edwards wrote:

Starting in Python 3., python's stdio file objects are _not_
on top of the libc FILE streams: they're directly on top of the file
descriptor.


This sounds like rather a bad situation, because it means that
any C library using stdio is going to interact badly with Python
stdio.

Can something be done about this? Maybe Python stdio objects
should flush all the C stdio streams before writing anything?

--
Greg
--
https://mail.python.org/mailman/listinfo/python-list


Re: Writing a Python3 ttk.Notebook

2021-01-15 Thread Terry Reedy

On 1/15/2021 3:51 PM, Rich Shepard wrote:

I want to replace the menu on my application with the more appropriate
notebook. After looking at examples in my reference books and on the Web I
still cannot get it working properly.


IDLE's settings dialog uses a ttk.Notebook.  The file is 
Lib/idlelib/configdialog.py.


--
Terry Jan Reedy

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


Re: Writing a Python3 ttk.Notebook

2021-01-15 Thread MRAB

On 2021-01-16 00:16, Rich Shepard wrote:

On Fri, 15 Jan 2021, Rich Shepard wrote:


Progress: I didn't put the notebook on the main window using grid. Now I
need to find how to specify the position so it's at the top of the window.
I'll read the options on grid.


The notebook tabs are placed on the grid as nb.grid(row=0, column=0,
columnspan=6). But, it's in the center of the main frame and small.

The '.grid' method has a 'sticky' keyword parameter that controls the 
alignment within the grid cell.



All the references I've found in Tkinter books and on the web have small,
stand-alone, samples of notebooks. Is
 the best and most
complete reference for learning how to apply a ttk.Notebook?


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


Re: Writing a Python3 ttk.Notebook

2021-01-15 Thread Rich Shepard

On Fri, 15 Jan 2021, Rich Shepard wrote:


Progress: I didn't put the notebook on the main window using grid. Now I
need to find how to specify the position so it's at the top of the window.
I'll read the options on grid.


The notebook tabs are placed on the grid as nb.grid(row=0, column=0,
columnspan=6). But, it's in the center of the main frame and small.

All the references I've found in Tkinter books and on the web have small,
stand-alone, samples of notebooks. Is
 the best and most
complete reference for learning how to apply a ttk.Notebook?

Regards,

Rich
--
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Chris Angelico
On Sat, Jan 16, 2021 at 10:18 AM dn via Python-list
 wrote:
> >> I am confuzzed.
> >
> > It's a common condition.
>
> There are three components:
> 1 From the Greek: "con" meaning 'against' or 'unable'.
> 2 From tech-jargon (and the Australian habit of shortening every word in
> the English language): "fuzz" is the contraction of two highly-technical
> terms, famously applied in intro courses and by naive job-interviewers.
> 3 From English: the suffix "ed" meaning past tense.
>
> Thus, (smirking!) "confuzzed" is the psychological term for people who
> have never been able to bend their minds around the "fizz-buzz" coding
> challenge.
>
>
> PS am running for cover before @Chris reads this...

Good idea, you never know what I might have been drinking, and
therefore what materials could have been sprayed across the screen
when I read that! :D

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread dn via Python-list
On 16/01/2021 11.40, Michael F. Stemper wrote:
> On 15/01/2021 16.01, Chris Angelico wrote:
>> On Sat, Jan 16, 2021 at 8:56 AM Michael F. Stemper
>>  wrote:
>>>
>>> On 15/01/2021 15.26, Stefan Ram wrote:
 "Michael F. Stemper"  writes:
> On 15/01/2021 14.01, Stefan Ram wrote:
> 
>> __import__( "math" ).sqrt( 4 )
> I had no idea that syntax existed, and find it completely at odds
> with The Zen of Python. I'm torn between forgetting that I ever saw
> it and using it for some evilly-obfuscated code.

     When one collects snippets of Python code that are intended
     to be inserted into programs, a snippet usually would have
     to consist of two parts: One part to be inserted at the top
     of the program, into the imports section, and then the actual
     snippet.
     "__import__" allows to write snippets that can be inserted
     as they are without the need to do insertions at two different
     places. (Possibly with a tool to later normalize the insertions
     to the usual style.)
>>
>> I'm not sure how that works. In Python, you can just put the imports
>> where you want them - why would the __import__ function be needed?

import is 'syntactic sugar' for __import__().

Have you not heard that "sugar is the new smoking"? We're being
encouraged to cut-back or giving it up completely...


More seriously, it's like creating a class object by

MyClass = type('MyClass', (), {})

whereas it's far easier (for most of us) to use

class MyClass( etc )

However, when the power and/or dynamic possibilities of the underlying
code-construct is/are required...


> I have no idea what PEP-8 has to say on the subject. However, my coding
> style *generally* puts all of the imports up front, right after the
> prologue (program description, revision history, uzw).

This is indeed received-wisdom.

However it does not disallow (yuk: double-negative!) coding an import
statement elsewhere, eg a routine which is only executed during some
invocations, but not others.


What you may like to consider about "prolog[ue]s" is whether they belong
'in' the code (plenty of arguments 'for') or within the VCS (plenty of
arguments here too)...

eg1: how easy is it to establish when a particular decision/code-change
was made (more than one week ago)? - particularly if changes were
subsequent made 'on top of' that change?

eg2: is it a good idea to use 'Python constants' to display the
program(me) name and (perhaps) a version number on the
terminal/application window?


>> I am confuzzed.
> 
> It's a common condition.

There are three components:
1 From the Greek: "con" meaning 'against' or 'unable'.
2 From tech-jargon (and the Australian habit of shortening every word in
the English language): "fuzz" is the contraction of two highly-technical
terms, famously applied in intro courses and by naive job-interviewers.
3 From English: the suffix "ed" meaning past tense.

Thus, (smirking!) "confuzzed" is the psychological term for people who
have never been able to bend their minds around the "fizz-buzz" coding
challenge.


PS am running for cover before @Chris reads this...
-- 
Regards =dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Writing a Python3 ttk.Notebook

2021-01-15 Thread Rich Shepard

On Fri, 15 Jan 2021, Rich Shepard wrote:


The file 'application.py' is attached. If I had better docs here I could
probably work a lot of this out by myself.


Progress: I didn't put the notebook on the main window using grid. Now I
need to find how to specify the position so it's at the top of the window.
I'll read the options on grid.

Rich
--
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Chris Angelico
On Sat, Jan 16, 2021 at 9:47 AM Michael F. Stemper  wrote:
>
> On 15/01/2021 16.01, Chris Angelico wrote:
> > On Sat, Jan 16, 2021 at 8:56 AM Michael F. Stemper  
> > wrote:
> >>
> >> On 15/01/2021 15.26, Stefan Ram wrote:
> >>> "Michael F. Stemper"  writes:
>  On 15/01/2021 14.01, Stefan Ram wrote:
>
> > __import__( "math" ).sqrt( 4 )
>  I had no idea that syntax existed, and find it completely at odds
>  with The Zen of Python. I'm torn between forgetting that I ever saw
>  it and using it for some evilly-obfuscated code.
> >>>
> >>> When one collects snippets of Python code that are intended
> >>> to be inserted into programs, a snippet usually would have
> >>> to consist of two parts: One part to be inserted at the top
> >>> of the program, into the imports section, and then the actual
> >>> snippet.
> >>> "__import__" allows to write snippets that can be inserted
> >>> as they are without the need to do insertions at two different
> >>> places. (Possibly with a tool to later normalize the insertions
> >>> to the usual style.)
> >
> > I'm not sure how that works. In Python, you can just put the imports
> > where you want them - why would the __import__ function be needed?
>
> I have no idea what PEP-8 has to say on the subject. However, my coding
> style *generally* puts all of the imports up front, right after the
> prologue (program description, revision history, uzw).

Sure, and that's how I'd normally code too. But if I give you a
snippet like this:

from collections import Counter
ltr_weights = ''.join(Counter(text) & Counter(string.ascii_letters)).elements())

then it's absolutely fine to keep the import next to the code. There's
no need to go to the hassle of splitting the snippet; if you want to,
you can, but the snippet is still a single thing.

The __import__ function doesn't add anything here.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Michael F. Stemper

On 15/01/2021 16.01, Chris Angelico wrote:

On Sat, Jan 16, 2021 at 8:56 AM Michael F. Stemper  wrote:


On 15/01/2021 15.26, Stefan Ram wrote:

"Michael F. Stemper"  writes:

On 15/01/2021 14.01, Stefan Ram wrote:



__import__( "math" ).sqrt( 4 )

I had no idea that syntax existed, and find it completely at odds
with The Zen of Python. I'm torn between forgetting that I ever saw
it and using it for some evilly-obfuscated code.


When one collects snippets of Python code that are intended
to be inserted into programs, a snippet usually would have
to consist of two parts: One part to be inserted at the top
of the program, into the imports section, and then the actual
snippet.
"__import__" allows to write snippets that can be inserted
as they are without the need to do insertions at two different
places. (Possibly with a tool to later normalize the insertions
to the usual style.)


I'm not sure how that works. In Python, you can just put the imports
where you want them - why would the __import__ function be needed?


I have no idea what PEP-8 has to say on the subject. However, my coding
style *generally* puts all of the imports up front, right after the
prologue (program description, revision history, uzw).


I am confuzzed.


It's a common condition.


--
Michael F. Stemper
Life's too important to take seriously.
--
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread dn via Python-list
On 15/01/2021 06.44, Denys Contant wrote:
> I don't understand why sqrt is not a built-in function. 
> Why do we have to first import the function from the math module?
> I use it ALL THE TIME!
> 
> That felt good. Thank you.


Are you 'venting', or do you have a specific frustration-induced question?


Much of my training work centers on HTML5. An issue which you will have
experienced as a user (if not an HTML5 coder), is how long it takes for
certain pages to load or to respond to a 'click'.

We talk of the "weight" of the page. Sadly, in a bid to "capture
eye-balls" and/or to prove how much smarter 'I' am (than any other
web-author/JavaScript-er), there are (far too) many reasons why
web-pages are adorned and accompanied by myriad scripts (and likely,
whole libraries/frameworks), and thus become slow (or 'heavy').


What does this have to do with Python?

As an "interpreted language" Python will (tend to) execute slowly when
compared with a "compiled language".
(ignoring 'shades and grades', and purity of definition)

Another form of delay/slow-ness, is how long it takes a program(me) to
start (in the eyes of the user). Another form of 'weight', and component
of start-up time is how much storage is required to hold the code
(excluding any data).


An advantage of Python is that it has a small 'core'. Mark Summerfield
(author) refers to it as "Python's beautiful heart". The minimised core
(or should that be "optimised"?) is fast to load, and occupies minimal
resource.

As a consequence, you and I may well grumble that we have to import the
math library - every time we code some non-trivial calculation. However,
in doing-so we (should) compute a conscious cost-benefit analysis:
knowing that to include the library will incur a resource-cost, but that
its facilities will improve the accuracy and/or efficiency (eg speed) of
our work. OK, so sign me up!

Contrarily, people who don't 'work with numbers', eg other threads
'here' discussing character manipulation; don't experience any longer
waiting-time or 'suffer' extra resource-cost, due to loading the math
library, from which they/their code will receive no benefit at all!


Thus, one of the philosophies of Python I keenly appreciate (that makes
me "[feel] good", to borrow your words), is that not only are "batteries
included", but I don't have to carry-around any 'spare batteries' that I
don't actually need right now!

(even more applicable when using MicroPython, etc)
-- 
Regards =dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Exploring terminfo

2021-01-15 Thread Grant Edwards
On 2021-01-15, Grant Edwards  wrote:

> Entities that are parameterized (e.g. goto location) would need to be
> passed through curses.tiparm() before they're decoded and printed. I'm
> goign to try that next.

The curses module doesn't expose tiparm, but you can use tparm
instead:

#!/usr/bin/python
import curses,sys

curses.setupterm()

write = sys.stdout.write

bold = curses.tigetstr('bold').decode('ascii')
norm = curses.tigetstr('sgr0').decode('ascii')
cls = curses.tigetstr('clear').decode('ascii')
cup = curses.tigetstr('cup')

def goto(row,column):
write(curses.tparm(cup,row,column).decode('ascii'))

def clear():
write(cls)

clear()
name = input("enter name: ")

for row in [3,5,10,20]:
goto(row, row+5)
write(f'{bold}Hi there {name}{norm}')
goto(row+1, row+6)
write(f'Hi there {name}')

goto(24,0)
input("press enter to exit: ")
clear()

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


Re: Writing a Python3 ttk.Notebook

2021-01-15 Thread Rich Shepard

On Fri, 15 Jan 2021, Dennis Lee Bieber wrote:


Off-hand, I'd suspect you should be adding these to the NOTEBOOK
object "n".


Dennis,

You're correct. The MWE didn't have the proper syntax.

Now, the problem is the notebook doesn't display its tabs on the main
window, while the proper syntax on a separate file opens a window with the
tabs displayed.

The file 'application.py' is attached. If I had better docs here I could
probably work a lot of this out by myself.

Regards,

Rich
#!/usr/bin/env python3

# main file to start application.

from os import environ
import sys
from datetime import datetime
import tkinter as tk
from tkinter import ttk
from tkinter.ttk import Notebook as nb
from tkinter import filedialog
from tkinter import messagebox
from tkinter.font import nametofont
from functools import partial
import model as m
import views as v
import controller as c


class Application(tk.Tk):
""" Application root window """

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

# the top level frame holding notebook, status bar, etc.
self.columnconfigure(0, weight=1)   # helps with frame/app resizing on 
the fly
self.rowconfigure(0, weight=1)  # helps with frame/app resizing on 
the fly
# open application centered on screen; set window width and height
self.appwidth = 1000
self.appheight = 800
# get screen width and height
self.scrwidth = self.winfo_screenwidth()
self.scrheight = self.winfo_screenheight()
# formula to find screen center
self.xLeft = (self.scrwidth/2) - (self.appwidth/2)
self.yTop = (self.scrheight/2) - (self.appheight/2)
# set geometry
self.geometry(str(self.appwidth) + "x" + str(self.appheight) +
  "+" + str(int(self.xLeft)) + "+" + str(int(self.yTop)))

self.title("Main Window Title Goes Here")
self.resizable(width=True, height=True)

datestring = datetime.today().strftime("%Y-%m-%d")

# variables for adjusting font size and style
self.font_bold = tk.BooleanVar()
self.font_size = tk.IntVar()

def set_font(*args):
self.font_spec = 'TkDefaultFont {size} {bold}'.format(
size=font_size.get(),
bold='bold' if font_bold.get() else '')
self.label.config(font=font_spec)
self.font_bold.trace('w', set_font)
self.font_size.trace('w', set_font)

# status bar
self.status = tk.StringVar()
self.statusbar = ttk.Label(self, textvariable=self.status)
self.statusbar.grid(sticky="we", row=3, padx=10)

# notebook
nb = ttk.Notebook(self)

self.tab1 = ttk.Frame(nb) # activities
self.tab2 = ttk.Frame(nb) # people
self.tab3 = ttk.Frame(nb) # locations
self.tab4 = ttk.Frame(nb) # organizations
self.tab5 = ttk.Frame(nb) # reports
self.tab6 = ttk.Frame(nb) # lookup tables

nb.add(self.tab1, text='Activities')
nb.add(self.tab2, text='People')
nb.add(self.tab3, text='Locations')
nb.add(self.tab4, text='Organizationbs')
nb.add(self.tab5, text='Reports')
nb.add(self.tab6, text='Lookups')


if __name__ == "__main__":
app = Application()
app.mainloop()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Chris Angelico
On Sat, Jan 16, 2021 at 9:25 AM Eli the Bearded <*@eli.users.panix.com> wrote:
>
> In comp.lang.python, Chris Angelico   wrote:
> > Michael F. Stemper  wrote:
> >> On 15/01/2021 14.01, Stefan Ram wrote:
> >>> __import__( "math" ).sqrt( 4 )
> >> I had no idea that syntax existed, and find it completely at odds
> >> with The Zen of Python. I'm torn between forgetting that I ever saw
> >> it and using it for some evilly-obfuscated code.
> > I recommend option #2. It is incredibly good fun. For added bonus
> > obscurity, don't import a module directly; import it from some
> > unrelated module, such as "from ast import sys" or "from base64 import
> > re".
>
> Is there an Obfuscated Python contest, like there is with C? I know the
> C ones are often quite interesting, like the 2020 entry that implements
> tic-tac-toe in "Turing complete" sub-language of printf() format strings.
> (Carlini, http://www.ioccc.org/years.html#2020 )
>

No there isn't, but similar abominations have showed up in security
testing. Attempts to (a) create a sandboxed Python, and then (b) break
out of said sandbox, have produced some fairly terrifying (and quite
awesome) demonstrations.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Eli the Bearded
In comp.lang.python, Chris Angelico   wrote:
> Michael F. Stemper  wrote:
>> On 15/01/2021 14.01, Stefan Ram wrote:
>>> __import__( "math" ).sqrt( 4 )
>> I had no idea that syntax existed, and find it completely at odds
>> with The Zen of Python. I'm torn between forgetting that I ever saw
>> it and using it for some evilly-obfuscated code.
> I recommend option #2. It is incredibly good fun. For added bonus
> obscurity, don't import a module directly; import it from some
> unrelated module, such as "from ast import sys" or "from base64 import
> re".

Is there an Obfuscated Python contest, like there is with C? I know the
C ones are often quite interesting, like the 2020 entry that implements
tic-tac-toe in "Turing complete" sub-language of printf() format strings.
(Carlini, http://www.ioccc.org/years.html#2020 )

Elijah
--
with the complexity of fitting the 200k format into a 2k source file
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Exploring terminfo

2021-01-15 Thread Grant Edwards
On 2021-01-15, Grant Edwards  wrote:
> On 2021-01-15, Alan Gauld via Python-list  wrote:
>> On 15/01/2021 17:31, Grant Edwards wrote:
>>
>>> I suspect that the problem is that putp is writing to the libc
>>> "stdout" FILE stream that's declaredin . That stream
>>> layer/object has buffering that is invisible to Python. 
>>
>> That would indeed explain it.
>>
>>> Now the question: is there a way to tell the curses module to flush
>>> its stdout FILE stream?
>>
>> Indeed. But unless it's trivial it rather defeats the concept of
>> using the terminfo functions to create text effects without
>> diving into full curses screen control!
>
> Indeed, that appears to be the case for Python 3.x (unless we can
> figure out a way to flush 's FILE *stdio stream from Python).
> I started a separate thread about that specific topic.

I've already posted code showing how to call fflush(FILE *stdio). An
even cleaner solution is avoid using the libc FILE* stuff
entirely. Just grab the strings you need from ncurses and output them
via Pythons I/O streams:

import curses
curses.setupterm()

bold = curses.tigetstr('bold').decode('ascii')
norm = curses.tigetstr('sgr0').decode('ascii')
cls = curses.tigetstr('clear').decode('ascii')

print(cls,end='')

name = input("enter name: ")

print(f'{bold}Hi there {name}{norm}')

input("press enter to exit: ")


Though that seems to work fine with urxvt, it _might_ not be quite
kosher according the ncurses man page, since it says:

  Parameterized strings should be passed through tparm to instantiate
  them.  All terminfo strings (including the output of tparm) should be
  printed with tputs or putp.

Apparently that's mainly so that it can "apply padding information". I
have no idea what that means:

  The tputs routine applies padding information to the string str and
  outputs it:

Entities that are parameterized (e.g. goto location) would need to be
passed through curses.tiparm() before they're decoded and printed. I'm
goign to try that next.

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


Re: Exploring terminfo

2021-01-15 Thread Grant Edwards
On 2021-01-15, Alan Gauld via Python-list  wrote:
> On 15/01/2021 17:31, Grant Edwards wrote:
>
 cur.putp(cls)
 name = input("Hello, what's your name? ")

 cur.putp(bold)
 print("Nice to meet you ", name)
>
>
>>> putp(clr);
>>> putp(bold);
>>> printf("Enter a name: ");
>>> fgets(line, sizeof(line),stdin);
>>>
>>> printf("Hello %s\n", line);
>>> exit(0);
>
>> One difference is that the name prompt is being written to stdout in
>> the C version and stderr in the Python version. But I don't see why
>> that would matter.
>
> That could make a big difference, the putp() function specifically
> states that it writes to stdout.
>
>> I suspect that the problem is that putp is writing to the libc
>> "stdout" FILE stream that's declaredin . That stream
>> layer/object has buffering that is invisible to Python. 
>
> That would indeed explain it.
>
>> Now the question: is there a way to tell the curses module to flush
>> its stdout FILE stream?
>
> Indeed. But unless it's trivial it rather defeats the concept of
> using the terminfo functions to create text effects without
> diving into full curses screen control! And that was what I
> was hoping to uncover.
>
> I wonder if I can use the os module to mess with the
> file descriptors hmmm.

Yes, but that doesn't help. You need to flush the libc FILE *stdio not
the underlying file descriptor. Here's how you do it:


  import os,ctypes,sys,time
  
  libc = ctypes.CDLL(None, use_errno=True)
  
  import curses as cur
  cur.setupterm()
  
  bold = cur.tigetstr('bold')
  norm = cur.tigetstr('sgr0')
  cls = cur.tigetstr('clear')
  
  cur.putp(cls)
  libc.fflush(None)
  name = input("Enter your name: ")
  cur.putp(bold)
  libc.fflush(None)
  sys.stdout.write("\nNice to meet you " + name + "\n")
  cur.putp(norm);
  libc.fflush(None)
  input("Hit enter to exit")

The call to libc.fflush(None) flushes all output FILE * streams. If
you really just want to flush stdout, to flush just stdout:


  import os,ctypes,sys,time

  libc = ctypes.CDLL(None, use_errno=True)
  stdout = ctypes.c_void_p.in_dll(libc, 'stdout')

  import curses as cur
  cur.setupterm()

  bold = cur.tigetstr('bold')
  norm = cur.tigetstr('sgr0')
  cls = cur.tigetstr('clear')

  cur.putp(cls)
  libc.fflush(stdout)
  name = input("Enter your name: ")
  cur.putp(bold)
  libc.fflush(stdout)
  sys.stdout.write("\nNice to meet you " + name + "\n")
  cur.putp(norm);
  libc.fflush(stdout)
  input("Hit enter to exit")

I'd wrap cur.putp() to make it less ugly:

  import os,ctypes,sys,time

  libc = ctypes.CDLL(None, use_errno=True)
  stdout = ctypes.c_void_p.in_dll(libc, 'stdout')

  import curses as cur
  cur.setupterm()

  def putp(*args):
  sys.stderr.flush()
  sys.stdout.flush()
  cur.putp(*args)
  libc.fflush(stdout)

  bold = cur.tigetstr('bold')
  norm = cur.tigetstr('sgr0')
  cls = cur.tigetstr('clear')

  putp(cls)

  name = input("Enter your name: ")

  putp(bold)
  print("Nice to meet you",name)
  putp(norm);

  input("Hit enter to exit")

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


Re: How to flush 's stdout stream?

2021-01-15 Thread Grant Edwards
On 2021-01-15, Eryk Sun  wrote:
> On 1/15/21, Grant Edwards  wrote:
>> In Python 3.7+, how does one flush the stdout FILE stream? I mean the
>> FILE *declared as 'stdio' in . I'm _not_ asking how to flush the
>> Python file object sys.stdio.
>
> You can flush all output streams via C fflush(NULL).

Brilliant! I read through the fflush() man page earlier but missed that.

fflush(NULL) should work.

> If it has to be just stdout, the code will vary by platform. As far
> as I know, there is no standard way at the ABI level to reference C
> stdin, stdout, and stderr. Typically these are macros at the API
> level. The macro might directly reference the FILE record, or maybe
> it calls an inline function that returns the reference.

That's what I was trying to figure out: whether 'stdio' was actually a
global symbol. On Linux it appears to be. I was afraid it was a macro
that referred indirectly to some per-thread storage or something...

> CPython doesn't have a common wrapper function for this. With
> ctypes, you'll have to special case common platform CRTs such as
> glibc in Linux and ucrt in Windows (possible, but undocumented). For
> example:
>
> import sys
> import time
> import ctypes
>
> if sys.platform == 'win32' and sys.version_info >= (3, 5):
> libc = ucrt = ctypes.CDLL('ucrtbase', use_errno=True)
> IOLBF = 0x0040
> libc.__acrt_iob_func.restype = ctypes.c_void_p
> stdout = ctypes.c_void_p(libc.__acrt_iob_func(1))
> elif sys.platform == 'linux':
> libc = cglobal = ctypes.CDLL(None, use_errno=True)
> IOLBF = 1
> stdout = ctypes.c_void_p.in_dll(libc, 'stdout')

That part I hadn't figured out. I've always used ctypes to call
functions in .so libraries that were explicitly loaded by the Python
app.


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


Re: why sqrt is not a built-in function?

2021-01-15 Thread dn via Python-list
On 16/01/2021 10.49, Michael F. Stemper wrote:
...

> Es ist Feierabend


You had me there for a moment, because spotting a 'double meaning"
(actually triple) my mind succumbing to dissonance, refused to translate
(into English), instead latching onto the last two syllables:-

At one time, tech-jargon included the term "abend". It meant "abnormal
end", and was a more palatable term (to someone) for "crash" - a bit
like the airline which talked of "non-operational termination" instead
of using the same (unpalatable) word!


Yes, not only might it have been literally the end of (your) day. This
conversation does seem to have reached the point of reductio ad absurdum!
-- 
Regards =dn
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Chris Angelico
On Sat, Jan 16, 2021 at 8:56 AM Michael F. Stemper  wrote:
>
> On 15/01/2021 15.26, Stefan Ram wrote:
> > "Michael F. Stemper"  writes:
> >> On 15/01/2021 14.01, Stefan Ram wrote:
> >>> __import__( "math" ).sqrt( 4 )
> >> I had no idea that syntax existed, and find it completely at odds
> >> with The Zen of Python. I'm torn between forgetting that I ever saw
> >> it and using it for some evilly-obfuscated code.
> >
> >When one collects snippets of Python code that are intended
> >to be inserted into programs, a snippet usually would have
> >to consist of two parts: One part to be inserted at the top
> >of the program, into the imports section, and then the actual
> >snippet.
> >"__import__" allows to write snippets that can be inserted
> >as they are without the need to do insertions at two different
> >places. (Possibly with a tool to later normalize the insertions
> >to the usual style.)

I'm not sure how that works. In Python, you can just put the imports
where you want them - why would the __import__ function be needed?

I am confuzzed.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Michael F. Stemper

On 15/01/2021 15.26, Stefan Ram wrote:

"Michael F. Stemper"  writes:

On 15/01/2021 14.01, Stefan Ram wrote:

__import__( "math" ).sqrt( 4 )

I had no idea that syntax existed, and find it completely at odds
with The Zen of Python. I'm torn between forgetting that I ever saw
it and using it for some evilly-obfuscated code.


   When one collects snippets of Python code that are intended
   to be inserted into programs, a snippet usually would have
   to consist of two parts: One part to be inserted at the top
   of the program, into the imports section, and then the actual
   snippet.


This statement led inevitably to:

>>> sqrt = __import__("math").sqrt
>>> sqrt(4)
2.0
>>>

I don't know why; it just did.


   "__import__" allows to write snippets that can be inserted
   as they are without the need to do insertions at two different
   places. (Possibly with a tool to later normalize the insertions
   to the usual style.)


That's much too mature. Es ist Feierabend!

--
Michael F. Stemper
2 Chronicles 19:7
--
https://mail.python.org/mailman/listinfo/python-list


Re: Writing a Python3 ttk.Notebook

2021-01-15 Thread Rich Shepard

On Fri, 15 Jan 2021, MRAB wrote:

You should be adding the frames to the notebook. Also, the tabs are 
'self.tab1', not 'tab1', etc:

n.add(self.tab1, text='Activities')
Similarly for the others.


Thanks. MRAB. This allows me to move on and put pre-built widget pages on
the tabs.

Regards,

Rich
--
https://mail.python.org/mailman/listinfo/python-list


Re: Writing a Python3 ttk.Notebook

2021-01-15 Thread MRAB

On 2021-01-15 20:51, Rich Shepard wrote:

I want to replace the menu on my application with the more appropriate
notebook. After looking at examples in my reference books and on the Web I
still cannot get it working properly.

Here's a small example (nbtest.py):
---8< ---
#!/usr/bin/env python3

import tkinter as tk
from tkinter import ttk
from tkinter.ttk import Notebook as n

class Test(tk.Tk):

  def __init__(self, *args, **kwargs):
  super().__init__(*args, **kwargs)

  # notebook
  n = ttk.Notebook(self)

  self.tab1 = ttk.Frame(n) # activities
  self.tab2 = ttk.Frame(n) # people
  self.tab3 = ttk.Frame(n) # locations
  self.tab4 = ttk.Frame(n) # organizations
  self.tab5 = ttk.Frame(n) # reports
  self.tab6 = ttk.Frame(n) # lookup tables

  self.add(tab1, text='Activities')
  self.add(tab2, text='People')
  self.add(tab3, text='Locations')
  self.add(tab4, text='Organizations')
  self.add(tab5, text='Reports')
  self.add(tab6, text='Lookups')

You should be adding the frames to the notebook. Also, the tabs are 
'self.tab1', not 'tab1', etc:


 n.add(self.tab1, text='Activities')

Similarly for the others.


  n.pack(expand = 1, fill ="both")

if __name__ == "__main__":
  app = Test()
  app.mainloop()
>8 -

python-3.9.1 returns:
$ ./nbtest.py
Traceback (most recent call last):
File "/home/rshepard/development/business_tracker/./nbtest.py", line 32, in 

  app = Test()
File "/home/rshepard/development/business_tracker/./nbtest.py", line 22, in 
__init__
  self.add(tab1, text='Activities')
File "/usr/lib64/python3.9/tkinter/__init__.py", line 2346, in __getattr__
  return getattr(self.tk, attr)
AttributeError: '_tkinter.tkapp' object has no attribute 'add'

Explanation of the error and suggestions for ttk.notebook references are
needed.


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


Re: why sqrt is not a built-in function?

2021-01-15 Thread Chris Angelico
On Sat, Jan 16, 2021 at 8:16 AM Michael F. Stemper  wrote:
>
> On 15/01/2021 14.01, Stefan Ram wrote:
> > "Michael F. Stemper"  writes:
>
> >>   Of these, only EcmaScript has
> >> Math.sqrt() as part of the language, and that could be partly
> >> due to the fact that the language doesn't have any concept of
> >> "import" or "include".
> >
> >You do not need to use the import statement in Python,
> >but can also use the expression
> >
> > __import__( "math" ).sqrt( 4 )
>
> I had no idea that syntax existed, and find it completely at odds
> with The Zen of Python. I'm torn between forgetting that I ever saw
> it and using it for some evilly-obfuscated code.
>

Hehe, it's really nothing to do with the Zen; it's playing around with
internals, so you get whatever you get.

I recommend option #2. It is incredibly good fun. For added bonus
obscurity, don't import a module directly; import it from some
unrelated module, such as "from ast import sys" or "from base64 import
re".

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Michael F. Stemper

On 15/01/2021 14.01, Stefan Ram wrote:

"Michael F. Stemper"  writes:



  Of these, only EcmaScript has
Math.sqrt() as part of the language, and that could be partly
due to the fact that the language doesn't have any concept of
"import" or "include".


   You do not need to use the import statement in Python,
   but can also use the expression

__import__( "math" ).sqrt( 4 )


I had no idea that syntax existed, and find it completely at odds
with The Zen of Python. I'm torn between forgetting that I ever saw
it and using it for some evilly-obfuscated code.

I hope that it satisfies the OP.

--
Michael F. Stemper
I feel more like I do now than I did when I came in.
--
https://mail.python.org/mailman/listinfo/python-list


Writing a Python3 ttk.Notebook

2021-01-15 Thread Rich Shepard

I want to replace the menu on my application with the more appropriate
notebook. After looking at examples in my reference books and on the Web I
still cannot get it working properly.

Here's a small example (nbtest.py):
---8< ---
#!/usr/bin/env python3

import tkinter as tk
from tkinter import ttk
from tkinter.ttk import Notebook as n

class Test(tk.Tk):

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

# notebook
n = ttk.Notebook(self)

self.tab1 = ttk.Frame(n) # activities
self.tab2 = ttk.Frame(n) # people
self.tab3 = ttk.Frame(n) # locations
self.tab4 = ttk.Frame(n) # organizations
self.tab5 = ttk.Frame(n) # reports
self.tab6 = ttk.Frame(n) # lookup tables

self.add(tab1, text='Activities')
self.add(tab2, text='People')
self.add(tab3, text='Locations')
self.add(tab4, text='Organizations')
self.add(tab5, text='Reports')
self.add(tab6, text='Lookups')

n.pack(expand = 1, fill ="both")

if __name__ == "__main__":
app = Test()
app.mainloop()
>8 -

python-3.9.1 returns:
$ ./nbtest.py 
Traceback (most recent call last):

  File "/home/rshepard/development/business_tracker/./nbtest.py", line 32, in 

app = Test()
  File "/home/rshepard/development/business_tracker/./nbtest.py", line 22, in 
__init__
self.add(tab1, text='Activities')
  File "/usr/lib64/python3.9/tkinter/__init__.py", line 2346, in __getattr__
return getattr(self.tk, attr)
AttributeError: '_tkinter.tkapp' object has no attribute 'add'

Explanation of the error and suggestions for ttk.notebook references are
needed.

TIA,

Rich
--
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Chris Angelico
On Sat, Jan 16, 2021 at 7:45 AM Michael F. Stemper  wrote:
> > Languages differ. I don't see why it's so important to focus on just
> > one thing - and to complain that, even though it's in the standard
> > library, you have to use an import command to get it.
>
> You should probably direct this to the person who complained rather than
> the person who showed that the complaint wasn't really consistent with
> modern language direction, while python's handling of the square root
> function is consistent.
>

Sorry, you're right, it looked like I was focusing on you there. Your
post was a convenient one to pick up on, since it had some data -
that's all :) My point about complaining was aimed at the OP, who
started this thread with a rant on the basis of having to "import
math". No offense meant to anyone, least of all you.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Michael F. Stemper

On 15/01/2021 14.02, Chris Angelico wrote:

On Sat, Jan 16, 2021 at 6:21 AM Michael F. Stemper  wrote:

Here's the status of the square root function in various languages,
in the order that I encountered them:

FORTRANPart of the language
Pascal Part of the language
SNOBOL Part of the language
c  Need to #include 
clisp  Part of the language
EcmaScript Part of the language
python Need to import from math
Java   Need to import from java.math

The four that appear to be in the most use currently are c,
EcmaScript, python, and Java. Of these, only EcmaScript has
Math.sqrt() as part of the language, and that could be partly
due to the fact that the language doesn't have any concept of
"import" or "include".



Cool. Now tell me: Of all the languages that have a built-in global
name SQRT (which does not include ECMAScript,


I wasn't looking at how the various languages spell it, I was just looking
at the fact that it could be used directly. Since ECMAScript has a
function Math.sqrt(), I counted it as being a direct part of the
language.


 and for the record, ES
does have imports),


I stand corrected. So I could say something like "import Math.*" and
then use "sqrt()" directly?


  how many of them have a built-in or syntax for
dictionaries/mappings?


Beats me. That wasn't what the OP was complaining about. I just did this
little ad-hoc survey to show that more modern languages don't have an
"inherent" square root function, so python's hardly unique.


  I would put it to you that the ability to look
up something by name in a tree, hashtable, or equivalent, is *at
least* as useful as the ability to calculate a square root.


I don't think that I've used the square root function since I took a
course in geometry in the fall of 2019, so I have no grounds to dispute.


Languages differ. I don't see why it's so important to focus on just
one thing - and to complain that, even though it's in the standard
library, you have to use an import command to get it.


You should probably direct this to the person who complained rather than
the person who showed that the complaint wasn't really consistent with
modern language direction, while python's handling of the square root
function is consistent.


--
Michael F. Stemper
Galatians 3:28
--
https://mail.python.org/mailman/listinfo/python-list


Re: Exploring terminfo

2021-01-15 Thread Grant Edwards
On 2021-01-15, Alan Gauld via Python-list  wrote:
> On 15/01/2021 17:31, Grant Edwards wrote:
>
>> I suspect that the problem is that putp is writing to the libc
>> "stdout" FILE stream that's declaredin . That stream
>> layer/object has buffering that is invisible to Python. 
>
> That would indeed explain it.
>
>> Now the question: is there a way to tell the curses module to flush
>> its stdout FILE stream?
>
> Indeed. But unless it's trivial it rather defeats the concept of
> using the terminfo functions to create text effects without
> diving into full curses screen control!

Indeed, that appears to be the case for Python 3.x (unless we can
figure out a way to flush 's FILE *stdio stream from Python).
I started a separate thread about that specific topic.

> And that was what I was hoping to uncover.
>
> I wonder if I can use the os module to mess with the
> file descriptors hmmm.
>
> Thanks for that snippet, I had no idea that input() wrote
> to stderr nor that Python added a stdout layer on top of libc.

Just to be clear, Python 3.7+ stdio,stdin,stderr layers are _not_ on
top of libc's FILE *stdout, stdin, stderr streams and share nothing
with them other than the spelling of the names and (by default) the
underlying file descriptors.  Python's input/output layers are on top
of file descriptors 0, 1, 2.

Older versions of Python had I/O layers that were on top of libc's
FILE *stdin, *stdout, *stderr.

> Do you know where that is documented? I'd be interested in
> reading more.

I can't find it at the moment. Unfortunately words like "file" and
"stream" are too common for Google.



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


Re: why sqrt is not a built-in function?

2021-01-15 Thread Chris Green
Michael F. Stemper  wrote:
> On 14/01/2021 13.00, Rob Cliffe wrote:
> > On 14/01/2021 17:44, Denys Contant wrote:
> 
> >> I don't understand why sqrt is not a built-in function.
> >> Why do we have to first import the function from the math module?
> >> I use it ALL THE TIME!
> > I agree that, especially if you have experience in other languages, this 
> > feels odd, and I have some sympathy for you.
> 
> I cut my teeth on FORTRAN, which has SQRT() as part of the
> language. At least 3, 4, and 5 did; I never used later versions.
> 
Surely III, IV and V.  I was definitely Fortran IV

-- 
Chris Green
·
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to flush 's stdout stream?

2021-01-15 Thread Eryk Sun
On 1/15/21, Grant Edwards  wrote:
> In Python 3.7+, how does one flush the stdout FILE stream? I mean the
> FILE *declared as 'stdio' in . I'm _not_ asking how to flush the
> Python file object sys.stdio.

You can flush all output streams via C fflush(NULL). If it has to be
just stdout, the code will vary by platform. As far as I know, there
is no standard way at the ABI level to reference C stdin, stdout, and
stderr. Typically these are macros at the API level. The macro might
directly reference the FILE record, or maybe it calls an inline
function that returns the reference. CPython doesn't have a common
wrapper function for this. With ctypes, you'll have to special case
common platform CRTs such as glibc in Linux and ucrt in Windows
(possible, but undocumented). For example:

import sys
import time
import ctypes

if sys.platform == 'win32' and sys.version_info >= (3, 5):
libc = ucrt = ctypes.CDLL('ucrtbase', use_errno=True)
IOLBF = 0x0040
libc.__acrt_iob_func.restype = ctypes.c_void_p
stdout = ctypes.c_void_p(libc.__acrt_iob_func(1))
elif sys.platform == 'linux':
libc = cglobal = ctypes.CDLL(None, use_errno=True)
IOLBF = 1
stdout = ctypes.c_void_p.in_dll(libc, 'stdout')

# ensure that stdout is buffered for this test
# has to be called before stdout is used
libc.setvbuf(stdout, None, IOLBF, 4096)

def test(flush=False):
print(f'test with flush={flush}')
libc.fwrite(b'spam', 1, 4, stdout)
if flush:
libc.fflush(stdout)
time.sleep(5)
libc.fflush(None)
print()

test(flush=False)
test(flush=True)

With flush=False, the test should wait 5 seconds before 'spam' is
flushed to the console/terminal. With flush=True, there should be no
delay.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Michael F. Stemper

On 15/01/2021 14.00, Chris Green wrote:

Michael F. Stemper  wrote:

On 14/01/2021 13.00, Rob Cliffe wrote:

On 14/01/2021 17:44, Denys Contant wrote:



I don't understand why sqrt is not a built-in function.
Why do we have to first import the function from the math module?
I use it ALL THE TIME!

I agree that, especially if you have experience in other languages, this
feels odd, and I have some sympathy for you.


I cut my teeth on FORTRAN, which has SQRT() as part of the
language. At least 3, 4, and 5 did; I never used later versions.


Surely III, IV and V.  I was definitely Fortran IV


I think that the listings for my cross-compiles for the Cyber 1700
actually said "FORTRAN 3" at the top of each page, but that was over
three decades back, so it's a little hazy. There weren't any standards
for it anyway.

You're spot-on for FORTRAN IV.

A quick check of wikipedia shows that the last one was better referred
to as FORTRAN 77, but I think that the NOS command to invoke the
compiler was FTN5.

--
Michael F. Stemper
Galatians 3:28
--
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Chris Angelico
On Sat, Jan 16, 2021 at 6:21 AM Michael F. Stemper  wrote:
> Here's the status of the square root function in various languages,
> in the order that I encountered them:
>
> FORTRANPart of the language
> Pascal Part of the language
> SNOBOL Part of the language
> c  Need to #include 
> clisp  Part of the language
> EcmaScript Part of the language
> python Need to import from math
> Java   Need to import from java.math
>
> The four that appear to be in the most use currently are c,
> EcmaScript, python, and Java. Of these, only EcmaScript has
> Math.sqrt() as part of the language, and that could be partly
> due to the fact that the language doesn't have any concept of
> "import" or "include".
>

Cool. Now tell me: Of all the languages that have a built-in global
name SQRT (which does not include ECMAScript, and for the record, ES
does have imports), how many of them have a built-in or syntax for
dictionaries/mappings? I would put it to you that the ability to look
up something by name in a tree, hashtable, or equivalent, is *at
least* as useful as the ability to calculate a square root. Python
gives you both (since you can raise something to the 0.5th power),
JavaScript in a web browser gives you both, C gives you neither (you
have to #include), and you can fill in the rest yourself.

Languages differ. I don't see why it's so important to focus on just
one thing - and to complain that, even though it's in the standard
library, you have to use an import command to get it.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why sqrt is not a built-in function?

2021-01-15 Thread Michael F. Stemper

On 14/01/2021 13.00, Rob Cliffe wrote:

On 14/01/2021 17:44, Denys Contant wrote:



I don't understand why sqrt is not a built-in function.
Why do we have to first import the function from the math module?
I use it ALL THE TIME!
I agree that, especially if you have experience in other languages, this 
feels odd, and I have some sympathy for you.


I cut my teeth on FORTRAN, which has SQRT() as part of the
language. At least 3, 4, and 5 did; I never used later versions.

Here's the status of the square root function in various languages,
in the order that I encountered them:

FORTRANPart of the language
Pascal Part of the language
SNOBOL Part of the language
c  Need to #include 
clisp  Part of the language
EcmaScript Part of the language
python Need to import from math
Java   Need to import from java.math

The four that appear to be in the most use currently are c,
EcmaScript, python, and Java. Of these, only EcmaScript has
Math.sqrt() as part of the language, and that could be partly
due to the fact that the language doesn't have any concept of
"import" or "include".



--
Michael F. Stemper
This email is to be read by its intended recipient only. Any other party
reading is required by the EULA to send me $500.00.
--
https://mail.python.org/mailman/listinfo/python-list


How to flush 's stdout stream?

2021-01-15 Thread Grant Edwards
In Python 3.7+, how does one flush the stdout FILE stream? I mean the
FILE *declared as 'stdio' in . I'm _not_ asking how to flush the
Python file object sys.stdio.

The problem is that some Python modules write to FILE *stdio, but
don't flush the stream so that the data gets written to the standard
output file descriptor (fd 1). If you need to interleave the output
from those modules with writes from other Python code to fd 1 (via
sys.stdout or whatever), you need a way to flush FILE *stdio.

I know how to use ctypels to call fflush(), but I can't figure out how
to get the FILE *stdio value to pass to fflush().

Is there some os.??? or sys.??? function that I've missed?



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


Re: Exploring terminfo

2021-01-15 Thread Alan Gauld via Python-list
On 15/01/2021 17:31, Grant Edwards wrote:

>>> cur.putp(cls)
>>> name = input("Hello, what's your name? ")
>>>
>>> cur.putp(bold)
>>> print("Nice to meet you ", name)


>> putp(clr);
>> putp(bold);
>> printf("Enter a name: ");
>> fgets(line, sizeof(line),stdin);
>>
>> printf("Hello %s\n", line);
>> exit(0);

> One difference is that the name prompt is being written to stdout in
> the C version and stderr in the Python version. But I don't see why
> that would matter.

That could make a big difference, the putp() function specifically
states that it writes to stdout.

> I suspect that the problem is that putp is writing to the libc
> "stdout" FILE stream that's declaredin . That stream
> layer/object has buffering that is invisible to Python. 

That would indeed explain it.

> Now the question: is there a way to tell the curses module to flush
> its stdout FILE stream?

Indeed. But unless it's trivial it rather defeats the concept of
using the terminfo functions to create text effects without
diving into full curses screen control! And that was what I
was hoping to uncover.

I wonder if I can use the os module to mess with the
file descriptors hmmm.

Thanks for that snippet, I had no idea that input() wrote
to stderr nor that Python added a stdout layer on top of libc.
Do you know where that is documented? I'd be interested in
reading more.

-- 
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


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


Re: Exploring terminfo

2021-01-15 Thread Grant Edwards
On 2021-01-15, Grant Edwards  wrote:

> I suspect that the problem is that putp is writing to the libc
> "stdout" FILE stream that's declaredin . That stream
> layer/object has buffering that is invisible to Python. Python's
> sys.stdout.flush() is flushing the Python file object's output buffers
> to the standard output file descriptor(fd 2).

This problem probably didn't happen with older versions of python
where python's stdout file object was on top of the libc stdout FILE
stream, and calling sys.stdout.flush() flushed both layers of
buffering out to the file descriptor.

Starting in Python 3., python's stdio file objects are _not_
on top of the libc FILE streams: they're directly on top of the file
descriptor.

IOW, Python's stdout file object buffering and ncurses stdout FILE
buffering are independent of each other. They reside "beside" each
other, both writing to the file descriptor whenever they see fit with
no coordination between the two.

--
Grant

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


Re: Exploring terminfo

2021-01-15 Thread Grant Edwards
On 2021-01-15, Alan Gauld via Python-list  wrote:
> On 14/01/2021 16:12, Alan Gauld via Python-list wrote:
>
>> #
>> import curses as cur
>> cur.setupterm()
>> 
>> bold = cur.tigetstr('bold')
>> cls = cur.tigetstr('clear')
>> 
>> cur.putp(cls)
>> name = input("Hello, what's your name? ")
>> 
>> cur.putp(bold)
>> print("Nice to meet you ", name)
>> 
>> input("\nHit enter to exit")
>> ###
>> 
>> I've tried variations on flush both inside and outside
>> the print() - both before and after.
>> I've tried writing to stdout instead of print, but nothing is working.
>> The "Hit enter..." message is in bold but the "Nice..." line isn't.
>
> A bit more exploration and I've got a C version of the same program
> to work (I'll spare you the #includes!):
>
> int main(void){
> char line[20];
> int err = 0;
> char *clr;
> char *bold;
>
> setupterm("xterm",1, &err);
> clr = tigetstr("clear");
> bold = tigetstr("bold");
>
> putp(clr);
> putp(bold);
> printf("Enter a name: ");
> fgets(line, sizeof(line),stdin);
>
> printf("Hello %s\n", line);
> exit(0);
> }

> So the native C functions work as expected.
> Why does the Python wrapper not?

One difference is that the name prompt is being written to stdout in
the C version and stderr in the Python version. But I don't see why
that would matter.

I suspect that the problem is that putp is writing to the libc
"stdout" FILE stream that's declaredin . That stream
layer/object has buffering that is invisible to Python. Python's
sys.stdout.flush() is flushing the Python file object's output buffers
to the standard output file descriptor(fd 2). It is not flushing the
the libc FILE stream's output buffers. That apparently doesn't happen
until input() is called (not sure why input() does that). If you omit
the second input() call, and just write to sys.stdout, then the bold
escape sequence doesn't get output until the program terminates.

Now the question: is there a way to tell the curses module to flush
its stdout FILE stream?

--
Grant





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


Re: Exploring terminfo

2021-01-15 Thread Alan Gauld via Python-list
On 14/01/2021 16:12, Alan Gauld via Python-list wrote:

> #
> import curses as cur
> cur.setupterm()
> 
> bold = cur.tigetstr('bold')
> cls = cur.tigetstr('clear')
> 
> cur.putp(cls)
> name = input("Hello, what's your name? ")
> 
> cur.putp(bold)
> print("Nice to meet you ", name)
> 
> input("\nHit enter to exit")
> ###
> 
> I've tried variations on flush both inside and outside
> the print() - both before and after.
> I've tried writing to stdout instead of print, but nothing is working.
> The "Hit enter..." message is in bold but the "Nice..." line isn't.

A bit more exploration and I've got a C version of the same program
to work (I'll spare you the #includes!):

int main(void){
char line[20];
int err = 0;
char *clr;
char *bold;

setupterm("xterm",1, &err);
clr = tigetstr("clear");
bold = tigetstr("bold");

putp(clr);
putp(bold);
printf("Enter a name: ");
fgets(line, sizeof(line),stdin);

printf("Hello %s\n", line);
exit(0);
}

So the native C functions work as expected.
Why does the Python wrapper not?

-- 
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


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


Re: Exploring terminfo

2021-01-15 Thread Alan Gauld via Python-list
On 14/01/2021 22:11, Grant Edwards wrote:

> Or use a terminfo library:
> 
>   https://github.com/DirectXMan12/py-terminfo
> 
> It _may_ be possible to use ncurses to get the terminfo strings
> required for various functions without actually having ncurses to any
> I/O, but I've never tried that...

That is precisely what the tiXXX family of functions in
the curses module is supposed to enable. I'm just struggling
to get anything other than very basic stuff working!

-- 
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


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


Re: Exploring terminfo

2021-01-15 Thread Alan Gauld via Python-list
On 14/01/2021 23:08, Grant Edwards wrote:

> Alternatively, I think you can use the ncurses library to retrieve the control
> strings (just don't use any ncurses input/output calls), like this example 
> from
> https://stackoverflow.com/questions/6199285/tput-cup-in-python-on-the-commandline:
> 
> from curses import *
> setupterm()
> 
> cols = tigetnum("cols")
> lines = tigetnum("lines")
> print str(cols) + "x" + str(lines)
> 
> place_begin = tparm(tigetstr("cup"), 15, 14)
> place_end = tparm(tigetstr("cup"), 50, 0)
> 
> print place_begin + "-- some text --" + place_end

That's exactly what I'm trying to do but with the character
attributes rather than cursor positioning. I can retrieve values and I
can clear the scrn. But the bold(and inverse and underline etc)
strings don;yt seem to affect print() or stdout.write(). But they do
affect the input() prompt strings.

What is different about the input() prompts? Why are they affected
when print isn't?

I've discovered that I can (sort of) get my code to work if I insert
blank input statements between the various prints. But then I need to
keep hitting return to get the display to show up - not exactly useful.
But the point is that after an input() the subsequent print statements
use the set attributes as desired. What can I insert to get the same
effect without requiring the user to type input between prints?
Or what parameter should I be setting where?

-- 
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


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


Re: Exploring terminfo

2021-01-15 Thread Alan Gauld via Python-list
On 14/01/2021 21:30, Barry Scott wrote:

>> During lockdown I've been digging deeper into the curses module
>> and lately into the ti family of functions that reside there.

> It seems that curses does not allow you to mix raw stdin/stdout with its 
> calls.

That's true of curses after you call initscr()

But the while point of using the tiXXX terminfo
functions is that you don't need to call initscr to
use them, just setupterm() which does no take control
in the same way.

The problem is the tiXXX functions are not well documented
and there are very few tutorials, even in C!

> If all you want is simple things like bold and clear I'd just use the
> ANSI escape sequences directly.

The whole point of terminfo is to avoid having to use
terminal specific control codes.

> Are there any terminals that do not understand ANSI escape sequences

Lots, most significantly the x3270 IBM mainframe terminals.
Now, whether you can run curses and terminfo on a 3270 I
don't know...
But I suspect the Wyse family are non ANSI compliant too
and there are still some of them around. And of course the
standard xterm emulator supports the Tektronic graphics
terminal emulation so there would definitely be a use there.

But to be honest if I was doing this in anger I'd just
use curses. This is more about exploring the module.
The functions are there and so we should be able to
use them and demonstrate them. But for that we need
tutorials/HowTos etc that cover them. I've already
written a curses HowTo, I'd like to extend it to cover
the terminfo bits too. But for now I'm drawing a blank.

-- 
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


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


Re: why sqrt is not a built-in function?

2021-01-15 Thread Rob Cliffe via Python-list



On 14/01/2021 17:44, Denys Contant wrote:

I don't understand why sqrt is not a built-in function.
Why do we have to first import the function from the math module?
I use it ALL THE TIME!
I agree that, especially if you have experience in other languages, this 
feels odd, and I have some sympathy for you.  I am not sure that I can 
give you a 100% satisfactory answer.

But:
    if the math module should be automatically imported, how many other 
modules that _somebody_ uses "all the time" should also be automatically 
be imported?  Python gives you a light-weight framework (fast to load a 
program) with the option to plug in whichever batteries you need, and 
it's not so terrible to remember to write "import math" or similar, 
especially after the first time.


That felt good. Thank you.
Although I hope you have other ways of venting your frustration than 
shouting at newsgroups.  Perhaps juggling balls?

Best wishes
Rob Cliffe
--
https://mail.python.org/mailman/listinfo/python-list