Re: meaning of: line, =

2015-02-05 Thread ast


"ast"  a écrit dans le message de 
news:54d227ef$0$3292$426a7...@news.free.fr...

thanks for the answers 


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


Re: meaning of: line, =

2015-02-05 Thread Devin Jeanpierre
On Wed, Feb 4, 2015 at 1:18 PM, Chris Angelico  wrote:
> On Thu, Feb 5, 2015 at 4:36 AM, Peter Otten <__pete...@web.de> wrote:
>> Another alternative is to put a list literal on the lefthand side:
>>
> def f(): yield 42
>>
>> ...
> [result] = f()
> result
>> 42
>
> Huh, was not aware of that alternate syntax.

Nor are most people. Nor is Python, in some places -- it seems like
people forgot about it when writing some bits of the grammar.

I'd suggest not using it.

>> (If you're worried: neither the list nor the tuple will be created; the
>> bytecode is identical in both cases)
>
> It can't possibly be created anyway. Python doesn't have a notion of
> "assignable thing that, when assigned to, will assign to something
> else" like C's pointers or C++'s references. There's nothing that you
> could put into the list that would have this behaviour.

C pointers don't do that either. It's really just references. (C
pointers aren't any more action-at-a-distance than Python attributes.)

Anyway, it could create a new list in Python, because Python can do
whatever it wants. But it doesn't, because as you say, that wouldn't
do anything.

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


Re: meaning of: line, =

2015-02-05 Thread Steven D'Aprano
Devin Jeanpierre wrote:

> On Wed, Feb 4, 2015 at 1:18 PM, Chris Angelico  wrote:
>> On Thu, Feb 5, 2015 at 4:36 AM, Peter Otten <__pete...@web.de> wrote:
>>> Another alternative is to put a list literal on the lefthand side:
>>>
>> def f(): yield 42
>>>
>>> ...
>> [result] = f()
>> result
>>> 42
>>
>> Huh, was not aware of that alternate syntax.
> 
> Nor are most people. Nor is Python, in some places -- it seems like
> people forgot about it when writing some bits of the grammar.

Got an example where you can use a,b but not [a,b] or (a,b)?




-- 
Steven

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


Re: Indentation issues with python

2015-02-05 Thread Denis McMahon
On Wed, 04 Feb 2015 19:07:53 -0800, syed khalid wrote:

> I downloaded this code and am attempting to run it. I keep getting
> indentation error.

> class EventHubClient(object):
> def sendMessage(self,body,partition):eventHubHost =
> "pac-ns.servicebus.windows.net"
>httpclient = _HTTPClient(service_instance=self)

> def sendMessage(self,body,partition):
> ^

> IndentationError: expected an indented block
> ***
> sasKeyName = "SendPolicy"
> sasKeyValue = "erENqf/5wdWCNEbCA9NsDIRqd5MRKdkii07+wezl/NU="

class starts a class definition. def starts a function (or method) 
definition. The parser expects these definitions to be followed by one or 
more indented lines being the code of the class or function (method).

The following lines down to either a return or the next function 
definition line should probably all be indented.

eg:

class EventHubClient(object):

def sendMessage(self,body,partition):
eventHubHost = "pac-ns.servicebus.windows.net"
httpclient = _HTTPClient(service_instance=self)
sasKeyName = "SendPolicy"
sasKeyValue = "erENqf/5wdWCNEbCA9NsDIRqd5MRKdkii07+wezl/NU="
.. more indented code should probably follow

Getting the indentation correct is absolutely critical in Python.

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Usage of some pastebin service proposed

2015-02-05 Thread Skip Montanaro
On Wed, Feb 4, 2015 at 10:53 PM, Abhiram R  wrote:
> So is it possible to let everyone know that they need to paste their code
on
> some site like pastebin.com and give us the link here so help can be
> provided better?

Better would be to attach small code snippets.

I agree with Ben about the HTML mail thing. If you insist on using that
(sometimes I get into non-plain-text mode in Gmail and forget to turn it
off), then use whatever facility your mailer has for quoting text, and set
the font to fixed width.

try:
> opts, args = getopt.getopt(args, "o:i:f:F:DHnh")
> except getopt.GetoptError, msg:
> usage(msg)
> return 1


old-school-argument-parsing-ly, y'rs,

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


Re: meaning of: line, =

2015-02-05 Thread Ian Kelly
On Thu, Feb 5, 2015 at 2:40 AM, Steven D'Aprano
 wrote:
> Devin Jeanpierre wrote:
>
>> On Wed, Feb 4, 2015 at 1:18 PM, Chris Angelico  wrote:
>>> On Thu, Feb 5, 2015 at 4:36 AM, Peter Otten <__pete...@web.de> wrote:
 Another alternative is to put a list literal on the lefthand side:

>>> def f(): yield 42

 ...
>>> [result] = f()
>>> result
 42
>>>
>>> Huh, was not aware of that alternate syntax.
>>
>> Nor are most people. Nor is Python, in some places -- it seems like
>> people forgot about it when writing some bits of the grammar.
>
> Got an example where you can use a,b but not [a,b] or (a,b)?

>>> def f(a, (b, c)):
... print a, b, c
...
>>> f(3, [4, 5])
3 4 5
>>> def g(a, [b, c]):
  File "", line 1
def g(a, [b, c]):
 ^
SyntaxError: invalid syntax

Although to be fair, the first syntax there is no longer valid either
in Python 3.
-- 
https://mail.python.org/mailman/listinfo/python-list


Monte Carlo probability calculation in Python

2015-02-05 Thread Paul Moore
I'm interested in prototyping a Monte Carlo type simulation algorithm in 
Python. The background is that a friend has written a similar program in C++, 
and I'm interested in seeing if I can achieve something comparable in a much 
better language :-)

