Re: Ask for help about class variable scope (Re: Why doesn't a dictionary work in classes?)

2018-12-28 Thread jfong
eryk sun at 2018/12/27 UTC+8 PM 6:58:33 wrote:
> On 12/27/18, jf...@ms4.hinet.net  wrote:
> >
> > I still don't get it. When I change it to using list comprehension, the
> > problem is still there. (it now has no late-binding variable, right? :-)
> >
>  class Too:
> > ... XS = [15, 15, 15, 15]
> > ... Z4 = [val for val in XS]
> > ... Z5 = [XS[0] for val in XS]
> > ...
> > Traceback (most recent call last):
> >   File "", line 1, in 
> >   File "", line 4, in Too
> >   File "", line 4, in 
> > NameError: name 'XS' is not defined
> >
> > The problem confuse me is that is XS a local variable of the list
> > comprehension?
> 
> XS is not a local variable in the scope of either comprehension. XS is
> local to the class statement's scope. For each comprehension, an
> iterator for the current object referenced by XS gets instantiated
> (early binding) and passed as an argument to the comprehension scope.
> If we disassemble the comprehension code, we find that this iterator
> argument has the creatively illegal name ".0". (The bytecode
> references it by its fast-locals-array index, not its weird name.)
> 
> In the Z5 case, XS is a non-local variable (late binding) in the
> loop-body expression (left-hand side) of the comprehension. That's
> common for Python code. In every iteration of the loop, the
> interpreter looks up the object referenced by the name "XS", which can
> change at any time (e.g. by another thread).

In Python document 4.2.2. Resolution of names, the last paragraph:

"...A class definition is an executable statement that may use and define 
names. These references follow the normal rules for name resolution with an 
exception that unbound local variables are looked up in the global namespace. 
...The scope of names defined in a class block is limited to the class block; 
it does not extend to the code blocks of methods – this includes comprehensions 
and generator expressions since they are implemented using a function scope". 

These statements reflect the following difference:

>>> xy = [1,2]
>>> [dir() for i in xy]
[['.0', 'i'], ['.0', 'i']]
>>> [xy[0] for i in xy]
[1, 1]

>>> class foo():
... xs = [1,2]
... z4 = [dir() for i in xs]
...
>>> foo().z4
[['.0', 'i'], ['.0', 'i']]
>>> class foo():
... xs = [1,2]
... z4 = [xs[0] for i in xs]
...
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in foo
  File "", line 3, in 
NameError: name 'xs' is not defined
>>>

and it goes further:

>>> [dir() for i in xy for j in xy]
[['.0', 'i', 'j'], ['.0', 'i', 'j'], ['.0', 'i', 'j'], ['.0', 'i', 'j']]
>>> class foo():
... xs = [1,2]
... z5 = [dir() for i in xs for j in xs]
...
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3, in foo
  File "", line 3, in 
NameError: name 'xs' is not defined
>>>

That's all I had learn so far, although not understand the design decision 
behind it yet:-(

--Jach

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


Re: dangerous class neighborhood

2018-12-28 Thread Abdur-Rahmaan Janhangeer
thanks, the 3 dots are more explicit, thought was another py trick

yours,

Abdur-Rahmaan Janhangeer
http://www.pythonmembers.club | https://github.com/Abdur-rahmaanJ
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


graded randomness

2018-12-28 Thread Abdur-Rahmaan Janhangeer
greetings,

let us say that i have a box of 5 balls,

green balls - 2 with probability 2/5
red balls 2 - with probability 2/5
blue balls 1 - with probability 1/5

how to program the selection so that the random choices reflect the
probabilities?

-- 
Abdur-Rahmaan Janhangeer
http://www.pythonmembers.club | https://github.com/Abdur-rahmaanJ
Mauritius


Garanti
sans virus. www.avast.com

<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Facing an Error after migrating from python 3.4.1 to python 3.6.6 ( Failed to import the site module )

2018-12-28 Thread Piet van Oostrum
sandeep.ba...@gmail.com writes:

> ``` 
> Error code: 
> -- 
>
>
> Traceback (most recent call last): 
>   File 
> "C:\Users\sandeep\AppData\Local\Programs\Python\Python36-32\Lib\site.py", 
> line 73, in  import os 
>   File 
> "C:\Users\sandeep\AppData\Local\Programs\Python\Python36-32\Lib\os.py", line 
> 652, in  
> from _collections_abc import MutableMapping 
>   File 
> "C:\Users\sandeep\AppData\Local\Programs\Python\Python36-32\Lib\_collections_abc.py",
>  line 58 
> async def _coro(): pass 
> ^ 
> SyntaxError: invalid syntax 
> Failed to import the site module 
>
>  
> After migrating from python 3.4.1 to python 3.6.6 
> while Executing my project, I'm facing this issue and not able to
> resolve it. Can i get any solution for this issue?

Could it be that your PYTHONPATH environment variable is set to a directory in 
Python 3.4.1?

-- 
Piet van Oostrum 
WWW: http://piet.vanoostrum.org/
PGP key: [8DAE142BE17999C4]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: graded randomness

2018-12-28 Thread Ben Bacarisse
Abdur-Rahmaan Janhangeer  writes:

> let us say that i have a box of 5 balls,
>
> green balls - 2 with probability 2/5
> red balls 2 - with probability 2/5
> blue balls 1 - with probability 1/5
>
> how to program the selection so that the random choices reflect the
> probabilities?

>>> import random
>>> random.choice(["green", "green", "red", "red", "blue"])

Not a method that scales particularly well, but there's almost no
context to evaluate solutions.

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


Re: graded randomness

2018-12-28 Thread Abdur-Rahmaan Janhangeer
@Tim

do you have something like

choice(balls)

>>> red

and subsequent repetitions for long enough yield approximately 2/5 times r
2/5 times g and 1/5 b

like one without random choice over list/tuples

Abdur-Rahmaan Janhangeer
http://www.pythonmembers.club | https://github.com/Abdur-rahmaanJ
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: graded randomness

2018-12-28 Thread Chris Angelico
On Sat, Dec 29, 2018 at 12:28 AM Abdur-Rahmaan Janhangeer
 wrote:
>
> woops @ben me too i got that solution but i'm searching for a neater answer.
>
> let us say i'm using it over new data, 1 million data of red blue green can
> be saved by just dealing with the probabilities ^^_

Assuming you're on Python 3.6 or newer, you should be able to use
random.choices() for this.

https://docs.python.org/3/library/random.html#random.choices

>>> random.choices("spam", [10, 1, 3, 2])
['a']

You can get any of the four letters back, but you're more likely to
get 's' than anything else. Is that the sort of thing you're after?

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


Re: graded randomness

2018-12-28 Thread Abdur-Rahmaan Janhangeer
ah yes, powerful enough for further customisations

* scratches head

thanks everybody !

Abdur-Rahmaan Janhangeer
http://www.pythonmembers.club | https://github.com/Abdur-rahmaanJ
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: graded randomness

2018-12-28 Thread Tim Chase
On 2018-12-28 16:15, Abdur-Rahmaan Janhangeer wrote:
> greetings,
> 
> let us say that i have a box of 5 balls,
> 
> green balls - 2 with probability 2/5
> red balls 2 - with probability 2/5
> blue balls 1 - with probability 1/5
> 
> how to program the selection so that the random choices reflect the
> probabilities?

You're looking for what are called "weighted choices" which the
random.choice() function provides as of Py3.6

https://docs.python.org/3/library/random.html#random.choices

>>> from random import choices
>>> distribution = {"green":2, "red": 2, "blue", 1}
>>> data, weights = zip(*distribution.items())
>>> sum(weights)
5
>>> sorted(choices(data, weights=weights, k=20))
['blue', 'blue', 'blue', 'blue', 'green', 'green', 'green', 'green',
'green', 'green', 'green', 'green', 'red', 'red', 'red', 'red',
'red', 'red', 'red', 'red']

-tim




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


Re: graded randomness

2018-12-28 Thread Tim Chase
On 2018-12-28 17:31, Abdur-Rahmaan Janhangeer wrote:
> do you have something like
> 
> choice(balls)
> 
> >>> red  

Don't specify the "k=" (which defaults to 1 if you omit it) and use
the first element of the results:

>>> from random import choices
>>> distribution = {"green":2, "red": 2, "blue": 1}
>>> data, weights = zip(*distribution.items())
>>> choices(data, weights)[0]
'red'


> and subsequent repetitions for long enough yield approximately 2/5
> times r 2/5 times g and 1/5 b

You can sample it yourself:

>>> from collections import defaultdict
>>> a = defaultdict(int)
>>> for i in range(1):
... a[choices(data, weights=weights)[0]] += 1
... 
>>> dict(a)
{'green': 3979, 'red': 4008, 'blue': 2013}

though if you plan to, then it might be better/faster to use
cum_weights instead, calculating it once and then reusing it rather
than having choices() re-calculate the cumulative-weights on every
call.


> like one without random choice over list/tuples

Not sure what you mean by this.

-tkc


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


Re: graded randomness

2018-12-28 Thread Abdur-Rahmaan Janhangeer
woops @ben me too i got that solution but i'm searching for a neater answer.

let us say i'm using it over new data, 1 million data of red blue green can
be saved by just dealing with the probabilities ^^_

Abdur-Rahmaan Janhangeer
http://www.pythonmembers.club | https://github.com/Abdur-rahmaanJ
Mauritius
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: ANNOUNCE: TIB/Rendezvous module for python

2018-12-28 Thread zhen . zhong
Hi, There,

I am an engineer in Taiwan and I was trying to install 
rvpython-2.1final.tar.gz  but it's built up in python 2.x which cannot be 
installed in python 3 or above.

Is there any officially released version of rvpython  compatible 
with python 3 or above?

Thank you, sincerely. 


==
Zhen Zhong  鍾震
Innolux Corporation
TFT PIA CIM1-EA
TEL:037-586000#64734
苗栗縣竹南鎮新竹科學工業園區竹南基地科學路160號
No.160,Kesyue Rd., Chunan Science Park,Miao-Li Country 350,Taiwan
E-mail:zhen.zh...@innolux.com
=

This e-mail and any files transmitted with it are CONFIDENTIAL and 
intended solely for the use of the intended recipient.  If you are not the 
intended recipient or the named addressee, please notify the sender 
immediately and delete this e-mail and any files transmitted with it from 
your system; you should not disseminate, distribute, or copy this e-mail 
and any files transmitted with it, or take any action in reliance on the 
contents of the said e-mail and files.

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


Re: Undocumented issue: Open system call blocks on named pipes (and a feature request)

2018-12-28 Thread Grant Edwards
On 2018-12-27, Daniel Ojalvo via Python-list  wrote:

 open("this_is_a_pipe")
>

Opening a tty device can also block[1].  However, if somebody is using
the open() builtin on tty devices that's probably the least of their
problems.

[1] Technically, opening any character-mode device could block --
serial ports are the only "common" example I can think of.

-- 
Grant Edwards   grant.b.edwardsYow! How many retured
  at   bricklayers from FLORIDA
  gmail.comare out purchasing PENCIL
   SHARPENERS right NOW??

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


Re: Undocumented issue: Open system call blocks on named pipes (and a feature request)

2018-12-28 Thread Chris Angelico
On Sat, Dec 29, 2018 at 4:24 AM Grant Edwards  wrote:
>
> On 2018-12-27, Daniel Ojalvo via Python-list  wrote:
>
>  open("this_is_a_pipe")
> >
>
> Opening a tty device can also block[1].  However, if somebody is using
> the open() builtin on tty devices that's probably the least of their
> problems.

Depending on what you mean by "block", pretty much anything can. It's
not indefinite, but this is clearly an example of blocking behaviour:

rosuav@sikorsky:~$ mkdir gideon_home
rosuav@sikorsky:~$ sshfs gideon: gideon_home/
rosuav@sikorsky:~$ python3
Python 3.8.0a0 (heads/master:8b9c33ea9c, Nov 20 2018, 02:18:50)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> time.time(); open("gideon_home/.bashrc"); time.time()
1546018477.1130645
<_io.TextIOWrapper name='gideon_home/.bashrc' mode='r' encoding='UTF-8'>
1546018477.8339248

Due to the latency introduced by having a completely-out-of-cache
remote access directory, simply opening an ordinary file with an
ordinary path took over half a second. But *this* type of blocking
access is NOT changed by adding os.O_NONBLOCK; it will still take that
half second even if you say "opener=nonblock". OTOH, this form of
blocking is a lot safer - normal file systems [1] might be slow, but
they can't deadlock, whereas a pipe most certainly could.

ChrisA

[1] Of course, you could use fusermount and shenanigans to do
basically anything. But at that point, you're deliberately shooting
yourself in the foot, and all I can advise is "don't do that".
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: dangerous class neighborhood

2018-12-28 Thread Avi Gross
[REAL SUBJECT: an assortment of nothings]

 

Python tricks?

 

Speaking from a tutorial forum, tricks can catch people trying to learn.

 

I am not sure of the history of the ellipsis object. 

 

>>> dir(...)

['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', 
'__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', 
'__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', 
'__subclasshook__']

 

Would you believe it is syntactically valid to use 4 periods in a row by asking 
for the contents like this:

 

>>> __class__



 

My impression is that the main initial use for the ellipsis was as a 
placeholder in a numpy multidimensional array so you can specify which axis you 
want to get all of:

 

https://python-reference.readthedocs.io/en/latest/docs/brackets/ellipsis.html

 

I don’t want to start yet another discussion but there seem to be a range of 
ways to say you want something without quite saying what you want. We have 
mentioned the “pass” argument. We also have the naked colon as in:

 

new = old[ : ]

 

The above will make a shallow copy of a list. It is not really a new symbol but 
what happens when you take from:to and remove the from and the to and allow the 
defaults to take over. It gets murky as often underneath it all there are 
hidden objects like the slice:

 

>>> alpha = list(range(10))

>>> alpha

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 

So you can explicitly index with a slice object or use the colon notation to 
get the same thing:

 

>>> alpha[1:5]

[1, 2, 3, 4]

>>> alpha[slice(1,5)]

[1, 2, 3, 4]

>>> alpha[1:10:2]

[1, 3, 5, 7, 9]

>>> alpha[slice(1,10,2)]

[1, 3, 5, 7, 9]

>>> alpha[5:]

[5, 6, 7, 8, 9]

>>> alpha[slice(5,)]

[0, 1, 2, 3, 4]

>>> alpha[slice(5,None)]

[5, 6, 7, 8, 9]

>>> alpha[:]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> alpha[slice(,)]

SyntaxError: invalid syntax

>>> alpha[slice(None)]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 

Note the placeholder is now the item called “None”

 

The ellipsis can be used here but causes errors.

 

And there are more subtle placeholders with meanings like DOES not exist. Numpy 
has a “nan” and Pandas has NaN and a missing date is NaT and beneath it all 
there are names for a missing int versus float versus who knows what.

 

These can be subtle ideas for a newcomer, even for people who come from 
languages that don’t have the distinctions. For that matter, there are ways to 
say something is infinite which is not the same as saying the maximum value you 
can store in N bits.

 

But I express some caution on calling some of these things tricks. Yes, of 
course they can be tricky. What they often are may well be considered 
additional functionality by way of abstractions. Clearly a key word like “pass” 
may be easier to understand than some of the others.

 

 

From: Abdur-Rahmaan Janhangeer  
Sent: Friday, December 28, 2018 3:46 AM
To: Avi Gross 
Cc: Python 
Subject: Re: dangerous class neighborhood

 

thanks, the 3 dots are more explicit, thought was another py trick

 

yours,

Abdur-Rahmaan Janhangeer
http://www.pythonmembers.club | https://github.com/Abdur-rahmaanJ
Mauritius

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


Re: graded randomness

2018-12-28 Thread Abdur-Rahmaan Janhangeer
well i wanted that to improve the following code:

https://www.pythonmembers.club/2018/12/28/reviving-bertrand-russell-through-python/

that one i used the random list technique

Abdur-Rahmaan Janhangeer
http://www.pythonmembers.club | https://github.com/Abdur-rahmaanJ
Mauritius

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


RE: Undocumented issue: Open system call blocks on named pipes (and a feature request)

2018-12-28 Thread Daniel Ojalvo via Python-list
Thank you for the advice!

I haven't used the opener argument before, but I'll keep it for future 
reference. I think it's still a little kludge-y, but it works.

I agree that previous behavior shouldn't be changed, but I would suggest 
updating the documentation to point it out as a footnote. The current behavior 
is correct just unclear. Most people just learning about the open command 
wouldn't have this expectation. I came across the issue when I had a program 
that would open up all the files in a directory to read a few bytes from the 
beginning. My concern would be someone just making a named pipe over a file 
that a program would open. Arguably, anyone affected by that would be shooting 
themselves in the foot to begin with, but I think there are "security" concerns 
because someone could cause a bit of mischief that would be difficult to 
diagnose.

That all being said, I think I would like to put in a feature request for a 
non-blocking option. How should I go about doing so?

Thanks again,
Dan

-Original Message-
From: Chris Angelico  
Sent: Thursday, December 27, 2018 7:10 PM
To: python-list@python.org
Subject: Re: Undocumented issue: Open system call blocks on named pipes (and a 
feature request)

On Fri, Dec 28, 2018 at 1:38 PM Daniel Ojalvo via Python-list 
 wrote:
>
> Hello,
>
> I've been working on a python3 project and I came across an issue with the 
> open system call that, at the very least, isn't documented. In my humble 
> opinion, the 
> documentation should 
> be updated because folks wouldn't expect open to be a blocking operation and 
> simply error out. Worse yet, open doesn't have an option to make itself 
> non-blocking. You have to use the os system calls to kludge a solution.
>

Hmm. I disagree that the docs are deceptive here; I would normally expect 
open() to block if it needs to. But looking at this as a feature request, it 
seems reasonable. Actually, it's not even that hard to do, since open() is 
already pluggable:

rosuav@sikorsky:~/tmp$ rm rene_magritte
rosuav@sikorsky:~/tmp$ mkfifo rene_magritte rosuav@sikorsky:~/tmp$ ls -l 
rene_magritte
prw-r--r-- 1 rosuav rosuav 0 Dec 28 14:05 rene_magritte rosuav@sikorsky:~/tmp$ 
python3 Python 3.8.0a0 (heads/master:8b9c33ea9c, Nov 20 2018, 02:18:50) [GCC 
6.3.0 20170516] on linux Type "help", "copyright", "credits" or "license" for 
more information.
>>> import os
>>> def nonblock(fn, mode): return os.open(fn, mode | os.O_NONBLOCK)
...
>>> open("rene_magritte", opener=nonblock)
<_io.TextIOWrapper name='rene_magritte' mode='r' encoding='UTF-8'>
>>> _.read(1)
''

> Here is how I reproduced the issue:
>
> root@beefy:~/sandbox# mkfifo this_is_a_pipe

(my example file name is a more subtle reference...)

> I'm doing this to get a fileobject and make it error out if we do have a 
> blocking special file:
> with os.fdopen(os.open(, os.O_RDONLY| os.O_NONBLOCK) , mode='rb') 
> as file_obj:
>
> I think this is mostly a documentation bug because this wouldn't be expected 
> behavior to someone reading the docs, but open is behaving as the fifo man 
> page is documented. The 
> feature request would be to add a non-blocking option to the default open 
> system call.
>

Honestly, I don't think there's a problem with it blocking by default.
Most of Python works that way. But it would be pretty straight-forward to add 
"nonblocking=False" as another keyword-only parameter, and for compatibility 
with existing versions (back as far as 3.3), the opener should work just fine.

ChrisA

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


Re: Undocumented issue: Open system call blocks on named pipes (and a feature request)

2018-12-28 Thread Chris Angelico
On Sat, Dec 29, 2018 at 7:21 AM Daniel Ojalvo  wrote:
>
> Thank you for the advice!
>
> I haven't used the opener argument before, but I'll keep it for future 
> reference. I think it's still a little kludge-y, but it works.

It has a very similar effect to what you were proposing, but still
works within the normal open() ecosystem. Its main benefit is that it
works on existing Pythons, whereas any idea proposed today can't get
into 3.7 and maybe not even 3.8.

> I agree that previous behavior shouldn't be changed, but I would suggest 
> updating the documentation to point it out as a footnote. The current 
> behavior is correct just unclear. Most people just learning about the open 
> command wouldn't have this expectation.
>

That's what I'm not sure about. Do people really have an expectation
of nonblocking behaviour?

> I came across the issue when I had a program that would open up all the files 
> in a directory to read a few bytes from the beginning. My concern would be 
> someone just making a named pipe over a file that a program would open. 
> Arguably, anyone affected by that would be shooting themselves in the foot to 
> begin with, but I think there are "security" concerns because someone could 
> cause a bit of mischief that would be difficult to diagnose.
>

What happens if someone has a subdirectory in there? To be resilient
against everything you might come across, you probably need to check
anyway.

> That all being said, I think I would like to put in a feature request for a 
> non-blocking option. How should I go about doing so?

Hmm, there are a few options. If you reckon it's pretty easy, you
could just go straight to a GitHub pull request, and discuss it there.
Or you could open a bugs.python.org tracker issue and hope someone
else does the coding. Alternatively, you could find out who else
supports the idea by posting to the python-id...@python.org mailing
list.

Of those, I think posting to python-ideas is possibly the best, as
there will likely be some bikeshedding about the name and such.

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


RE: graded randomness

2018-12-28 Thread Avi Gross
Abdur-Rahman

I am sure various modules available have ready-made solutions and I see
others have replied to your question. The usual disclaimers apply. This is
an academic discussion and not a statement of the right or only way to do an
abstract task.

So just a thought. You seem interested in a GENERAL situation where you have
N situations with each having a specific probability and the probabilities
sum to 1.0. If that is right, you are creating a partition where you can
make a data structure listing N ordered items along with their individual
probability. Given such a list, you can create another item that is a
cumulative sum.

In your example, your individual probabilities for ['green', 'red', 'blue']
are [0.4, 0.4, 0.2] but the use of lists is just for illustration. You might
use a Numpy array as they have a cumulative sum function:

import numpy as np
np.cumsum([0.4, 0.4, 0.2])
Returns:
array([0.4, 0.8, 1. ])

or viewed vertically:

np.cumsum([0.4, 0.4, 0.2]).reshape(3,1)
array([[0.4],
   [0.8],
   [1. ]])

Again, we are talking about a GENERAL solution but using this example to
illustrate. To get a weighted probability now, you use the random module (or
anything else) to generate a random number between 0 and 1. You search in
the cumulative sum data structure to find the right range. A random value
less than 0.4 should direct you to using green. If above that but less than
0.8, use red. Else, use blue.

To do this properly, you can decide what data structures makes this easy to
do. Maintaining three independent lists or arrays may not be optimal. 

The main idea is to find a way to segment your choices. So consider a
different common example of rolling a pair of (six sided) standard dice. You
know there are 6**2 possible outcomes. There is only one way to get a sum of
2 by rolling a one and another one. So the probability is 1/36 or .0277...
and you can calculate the probabilities of all the other sums with a 7 being
the most common roll at .1667. In this example your choices are rolls of 2
through 12 or 11 choices. The same logic applies. Generate 11 data measures
and a cumulative sum. Just as illustration, I show code using a Pandas
DataFrame object.

import numpy as np
import pandas as pd
diceSumText = np.array(["two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "eleven", "twelve"])
diceSumVal = np.array(range(2,13))
diceProbability = np.array([1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]) / 36
diceProbCumSum = np.cumsum(diceProbability)

Now combine those:

mydata = pd.DataFrame({"Text": diceSumText, "Value": diceSumVal, "Prob":
diceProbability, "Cum": diceProbCumSum})
print(mydata)

  Text  Value  Prob   Cum
0  two  2  0.027778  0.027778
1three  3  0.06  0.08
2 four  4  0.08  0.17
3 five  5  0.11  0.28
4  six  6  0.138889  0.416667
5seven  7  0.17  0.58
6eight  8  0.138889  0.72
7 nine  9  0.11  0.83
8  ten 10  0.08  0.916667
9   eleven 11  0.06  0.97
10  twelve 12  0.027778  1.00

Again, you can do something any number of ways. This is just one. And in
this format the indentation is not great. 

But it lets you write an algorithm that finds the highest 'index" that still
is below the random number chosen and then select either the text or value
that fits in that partition. Not to repeat, there are many other ways so
feel free to innovate. 


-Original Message-
From: Python-list  On
Behalf Of Abdur-Rahmaan Janhangeer
Sent: Friday, December 28, 2018 2:45 PM
To: Python 
Subject: Re: graded randomness

well i wanted that to improve the following code:

https://www.pythonmembers.club/2018/12/28/reviving-bertrand-russell-through-
python/

that one i used the random list technique

Abdur-Rahmaan Janhangeer
http://www.pythonmembers.club | https://github.com/Abdur-rahmaanJ Mauritius

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

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


Re: Undocumented issue: Open system call blocks on named pipes (and a feature request)

2018-12-28 Thread Cameron Simpson

On 28Dec2018 20:21, Daniel Ojalvo  wrote:
I agree that previous behavior shouldn't be changed, but I would 
suggest updating the documentation to point it out as a footnote. The 
current behavior is correct just unclear. Most people just learning 
about the open command wouldn't have this expectation.


Maybe, maybe not. "Most" is a conjecture. IMO people will only find it 
surprising if they think any filesystem object can be instantly opened.  
However that is a misapprehension on their part.


My personal expectation is that open() will come back when the object is 
open. I don't have a timeframe in mind unless I have a strong 
expectation about _what_ I'm opening.


I came across the issue when I had a program that would open up all the 
files in a directory to read a few bytes from the beginning. My concern 
would be someone just making a named pipe over a file that a program 
would open.


What about a symlink to a magic /dev/tcp/host:port device, initiating a 
TCP connection? Particularly if "host" is down or inaccessible? Etc.


Arguably, anyone affected by that would be shooting themselves in the 
foot to begin with, but I think there are "security" concerns because 
someone could cause a bit of mischief that would be difficult to 
diagnose.


It isn't hard to diagnose at all. Point strace at the hung pogram, see 
it is opening some path, "ls -ld the-path", oooh, it isn't a regular 
file.


The point here is that if a programme opens every file in a directory, 
maybe it should constrain itself to regular files. Opening anything else 
may not just hang, it can have real world side effects. (Usually such 
effect happen at some point after open, for example opening a rewind 
take device will physicially rewind the tape on close, but you've 
committed to that happening by opening it in the first place.)


I think Chris offered the example of a subdirectory to suggest that such 
a programme already has an opnion about what to open and what to leave 
alone (unless is _does_ open() subdirectories, which might be useful but 
is usually misleading and on some OSes unsupported). So the programme 
should be pickier anyway.


That all being said, I think I would like to put in a feature request 
for a non-blocking option. How should I go about doing so?


I agree with the suggestion already made: devise a well thought out 
proposal which fits nicely with the existing open() call (eg an addition 
to the mode argument or something), and describe it clearly in 
python-ideas.


Certainly a number of things can be opened in a "nonblocking" mode, 
which means that reads return instantly if there's no available data, so 
having an open not block isn't unreasonable to want. But it may be 
unreasonable to implement in general: OSes may not support it directly.


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


Re: Ask for help about class variable scope (Re: Why doesn't a dictionary work in classes?)

2018-12-28 Thread jfong
jf...@ms4.hinet.net於 2018年12月28日星期五 UTC+8下午4時04分07秒寫道:
> eryk sun at 2018/12/27 UTC+8 PM 6:58:33 wrote:
> > On 12/27/18, jf...@ms4.hinet.net  wrote:
> > >
> > > I still don't get it. When I change it to using list comprehension, the
> > > problem is still there. (it now has no late-binding variable, right? :-)
> > >
> >  class Too:
> > > ... XS = [15, 15, 15, 15]
> > > ... Z4 = [val for val in XS]
> > > ... Z5 = [XS[0] for val in XS]
> > > ...
> > > Traceback (most recent call last):
> > >   File "", line 1, in 
> > >   File "", line 4, in Too
> > >   File "", line 4, in 
> > > NameError: name 'XS' is not defined
> > >
> > > The problem confuse me is that is XS a local variable of the list
> > > comprehension?
> > 
> > XS is not a local variable in the scope of either comprehension. XS is
> > local to the class statement's scope. For each comprehension, an
> > iterator for the current object referenced by XS gets instantiated
> > (early binding) and passed as an argument to the comprehension scope.
> > If we disassemble the comprehension code, we find that this iterator
> > argument has the creatively illegal name ".0". (The bytecode
> > references it by its fast-locals-array index, not its weird name.)
> > 
> > In the Z5 case, XS is a non-local variable (late binding) in the
> > loop-body expression (left-hand side) of the comprehension. That's
> > common for Python code. In every iteration of the loop, the
> > interpreter looks up the object referenced by the name "XS", which can
> > change at any time (e.g. by another thread).
> 
> In Python document 4.2.2. Resolution of names, the last paragraph:
> 
> "...A class definition is an executable statement that may use and define 
> names. These references follow the normal rules for name resolution with an 
> exception that unbound local variables are looked up in the global namespace. 
> ...The scope of names defined in a class block is limited to the class block; 
> it does not extend to the code blocks of methods – this includes 
> comprehensions and generator expressions since they are implemented using a 
> function scope". 
> 
> These statements reflect the following difference:
> 
> >>> xy = [1,2]
> >>> [dir() for i in xy]
> [['.0', 'i'], ['.0', 'i']]
> >>> [xy[0] for i in xy]
> [1, 1]
> 
> >>> class foo():
> ... xs = [1,2]
> ... z4 = [dir() for i in xs]
> ...
> >>> foo().z4
> [['.0', 'i'], ['.0', 'i']]
> >>> class foo():
> ... xs = [1,2]
> ... z4 = [xs[0] for i in xs]
> ...
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 3, in foo
>   File "", line 3, in 
> NameError: name 'xs' is not defined
> >>>
> 
> and it goes further:
> 
> >>> [dir() for i in xy for j in xy]
> [['.0', 'i', 'j'], ['.0', 'i', 'j'], ['.0', 'i', 'j'], ['.0', 'i', 'j']]
> >>> class foo():
> ... xs = [1,2]
> ... z5 = [dir() for i in xs for j in xs]
> ...
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "", line 3, in foo
>   File "", line 3, in 
> NameError: name 'xs' is not defined
> >>>
> 
> That's all I had learn so far, although not understand the design decision 
> behind it yet:-(
> 
> --Jach

Anyway, it "looks" weird. Isn't it?

>>> xs = [5,6,7,8]
>>> class foo():
... xs = [1,2,3]
... z4 = [xs[i] for i in xs]
...
>>> foo.z4
[6,7,8]

xs in the "for" statement referenced to class variable xs and xs[i] in the body 
referenced to the global xs with i from locals.

PS. Don't bother to reply. This is just for my own documentary:-)
-- 
https://mail.python.org/mailman/listinfo/python-list


Passing back the ERRORLEVEL

2018-12-28 Thread Gisle Vanem

I have trouble understanding why a 'sys.exit(2)' is
*not* passed back to the CMD shell in this little example:

- c:\py_cmd_test.cmd --
@%WinDir%\py.exe -2 -x %~dp0py_cmd_test.cmd & exit /b %ERRORLEVEL%

# The '-x' is for Python to skip the 1st line of this file.
import sys
print ("Hello, I am %s; %s" % (sys.argv[0], sys.version_info))
sys.exit (2)



Executing this in a 4NT shell (from JPsoft), correctly reports:
c:\> py_cmd_test.cmd & echo %errorlevel
Hello, I am C:\py_cmd_test.cmd; sys.version_info(major=2, minor=7, micro=15, 
releaselevel='final', serial=0)
2

But the junk-ware cmd.exe does not:
C:\>py_cmd_test.cmd & echo %ERRORLEVEL%
Hello, I am C:\py_cmd_test.cmd; sys.version_info(major=2, minor=7, micro=15, 
releaselevel='final', serial=0)
0

Anybody here who can spot the problem?

Same issue with 'py -3'. I'm on Windows-10.

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