The basic job of the program will be to simulate games of chance - so we'll 
have random inputs (die rolls, card draws, etc) and repeatedly simulate 
calculating a "result". Based on the results of the simulation, the idea is to 
estimate the probability of a given result.

So, to give a very specific example:

import random

def die(n, sides=6):
total = sum(random.randint(1, sides) for i in range(n))
return total

def simulate(n, test):
"Run the simulation N times, returning the probability that TEST is true"
successes = 0
for i in range(n):
if test():
successes = successes + 1
return successes/n

def check_3d6_gt_15():
return die(3) > 15

if __name__ == '__main__':
print(simulate(10, check_3d6_gt_15))

Obviously, this is going to run ridiculously slowly as the number of 
simulations or the complexity of the calculation increases, but this gives the 
idea.

My immediate instinct is that somewhere in the scipy stack, there will be a 
module that does this sort of thing efficiently, but I don't really know where 
to look - my understanding of the maths involved is very much at the naive 
level above, so I'm not sure what terms I should be searching for, or how to 
frame a query.

Can anyone give me some pointers as to where I should go to find out more about 
this sort of task? Either more general theory (that would help me ask the right 
questions!) or specific packages or techniques I should be using in 
Python/numpy would be fantastic. 

Any help would be gratefully accepted - surely nobody wants to see Python 
beaten by a C++ program??? :-)

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


Re: Monte Carlo probability calculation in Python

2015-02-05 Thread Joel Goldstick
On Thu, Feb 5, 2015 at 11:20 AM, Paul Moore  wrote:

> I'm interested in prototyping a Monte Carlo type simulation algorithm in
> Python. The background is that a friend has written a similar program in
> C++, and I'm interested in seeing if I can achieve something comparable in
> a much better language :-)
>
> The basic job of the program will be to simulate games of chance - so
> we'll have random inputs (die rolls, card draws, etc) and repeatedly
> simulate calculating a "result". Based on the results of the simulation,
> the idea is to estimate the probability of a given result.
>
> So, to give a very specific example:
>
> import random
>
> def die(n, sides=6):
> total = sum(random.randint(1, sides) for i in range(n))
> return total
>
> def simulate(n, test):
> "Run the simulation N times, returning the probability that TEST is
> true"
> successes = 0
> for i in range(n):
> if test():
> successes = successes + 1
> return successes/n
>
> def check_3d6_gt_15():
> return die(3) > 15
>
> if __name__ == '__main__':
> print(simulate(10, check_3d6_gt_15))
>
> Obviously, this is going to run ridiculously slowly as the number of
> simulations or the complexity of the calculation increases, but this gives
> the idea.
>
> My immediate instinct is that somewhere in the scipy stack, there will be
> a module that does this sort of thing efficiently, but I don't really know
> where to look - my understanding of the maths involved is very much at the
> naive level above, so I'm not sure what terms I should be searching for, or
> how to frame a query.
>
> Can anyone give me some pointers as to where I should go to find out more
> about this sort of task? Either more general theory (that would help me ask
> the right questions!) or specific packages or techniques I should be using
> in Python/numpy would be fantastic.
>
> Any help would be gratefully accepted - surely nobody wants to see Python
> beaten by a C++ program??? :-)
>
> Thanks,
> Paul
> --
> https://mail.python.org/mailman/listinfo/python-list
>

have you googled "python monte carlo"?

-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Monte Carlo probability calculation in Python

2015-02-05 Thread Paul Moore
On Thursday, 5 February 2015 16:28:07 UTC, Joel Goldstick  wrote:
> have you googled "python monte carlo"?

Yes. And a number of other variations. None gave anything that seemed to 
relate. It's quite likely though that I'm simply not understanding how things 
like pymc (which came up in the searches) might help me, or how to convert my 
problem into a Monte Carlo integration problem (another topic that came up a 
lot, for example). So if there are specific links from such a search that match 
well to the problem as I described it above, I'd be really grateful for 
pointers.

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


Re: meaning of: line, =

2015-02-05 Thread Rustom Mody
On Thursday, February 5, 2015 at 9:39:27 PM UTC+5:30, Ian wrote:
> On Thu, Feb 5, 2015 at 2:40 AM, Steven D'Aprano wrote:
> > Devin Jeanpierre wrote:
> >
> >> On Wed, Feb 4, 2015 at 1:18 PM, Chris Angelico wrote:
> >>> On Thu, Feb 5, 2015 at 4:36 AM, Peter Otten  wrote:
>  Another alternative is to put a list literal on the lefthand side:
> 
> >>> def f(): yield 42
> 
>  ...
> >>> [result] = f()
> >>> result
>  42
> >>>
> >>> Huh, was not aware of that alternate syntax.
> >>
> >> Nor are most people. Nor is Python, in some places -- it seems like
> >> people forgot about it when writing some bits of the grammar.
> >
> > Got an example where you can use a,b but not [a,b] or (a,b)?
> 
> >>> def f(a, (b, c)):
> ... print a, b, c

What the hell is that?!
First I am hearing/seeing it.
Whats it called?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: meaning of: line, =

2015-02-05 Thread Skip Montanaro
Tuple packing. No longer supported in Python 3, but in available in Python <= 2.

Skip


On Thu, Feb 5, 2015 at 10:45 AM, Rustom Mody  wrote:
> On Thursday, February 5, 2015 at 9:39:27 PM UTC+5:30, Ian wrote:
>> On Thu, Feb 5, 2015 at 2:40 AM, Steven D'Aprano wrote:
>> > Devin Jeanpierre wrote:
>> >
>> >> On Wed, Feb 4, 2015 at 1:18 PM, Chris Angelico wrote:
>> >>> On Thu, Feb 5, 2015 at 4:36 AM, Peter Otten  wrote:
>>  Another alternative is to put a list literal on the lefthand side:
>> 
>> >>> def f(): yield 42
>> 
>>  ...
>> >>> [result] = f()
>> >>> result
>>  42
>> >>>
>> >>> Huh, was not aware of that alternate syntax.
>> >>
>> >> Nor are most people. Nor is Python, in some places -- it seems like
>> >> people forgot about it when writing some bits of the grammar.
>> >
>> > Got an example where you can use a,b but not [a,b] or (a,b)?
>>
>> >>> def f(a, (b, c)):
>> ... print a, b, c
>
> What the hell is that?!
> First I am hearing/seeing it.
> Whats it called?
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: meaning of: line, =

2015-02-05 Thread Tim Chase
On 2015-02-05 08:45, Rustom Mody wrote:
> > >>> def f(a, (b, c)):
> > ... print a, b, c
> 
> What the hell is that?!
> First I am hearing/seeing it.
> Whats it called?

"tuple parameter unpacking", removed in Py3

https://www.python.org/dev/peps/pep-3113/

-tkc



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


Re: Monte Carlo probability calculation in Python

2015-02-05 Thread Rob Gaddi
On Thu, 05 Feb 2015 08:20:41 -0800, Paul  Moore wrote:

> I'm interested in prototyping a Monte Carlo type simulation algorithm in
> Python. The background is that a friend has written a similar program in
> C++, and I'm interested in seeing if I can achieve something comparable
> in a much better language :-)
> 
> The basic job of the program will be to simulate games of chance - so
> we'll have random inputs (die rolls, card draws, etc) and repeatedly
> simulate calculating a "result". Based on the results of the simulation,
> the idea is to estimate the probability of a given result.
> 
> So, to give a very specific example:
> 
> import random
> 
> def die(n, sides=6):
> total = sum(random.randint(1, sides) for i in range(n))
> return total
> 
> def simulate(n, test):
> "Run the simulation N times, returning the probability that TEST is
> true"
> successes = 0 for i in range(n):
> if test():
> successes = successes + 1
> return successes/n
> 
> def check_3d6_gt_15():
> return die(3) > 15
> 
> if __name__ == '__main__':
> print(simulate(10, check_3d6_gt_15))
> 
> Obviously, this is going to run ridiculously slowly as the number of
> simulations or the complexity of the calculation increases, but this
> gives the idea.
> 
> My immediate instinct is that somewhere in the scipy stack, there will
> be a module that does this sort of thing efficiently, but I don't really
> know where to look - my understanding of the maths involved is very much
> at the naive level above, so I'm not sure what terms I should be
> searching for, or how to frame a query.
> 
> Can anyone give me some pointers as to where I should go to find out
> more about this sort of task? Either more general theory (that would
> help me ask the right questions!) or specific packages or techniques I
> should be using in Python/numpy would be fantastic.
> 
> Any help would be gratefully accepted - surely nobody wants to see
> Python beaten by a C++ program??? :-)
> 
> Thanks,
> Paul

You don't need the whole scipy stack, numpy will let you do everything 
you want.  The trick to working in numpy is to parallelize your problem; 
you don't do a thing a thousand times; you do it on a thousand-length 
array.  For example:

def dice(throws, per, sides=6):
"""Return an array throws long of rolls of (per)d(sides)."""
all_dice = np.random.randint(1, sides+1, size=(throws, per))
return all_dice.sum(axis=1)

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: meaning of: line, =

2015-02-05 Thread Rustom Mody
On Thursday, February 5, 2015 at 10:15:29 PM UTC+5:30, Rustom Mody wrote:
> On Thursday, February 5, 2015 at 9:39:27 PM UTC+5:30, Ian wrote:
> > On Thu, Feb 5, 2015 at 2:40 AM, Steven D'Aprano wrote:
> > > Devin Jeanpierre wrote:
> > >
> > >> On Wed, Feb 4, 2015 at 1:18 PM, Chris Angelico wrote:
> > >>> On Thu, Feb 5, 2015 at 4:36 AM, Peter Otten  wrote:
> >  Another alternative is to put a list literal on the lefthand side:
> > 
> > >>> def f(): yield 42
> > 
> >  ...
> > >>> [result] = f()
> > >>> result
> >  42
> > >>>
> > >>> Huh, was not aware of that alternate syntax.
> > >>
> > >> Nor are most people. Nor is Python, in some places -- it seems like
> > >> people forgot about it when writing some bits of the grammar.
> > >
> > > Got an example where you can use a,b but not [a,b] or (a,b)?
> > 
> > >>> def f(a, (b, c)):
> > ... print a, b, c
> 
> What the hell is that?!
> First I am hearing/seeing it.
> Whats it called?

The reason I ask: I sorely miss haskell's pattern matching in python.

It goes some way:

>>> ((x,y),z) = ((1,2),3)
>>> x,y,z
(1, 2, 3)

But not as far as I would like:

>>> ((x,y),3) = ((1,2),3)
  File "", line 1
SyntaxError: can't assign to literal
>>> 

[Haskell]

Prelude> let (x, (y, (42, z, "Hello"))) = (1, (2, (42, 3, "Hello")))
Prelude> (x,y,z)
(1,2,3)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Monte Carlo probability calculation in Python

2015-02-05 Thread Paul Moore
On Thursday, 5 February 2015 16:57:07 UTC, Rob Gaddi  wrote:
> You don't need the whole scipy stack, numpy will let you do everything 
> you want.  The trick to working in numpy is to parallelize your problem; 
> you don't do a thing a thousand times; you do it on a thousand-length 
> array.  For example:
> 
> def dice(throws, per, sides=6):
> """Return an array throws long of rolls of (per)d(sides)."""
> all_dice = np.random.randint(1, sides+1, size=(throws, per))
> return all_dice.sum(axis=1)

Thanks, that's a help. I see the principle, but a couple of questions. With 
bigger problems (deal 52 cards into bridge hands a million times, for example) 
would memory become an issue? Also, how do you handle things that don't fit 
into the built-in numpy operations? (For example, Monopoly - roll 2 dice and 
take the sum, unless you roll a double, in which case reroll, but if you roll 3 
doubles you fail - return NaN in that case).

As examples of a few more problems I'd use this for:

1. Roll 4 dice, and sum the largest 3.
2. Roll 9 dice, count how many different numbers you get.
3. Deal 4 hands of 13 cards from a full deck, determine the length of the 
longest suit anyone has.
4. Monopoly rolls (see above, 2 dice but reroll doubles up to 3 times)

All of these are reasonably easy to write as Python functions, but it becomes 
progressively harder (for a non-numpy expert) to know how to convert them into 
parallelizable numpy primitives.

I'll have a play with the approach you suggest though, and see how it handles 
some of the more complex problems my friend was showing off with :-) (his worst 
example was a horrendous expression to score Cribbage hands, that if I read his 
note correctly took about a minute to simulate 10,000,000 deals)

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


Re: meaning of: line, =

2015-02-05 Thread Tim Chase
On 2015-02-05 09:08, Ian Kelly wrote:
> > Got an example where you can use a,b but not [a,b] or (a,b)?  
> 
> >>> def f(a, (b, c)):  
> ... print a, b, c
> ...

Interesting.  I knew that at one point you could do this with lambdas
but never thought to do it with regular functions.  There are times
this would have been useful, but since it appears to have gone away
in Py3, I guess I won't adopt it.

-tkc


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


multiprocessing.Queue() and missing sem_open

2015-02-05 Thread Оlе Ѕtrеісhеr
Hi,

I am just trying to prepare a package (astropy) for (Debian) Hurd. This
os lacks a sem_open() implementation. When I now try:

import multiprocessing
q = multiprocessing.Queue()

I get an ImportError with Python 2.7, but an AttributeError with Python
3.4. In the documentation of multiprocessing.Queue() I couldn't find any
hint that it would throw this exception.

I am now curious, that

1. this behaviour is not documented
2. it changed at some point, without documentation.

Why does it not return a NotImplementedError (this is what I would
expect if a function is not implemented by the OS)?

Can I be sure that the following works also in future?

try
q = multiprocessing.Queue()
except (ImportError, AttributeError)
# handle the case of missing sem_open

Or what is the correct way to catch a not working Queue caused by a
missing sem_open() implementation?

Best regards

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


Re: pymongo and attribute dictionaries

2015-02-05 Thread Anssi Saari
Steven D'Aprano  writes:

> Vito De Tullio wrote:
>
>> Steven D'Aprano wrote:
>> 
 This just does not roll of the fingers well. Too many “reach for
 modifier keys” in a row.
>>> 
>>> *One* modifier key in a row is too many?
>>> 
>>> s o m e SHIFT D o c [ ' SHIFT _ i d ' ]
>> 
>> I'm not OP, but as side note... not everyone has "[" as a direct character
>> on the keyboard. I need to press "AltGr" + "è" (and "AltGr" + "+" to get
>> "]"), so I can feel the OP lamenting :)
>
> Point taken. Thank you.

What I find surprising is that so many people cling so hard to their
localized keyboard layouts. I think none of those were created by
engineers and should be avoided by technical people. Or, in fact,
everyone. Even Microsoft seems to understand this and so Windows
installs the US English layout by default as an alternative.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Monte Carlo probability calculation in Python

2015-02-05 Thread Rob Gaddi
On Thu, 05 Feb 2015 11:25:42 -0800, Paul  Moore wrote:

> On Thursday, 5 February 2015 16:57:07 UTC, Rob Gaddi  wrote:
>> You don't need the whole scipy stack, numpy will let you do everything
>> you want.  The trick to working in numpy is to parallelize your
>> problem;
>> you don't do a thing a thousand times; you do it on a thousand-length
>> array.  For example:
>> 
>> def dice(throws, per, sides=6):
>> """Return an array throws long of rolls of (per)d(sides)."""
>> all_dice = np.random.randint(1, sides+1, size=(throws, per))
>> return all_dice.sum(axis=1)
> 
> Thanks, that's a help. I see the principle, but a couple of questions.
> With bigger problems (deal 52 cards into bridge hands a million times,
> for example) would memory become an issue? Also, how do you handle
> things that don't fit into the built-in numpy operations? (For example,
> Monopoly - roll 2 dice and take the sum, unless you roll a double, in
> which case reroll, but if you roll 3 doubles you fail - return NaN in
> that case).
> 
> As examples of a few more problems I'd use this for:
> 
> 1. Roll 4 dice, and sum the largest 3.
> 2. Roll 9 dice, count how many different numbers you get.
> 3. Deal 4 hands of 13 cards from a full deck, determine the length of
> the longest suit anyone has.
> 4. Monopoly rolls (see above, 2 dice but reroll doubles up to 3 times)
> 
> All of these are reasonably easy to write as Python functions, but it
> becomes progressively harder (for a non-numpy expert) to know how to
> convert them into parallelizable numpy primitives.
> 
> I'll have a play with the approach you suggest though, and see how it
> handles some of the more complex problems my friend was showing off with
> :-) (his worst example was a horrendous expression to score Cribbage
> hands, that if I read his note correctly took about a minute to simulate
> 10,000,000 deals)
> 
> Paul

A lot of your examples can be dealt by the numpy fancy indexing tricks, 
which is really the heart of numpy.  A comparison on an array of numbers 
gives an array of bools, which can then be used to index the original 
array.  The Monopoly example, for instance.

  all_dice = np.random.randint(1, 7, size=(throws, 2))
  doubles = all_dice[all_dice[:,0] == all_dice[:,1]]

doubles is now a writeable view into the original all_dice array, so you 
could reroll them by saying something like.

  doubles[:,:] = np.random.randint(1, 7, size=doubles.shape)

Memory will eventually become a concern, but in that case you could 
always run it in parts and aggregate the parts.  I wouldn't sweat it 
until you get into 100s of millions of tries.  Even then, you could make 
some improvements by forcing the dtypes to be uint8, though there may be 
a performance penalty.

Numpy is fantastically powerful once you can wrap your head around it; I 
use it for a ton of things I used to use Matlab for.  The tutorial at  
http://wiki.scipy.org/Tentative_NumPy_Tutorial will go into lots of depth 
for you.


-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Monte Carlo probability calculation in Python

2015-02-05 Thread Ian Kelly
On Thu, Feb 5, 2015 at 12:25 PM, Paul  Moore  wrote:
> On Thursday, 5 February 2015 16:57:07 UTC, Rob Gaddi  wrote:
>> You don't need the whole scipy stack, numpy will let you do everything
>> you want.  The trick to working in numpy is to parallelize your problem;
>> you don't do a thing a thousand times; you do it on a thousand-length
>> array.  For example:
>>
>> def dice(throws, per, sides=6):
>> """Return an array throws long of rolls of (per)d(sides)."""
>> all_dice = np.random.randint(1, sides+1, size=(throws, per))
>> return all_dice.sum(axis=1)
>
> Thanks, that's a help. I see the principle, but a couple of questions. With 
> bigger problems (deal 52 cards into bridge hands a million times, for 
> example) would memory become an issue?

At the point memory becomes an issue you can partially roll it back
into a loop. For example, deal the bridge hands 1 times in a loop
of 100.

> Also, how do you handle things that don't fit into the built-in numpy 
> operations? (For example, Monopoly - roll 2 dice and take the sum, unless you 
> roll a double, in which case reroll, but if you roll 3 doubles you fail - 
> return NaN in that case).

Building on Rob's example:

def monopoly(throws, per=2, rerolls=3, sides=6):
all_dice = np.random.randint(1, sides+1, size=(throws, rerolls, per))
doubles = all_dice[...,0] == all_dice[...,1]
three_doubles = doubles[:,0] & doubles[:,1] & doubles[:,2]
return all_dice.sum(axis=2), doubles, three_doubles

This returns a (throws x rerolls) array of the sum of each roll, a
(throws x rerolls) array of booleans indicating whether the roll was a
double or not, and a throws-long array of booleans indicating whether
three doubles were rolled.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: multiprocessing.Queue() and missing sem_open

2015-02-05 Thread Chris Angelico
On Fri, Feb 6, 2015 at 7:22 AM, Оlе Ѕtrеісhеr  wrote:
> I am just trying to prepare a package (astropy) for (Debian) Hurd. This
> os lacks a sem_open() implementation. When I now try:
>
> import multiprocessing
> q = multiprocessing.Queue()
>
> I get an ImportError with Python 2.7, but an AttributeError with Python
> 3.4. In the documentation of multiprocessing.Queue() I couldn't find any
> hint that it would throw this exception.

Neither of those errors is being consciously thrown by the Queue
class; the latter means that multiprocessing exists but it has no
Queue in it, and the former means that the entire multiprocessing
module is absent.

I'm guessing you built Python from source? If so, you should have had
a report at the bottom of the build output stating which of the
optional packages weren't built, which on 2.7 will have included
multiprocessing. You might be able to install some dependency and get
that to build, though I don't know what it would be, given that the
3.4 build managed to find it.

But this is the exact way that Python will normally signal that
something isn't available. If your platform doesn't have, say,
os.O_BINARY, because that flag has no meaning for you, then you don't
get NotImplementedError - you simply get AttributeError.

> Can I be sure that the following works also in future?
>
> try
> q = multiprocessing.Queue()
> except (ImportError, AttributeError)
> # handle the case of missing sem_open
>
> Or what is the correct way to catch a not working Queue caused by a
> missing sem_open() implementation?

The ImportError will come from the import statement, the
AttributeError will come from the attribute lookup - the above code
can't[1] bomb out with ImportError. So a more correct way would be
something like:

try:
import multiprocessing
multiprocessing.Queue
except (ImportError, AttributeError):
# handle the absence

Or alternatively, don't even bother to try/except the import. If your
code requires multiprocessing.Queue (as opposed to just queue.Queue),
chances are you can't cope with the absence of the module.

ChrisA

[1] Yeah yeah, anything can do anything. You know what I mean.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Monte Carlo probability calculation in Python

2015-02-05 Thread Paul Moore
On Thursday, 5 February 2015 21:01:21 UTC, Ian  wrote:
> Building on Rob's example:
> 
> def monopoly(throws, per=2, rerolls=3, sides=6):
> all_dice = np.random.randint(1, sides+1, size=(throws, rerolls, per))
> doubles = all_dice[...,0] == all_dice[...,1]
> three_doubles = doubles[:,0] & doubles[:,1] & doubles[:,2]
> return all_dice.sum(axis=2), doubles, three_doubles
> 
> This returns a (throws x rerolls) array of the sum of each roll, a
> (throws x rerolls) array of booleans indicating whether the roll was a
> double or not, and a throws-long array of booleans indicating whether
> three doubles were rolled.

Nice! Thanks both of you. I start to see how to think about these things now. 
I'll play around with some of the other examples I've got, and see how far I 
get.

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


Re: meaning of: line, =

2015-02-05 Thread Gregory Ewing

Devin Jeanpierre wrote:

On Wed, Feb 4, 2015 at 1:18 PM, Chris Angelico  wrote:


On Thu, Feb 5, 2015 at 4:36 AM, Peter Otten <__pete...@web.de> wrote:


[result] = f()

result


Huh, was not aware of that alternate syntax.


Nor are most people. Nor is Python, in some places -- it seems like
people forgot about it when writing some bits of the grammar.


If I remember correctly, it's left over from long ago
when you had to use tuple syntax to unpack tuples and
list syntax to unpack lists (and you couldn't unpack
anything else).

When the iterator protocol was introduced, the two
became equivalent.

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


Re: meaning of: line, =

2015-02-05 Thread Devin Jeanpierre
On Thu, Feb 5, 2015 at 8:08 AM, Ian Kelly  wrote:
> On Thu, Feb 5, 2015 at 2:40 AM, Steven D'Aprano
>  wrote:
>> Devin Jeanpierre wrote:
>>> On Wed, Feb 4, 2015 at 1:18 PM, Chris Angelico  wrote:
 [result] = f()
 result
> 42

 Huh, was not aware of that alternate syntax.
>>>
>>> Nor are most people. Nor is Python, in some places -- it seems like
>>> people forgot about it when writing some bits of the grammar.
>>
>> Got an example where you can use a,b but not [a,b] or (a,b)?
>
 def f(a, (b, c)):
> ... print a, b, c
> ...
 f(3, [4, 5])
> 3 4 5
 def g(a, [b, c]):
>   File "", line 1
> def g(a, [b, c]):
>  ^
> SyntaxError: invalid syntax
>
> Although to be fair, the first syntax there is no longer valid either
> in Python 3.

As Ian rightly understood, I was referring to differences between "[a,
b, ...]" and "(a, b, ...)".

Here's another example, one that still exists in Python 3:

>>> [] = ''
>>> () = ''
  File "", line 1
SyntaxError: can't assign to ()

The syntax explicitly blacklists (), but forgets to blacklist [].

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


Re: meaning of: line, =

2015-02-05 Thread Chris Angelico
On Fri, Feb 6, 2015 at 12:12 PM, Devin Jeanpierre
 wrote:
> Here's another example, one that still exists in Python 3:
>
 [] = ''
 () = ''
>   File "", line 1
> SyntaxError: can't assign to ()
>
> The syntax explicitly blacklists (), but forgets to blacklist [].

So... this is actually a really really obscure little feature.

[] = x
# is equivalent to
try: next(iter(x))
except StopIteration: pass
else: raise ValueError("too many values to unpack (expected 0)")

It's a way of asserting that an iterator is exhausted! Perfect code
snippet for your next International Obfuscated Python Code Contest
entry.

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


Re: meaning of: line, =

2015-02-05 Thread Gregory Ewing

Chris Angelico wrote:

[] = x
# is equivalent to
try: next(iter(x))
except StopIteration: pass
else: raise ValueError("too many values to unpack (expected 0)")

It's a way of asserting that an iterator is exhausted!


But why disallow using () for the same thing? This
is a blatant case of outright list-ism! Tuples are
being unfairly discriminated against!

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


Azure event hub network access

2015-02-05 Thread syed khalid
I am getting http error 404. I am able to access the site via telnet which
eliminates network issues. Here is the code and subsequent errors



user/bin/python
import sys
import azure
import socket

from azure.servicebus import (
  _service_bus_error_handler
  )

from azure.servicebus.servicebusservice import (
  ServiceBusService,
  ServiceBusSASAuthentication
  )

from azure.http import (
  HTTPRequest,
  HTTPError
  )

from azure.http.httpclient import _HTTPClient

class EventHubClient(object):

def sendMessage(self,body,partition):
eventHubHost = "pac-ns.servicebus.windows.net"

httpclient = _HTTPClient(service_instance=self)

sasKeyName = "pac-pl"
sasKeyValue = "IhkEepQPLfSy9jo6H2Y="

authentication = ServiceBusSASAuthentication(sasKeyName,sasKeyValue)

request = HTTPRequest()
request.method = "POST"
request.host = eventHubHost
request.protocol_override = "https"
#request.path = "/myhub/publishers/" + partition +
"/messages?api-version=20
14-05"
request.body = body
request.headers.append(('Content-Type',
'application/atom+xml;type=entry;cha
rset=utf-8'))

authentication.sign_request(request, httpclient)

request.headers.append(('Content-Length', str(len(request.body
status = 0

try:
resp = httpclient.perform_request(request)
status = resp.status
except HTTPError as ex:
status = ex.status

return status

class EventDataParser(object):

  def getMessage(self,payload,sensorId):
host = socket.gethostname()
body = "{ \"DeviceId\" : \"" + host + "\",\"SensorData\": [ "

msgs = payload.split(",")
first = True

for msg in msgs:
# print msg
  sensorType = msg.split(":")[0]
sensorValue = msg.split(":")[1]
  if first == True:
first = False
  else:
body += ","

  body += "{ \"SensorId\" : \"" + sensorId + "\", \"SensorType\" : \""
+ sen
sorType + "\", \"SensorValue\" : " + sensorValue + " }"
body += "]}"

return body

hubClient = EventHubClient()
parser = EventDataParser()
hostname = socket.gethostname()
sensor = sys.argv[2]

body = parser.getMessage(sys.argv[1],sensor)
hubStatus = hubClient.sendMessage(body,hostname)
# return the HTTP status to the caller
print hubStatus
print hostname
print sensor




~/IOT/AZURE$ python send.py temperature:22,humidity:20 deviceid

404
ubuntu
deviceid
{ "DeviceId" : "ubuntu","SensorData": [ { "SensorId" : "deviceid",
"SensorType" : "temperature", "SensorValue" : 22 },{ "SensorId" :
"deviceid", "SensorType" : "humidity", "SensorValue" : 20 }]}




-- 
*Syed Khalid*
-- 
https://mail.python.org/mailman/listinfo/python-list


RE: [Python-Dev] Azure event hub network access

2015-02-05 Thread Steve Dower
This would be much better posted on the github page for the project. I don't 
have the URL handy, but if you search github for "Python Azure SDK" you'll find 
it.

Cheers,
Steve

Sent from my Windows Phone

From: syed khalid
Sent: ‎2/‎5/‎2015 21:27
To: python-...@python.org
Cc: python-list@python.org
Subject: [Python-Dev] Azure event hub network access

I am getting http error 404. I am able to access the site via telnet which 
eliminates network issues. Here is the code and subsequent errors



user/bin/python
import sys
import azure
import socket

from azure.servicebus import (
  _service_bus_error_handler
  )

from azure.servicebus.servicebusservice import (
  ServiceBusService,
  ServiceBusSASAuthentication
  )

from azure.http import (
  HTTPRequest,
  HTTPError
  )

from azure.http.httpclient import _HTTPClient

class EventHubClient(object):

def sendMessage(self,body,partition):
eventHubHost = 
"pac-ns.servicebus.windows.net"

httpclient = _HTTPClient(service_instance=self)

sasKeyName = "pac-pl"
sasKeyValue = "IhkEepQPLfSy9jo6H2Y="

authentication = ServiceBusSASAuthentication(sasKeyName,sasKeyValue)

request = HTTPRequest()
request.method = "POST"
request.host = eventHubHost
request.protocol_override = "https"
#request.path = "/myhub/publishers/" + partition + "/messages?api-version=20
14-05"
request.body = body
request.headers.append(('Content-Type', 'application/atom+xml;type=entry;cha
rset=utf-8'))

authentication.sign_request(request, httpclient)

request.headers.append(('Content-Length', str(len(request.body
status = 0

try:
resp = httpclient.perform_request(request)
status = resp.status
except HTTPError as ex:
status = ex.status

return status

class EventDataParser(object):

  def getMessage(self,payload,sensorId):
host = socket.gethostname()
body = "{ \"DeviceId\" : \"" + host + "\",\"SensorData\": [ "

msgs = payload.split(",")
first = True

for msg in msgs:
# print msg
  sensorType = msg.split(":")[0]
sensorValue = msg.split(":")[1]
  if first == True:
first = False
  else:
body += ","

  body += "{ \"SensorId\" : \"" + sensorId + "\", \"SensorType\" : \"" + sen
sorType + "\", \"SensorValue\" : " + sensorValue + " }"
body += "]}"

return body

hubClient = EventHubClient()
parser = EventDataParser()
hostname = socket.gethostname()
sensor = sys.argv[2]

body = parser.getMessage(sys.argv[1],sensor)
hubStatus = hubClient.sendMessage(body,hostname)
# return the HTTP status to the caller
print hubStatus
print hostname
print sensor




~/IOT/AZURE$ python send.py temperature:22,humidity:20 deviceid

404
ubuntu
deviceid
{ "DeviceId" : "ubuntu","SensorData": [ { "SensorId" : "deviceid", "SensorType" 
: "temperature", "SensorValue" : 22 },{ "SensorId" : "deviceid", "SensorType" : 
"humidity", "SensorValue" : 20 }]}




--
Syed Khalid

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