Re: Understanding Python Code

2014-06-19 Thread Ian Kelly
On Wed, Jun 18, 2014 at 11:50 PM,   wrote:
> Thank you for the reply. But as I checked it again I found,
> f_prev[k] is giving values of f_curr[st] = e[st][x_i] * prev_f_sum
> which is calculated later and again uses prev_f_sum.

f_prev is the f_curr that was calculated on the previous iteration of
the loop.  At each iteration after the first, the script calculates
f_curr based on the value of f_prev, that is, the old value of f_curr.
Then it reassigns the newly computed f_curr to f_prev, making it now
the previous, and on the next iteration it creates a new dict to store
the next f_curr.  Does that make sense?
-- 
https://mail.python.org/mailman/listinfo/python-list


Python 3 on Mac OS X 10.8.4

2014-06-19 Thread Une Bévue

On my mac i do have :
$ python --version
Python 2.7.2

I want to install Python 3 such as python-3.4.0-macosx10.6.dmg avoiding 
disturbing the "built-in" version.


Is that possible ?
--
https://mail.python.org/mailman/listinfo/python-list


Re: Under what kind of situation, time.sleep(n) would sleep much longer than n seconds?

2014-06-19 Thread Christian Gollwitzer

Am 19.06.14 01:38, schrieb Chris Angelico:

a good console UI just requires this:

something = raw_input("Enter something: ")
print("Result: "+result)


That is actually one of the worst console UIs possible. Almost all 
beginner's courses start with programs like that, requiring the user to 
key something in in the predefined order of the program. I've never seen 
a useful mature program working like that, only courseware and maybe 
crufty FORTRAN stuff from the past.


Unless there is good reason, make your program read the data from the 
command line args and from files given on the command line. This solves 
a lot of problems with user interaction, e.g. repeating and correcting 
commands. Programs written in the input() style are very annoying when 
you made a mistake in the 21st parameter of 30. Good interactive command 
line tools (e.g. gnuplot, Matlab, IPython, ...) exist, but they are 
complex; they bind to a readline library and implement a complex command 
language.


My advice:

1) First try parsing the command line. (Example: All Unix tools)

2) If you require more interaction and maybe state preservation, just 
write a couple of functions and run it in IPython (Example: SciPy)


3) Use a real GUI framework

It turns out, that 3) is actually not only easier to use, but often 
easier to write than 1)


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


Re: how to check if a value is a floating point or not

2014-06-19 Thread Ben Finney
Nicholas Cannon  writes:

> #checks if the user input is an integer value
> def checkint(a):
>   if a.isnumeric():
>   return True
>   else:
>   if a.isalpha():
>   return False
>   else:
>   return True

What code will be using this function? Why would that not be better
replaced with a ‘try … except’ construction?

That is, don't do this (Look Before You Leap)::

foo = get_a_string()
if checkint(foo):
bar = int(foo)
else:
bar = None

Instead, do this (Easier to Ask Forgiveness than Permission)::

foo = get_a_string()
try:
bar = int(foo)
except ValueError:
bar = None

If you need to create an integer based on a string, just do it, and
handle the exception (if any) at an appropriate level.

> There is one annoying error doing it this way and that is if you enter
> 12.ab or ab.12 it will say that it is okay. Still working on this so
> this should get sorted out soon.

You are re-inventing a wheel (the ‘int’ callable) which already does all
of that properly. Make use of it, and your frustration will be reduced.

-- 
 \ “It is far better to grasp the universe as it really is than to |
  `\persist in delusion, however satisfying and reassuring.” —Carl |
_o__)Sagan |
Ben Finney

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


Re: how to check if a value is a floating point or not

2014-06-19 Thread Ian Kelly
On Thu, Jun 19, 2014 at 12:48 AM, Nicholas Cannon
 wrote:
> On Thursday, June 19, 2014 1:53:31 PM UTC+8, Nicholas Cannon wrote:
>> I am making a calculator and i need it to support floating point values but 
>> i am using the function isnumeric to check if the user has entered an int 
>> value. I need the same for floating point types so i could implement an or 
>> in the if statement that checks the values the user has entered and allow it 
>> to check and use floating points. If you need the source code i am happy to 
>> give it to you. Thank you for your help
>
> I am using python 2.7.7 and i have come up with away but there is still 
> possible errors for this. What i did was i this
>
> #checks if the user input is an integer value
> def checkint(a):
> if a.isnumeric():
> return True
> else:
> if a.isalpha():
> return False
> else:
> return True
>
> The parameter a is the users input by the raw_input function. I first test if 
> it is normal int with the isnumeric function. Unfortunately this function 
> picks up the decimal as false. This means if the user inputs a float it has 
> to be false. I then test if this input has any alphabetical characters if it 
> does not the user could have only entered  something like 12.5 oppose to 
> abc.d.

unicode.isalpha does not test if the input has *any* alphabetic
characters.  It tests if the input is *only* alphabetic characters.
u'12.5'.isalpha() does return False.  u'abc.d'.isalpha() *also*
returns False, because the decimal point is not alphabetic.

I second Gary Herron's suggestion to just try converting the value and
catch the exception if it fails.  Python already knows how to do this
for you; there's no need to reinvent the wheel.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to check if a value is a floating point or not

2014-06-19 Thread Ian Kelly
On Thu, Jun 19, 2014 at 1:23 AM, Ian Kelly  wrote:
> On Thu, Jun 19, 2014 at 12:48 AM, Nicholas Cannon
>  wrote:
>> On Thursday, June 19, 2014 1:53:31 PM UTC+8, Nicholas Cannon wrote:
>>> I am making a calculator and i need it to support floating point values but 
>>> i am using the function isnumeric to check if the user has entered an int 
>>> value. I need the same for floating point types so i could implement an or 
>>> in the if statement that checks the values the user has entered and allow 
>>> it to check and use floating points. If you need the source code i am happy 
>>> to give it to you. Thank you for your help
>>
>> I am using python 2.7.7 and i have come up with away but there is still 
>> possible errors for this. What i did was i this
>>
>> #checks if the user input is an integer value
>> def checkint(a):
>> if a.isnumeric():
>> return True
>> else:
>> if a.isalpha():
>> return False
>> else:
>> return True
>>
>> The parameter a is the users input by the raw_input function. I first test 
>> if it is normal int with the isnumeric function. Unfortunately this function 
>> picks up the decimal as false. This means if the user inputs a float it has 
>> to be false. I then test if this input has any alphabetical characters if it 
>> does not the user could have only entered  something like 12.5 oppose to 
>> abc.d.
>
> unicode.isalpha does not test if the input has *any* alphabetic
> characters.  It tests if the input is *only* alphabetic characters.
> u'12.5'.isalpha() does return False.  u'abc.d'.isalpha() *also*
> returns False, because the decimal point is not alphabetic.

Incidentally, unicode.isnumeric is probably not what you want either.
According to the docs, it returns "True if there are only numeric
characters in S, False otherwise. Numeric characters include digit
characters, and all characters that have the Unicode numeric value
property, e.g. U+2155, VULGAR FRACTION ONE FIFTH."  So that includes
strings like u'123⅕⅓Ⅷ٤', which is clearly not an integer.  You'd
likely do better with unicode.isdigit, and even then you'd be allowing
for mixed scripts.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Under what kind of situation, time.sleep(n) would sleep much longer than n seconds?

2014-06-19 Thread Chris Angelico
On Thu, Jun 19, 2014 at 5:18 PM, Christian Gollwitzer  wrote:
> Am 19.06.14 01:38, schrieb Chris Angelico:
>
>> a good console UI just requires this:
>>
>> something = raw_input("Enter something: ")
>> print("Result: "+result)
>
>
> That is actually one of the worst console UIs possible
>
> My advice:
>
> 1) First try parsing the command line. (Example: All Unix tools)
>
> 2) If you require more interaction and maybe state preservation, just write
> a couple of functions and run it in IPython (Example: SciPy)
>
> 3) Use a real GUI framework
>
> It turns out, that 3) is actually not only easier to use, but often easier
> to write than 1)

I disagree. It may not be the *best* console UI, but it's not as bad
as you think. Yes, what I wrote was a massive oversimplification, but
compare this:

https://github.com/Rosuav/runningtime/blob/master/runningtime.py#L44

That's a simple, straight-forward UI. If you put the .py file onto
your desktop and double-click it, you'll see a series of prompts, and
this works on Windows, OS/2, probably Mac OS, and quite a few Linux
desktops. (Although I didn't put a shebang on that file, so it might
not work on your typical Linux.) How do you make something that
provides command line arguments to a double-clicked-on icon? Different
for every platform. (And seldom as easy as it is on OS/2.) If you run
that in a terminal, you'll see a series of prompts, and it works on
probably every Python implementation EVER. If you pull it up in IDLE,
it'll probably work there too, although I haven't tried it.

You're quite right that parsing the command line is often better for
long-term usability. But you try explaining to someone how to provide
args to a script. In fact, let's go a bit further: You can't assume
that Python was installed in any particular way, you've been told that
the OS is some version of Windows you're not familiar with (if you're
a Windows expert, then suppose this is some version of Mac OS that
you've never touched), and you're talking to the person over the
phone. This is, in fact, very similar to the situation I was in last
night, except that I wasn't even the person on the phone - my sister
was, and I was in the same room as she was. Now, you have no idea
whether typing "foo.py" will run it in Python, and if it does, in what
version; you have no idea whether "python.exe" is in PATH; and you
possibly can't even figure out how to open up a command prompt on that
system.

Yeah, I think [raw_]input() isn't so bad after all.

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


Re: Python 3 on Mac OS X 10.8.4

2014-06-19 Thread Andrea D'Amore

On 2014-06-19 07:02:21 +, Une Bévue said:

I want to install Python 3 such as python-3.4.0-macosx10.6.dmg avoiding 
disturbing the "built-in" version.

Is that possible ?


The Installer app won't let you see the target path of each package in 
the metapackage so you'll have to open each of the them (we're talking 
official binaries since you explicitly named that particular DMG file) 
and check where they are going to install their content.
Most likely they'll go in /usr/local so you won't have clashes with 
system's python.


An alternative is to install and learn to use a package manager, I use 
MacPorts that requires full Xcode. Brew should require the smaller 
command line package. Fink should require no additional packages since 
it's basically APT. There are other managers as well, these are the 
most common on OS X.


--
Andrea

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


Re: Python Fails to Write to File

2014-06-19 Thread cutey Love
Thank you very much, that fixed it.

On Thursday, June 19, 2014 12:03:43 AM UTC+1, cutey Love wrote:
> I'm trying to write data to a text file
> 
> 
> 
> But I'm getting the error:
> 
> 
> 
> TypeError: invalid file: <_io.TextIOWrapper 
> 
> 
> 
> Code is 
> 
> 
> 
> def saveFile():
> 
> file_path = filedialog.asksaveasfile(mode='w', filetypes=[('text files', 
> '.txt')], defaultextension=".txt")
> 
> fo = open(file_path, 'w')
> 
> 
> 
> for e in myList:
> 
> fo.write(e)
> 
> 
> 
> 
> 
> fo.close()
> 
> 
> 
> The file is being created if not already present but no data is written

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


Re: Not Responding When Dealing with Large Data

2014-06-19 Thread cutey Love
update_idletasks didn't work.

The code is this

file_path = filedialog.askopenfilename(filetypes=[('text files', '.txt')], 
multiple=True, defaultextension=".txt")

for path in file_path:

fo = open(path, "r")

for line in fo:
if myCase(line.lower()):
myList.append(line.lower())
fo.close()


def myCase(c):

if c in myList:
return False

if len(c) < 8 or len(c) > 80:
return False

return True



This processes a fair bit of data





On Thursday, June 19, 2014 12:06:26 AM UTC+1, Ian wrote:
> On Wed, Jun 18, 2014 at 4:32 PM, cutey Love  wrote:
> 
> > Hi, thanks for the replies,
> 
> >
> 
> > I mean windows displays "Not responding close the program now"
> 
> >
> 
> > How can I do it asynconistrically?
> 
> >
> 
> > It's simple code just open file, loop through line by line and do some 
> > comparons with the string.
> 
> 
> 
> If all you want is to prevent Windows from displaying that message
> 
> then I believe all you need to do is periodically call
> 
> frame.update_idletasks() (or the equivalent if you're using some
> 
> framework other than tkinter) so that the basic window events will get
> 
> processed.

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


Re: Python Fails to Write to File

2014-06-19 Thread Mark Lawrence

On 19/06/2014 08:54, cutey Love wrote:

Thank you very much, that fixed it.



What do you not understand about top posting and using google groups?

--
My fellow Pythonistas, ask not what our language can do for you, ask 
what you can do for our language.


Mark Lawrence

---
This email is free from viruses and malware because avast! Antivirus protection 
is active.
http://www.avast.com


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


Re: Python 3 on Mac OS X 10.8.4

2014-06-19 Thread Une Bévue

Le 19/06/14 09:52, Andrea D'Amore a écrit :

Brew should require the smaller command line package.

OK, fine thanks, I'll use brew.
--
https://mail.python.org/mailman/listinfo/python-list


urllib/urllib2 support for specifying ip address

2014-06-19 Thread Robin Becker
I want to run torture tests against an https server on domain A; I have 
configured apache on the server to respond to a specific hostname ipaddress.


I don't want to torture the live server so I have set up an alternate instance 
on a different ip address.


Is there a way to get urlib or urllib2 to use my host name and a specifed ip 
address?


I can always change my hosts file, but that is inconvenient and potentially 
dangerous.

--
Robin Becker

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


Re: Under what kind of situation, time.sleep(n) would sleep much longer than n seconds?

2014-06-19 Thread Marko Rauhamaa
Chris Angelico :

> Yeah, I think [raw_]input() isn't so bad after all.

I have never used it.

I *have* used getpass.getpass(). Unfortunately, it doesn't have a
corresponding prompt and raw input variant so I've had to essentially
copy over getpass() code and modify that:

   fd = os.open('/dev/tty', os.O_RDWR | os.O_NOCTTY)
   input = output = os.fdopen(fd, 'w+', 1)

etc.

Thing is, the standard streams are used for real work instead of
interacting with the user.


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


Re: urllib/urllib2 support for specifying ip address

2014-06-19 Thread Chris Angelico
On Thu, Jun 19, 2014 at 7:22 PM, Robin Becker  wrote:
> I want to run torture tests against an https server on domain A; I have
> configured apache on the server to respond to a specific hostname ipaddress.
>
> I don't want to torture the live server so I have set up an alternate
> instance on a different ip address.

Since you mention urllib2, I'm assuming this is Python 2.x, not 3.x.
The exact version may be significant.

Can you simply query the server by IP address rather than host name?
According to the docs, urllib2.urlopen() doesn't check the
certificate, so it should be accepted. Or does the server insist on
the hostname being correct?

Failing that, you could monkey-patch socket.create_connection, which
seems to be the thing that ultimately does the work. Something like
this:

import socket.
orig_create_connection = socket.create_connection
def create_connection(address, *args, **kwargs):
if address == "domainA": address = "1.2.3.4"
return orig_create_connection(address, *args, **kwargs)
socket.create_connection = create_connection
# Proceed to use urllib2.urlopen()

Untested, but may do what you want.

Normally, though, I'd look at just changing the hosts file, if at all
possible. You're right that it does change state for your whole
computer, but it's generally the easiest solution.

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


Re: Understanding Python Code

2014-06-19 Thread subhabangalore
On Thursday, June 19, 2014 12:30:12 PM UTC+5:30, Ian wrote:
> On Wed, Jun 18, 2014 at 11:50 PM,   wrote:
> 
> > Thank you for the reply. But as I checked it again I found,
> 
> > f_prev[k] is giving values of f_curr[st] = e[st][x_i] * prev_f_sum
> 
> > which is calculated later and again uses prev_f_sum.
> 
> 
> 
> f_prev is the f_curr that was calculated on the previous iteration of
> 
> the loop.  At each iteration after the first, the script calculates
> 
> f_curr based on the value of f_prev, that is, the old value of f_curr.
> 
> Then it reassigns the newly computed f_curr to f_prev, making it now
> 
> the previous, and on the next iteration it creates a new dict to store
> 
> the next f_curr.  Does that make sense?

Dear Group,

The logic seems going fine. I am just trying to cross check things once more,
so trying to generate the values and see on myself. 

I am trying to see this line,
prev_f_sum = sum(f_prev[k]*a[k][st] for k in states)

a[k][st], and f_prev[k] I could take out and understood.
Now as it is doing sum() so it must be over a list,
I am trying to understand the number of entities in the list, thinking whether 
to put len(), and see for which entities it is doing the sum.

Experimenting, if any one feels may kindly send any idea.

Regards,
Subhabrata Banerjee. 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python 3 on Mac OS X 10.8.4

2014-06-19 Thread Andrew Jaffe

On 19/06/2014 08:02, Une Bévue wrote:

On my mac i do have :
$ python --version
Python 2.7.2

I want to install Python 3 such as python-3.4.0-macosx10.6.dmg avoiding
disturbing the "built-in" version.

Is that possible ?
The python.org packages are explicitly created in order to have no 
conflict with the system installed python. There is no problem with 
using them.


Yours,

Andrew



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


can I get 0./0. to return nan instead of exception?

2014-06-19 Thread Neal Becker
Can I change behavior of py3 to return nan for 0./0. instead of raising an
exception?

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


Re: Not Responding When Dealing with Large Data

2014-06-19 Thread MRAB

On 2014-06-19 09:17, cutey Love wrote:

update_idletasks didn't work.

The code is this

 file_path = filedialog.askopenfilename(filetypes=[('text files', '.txt')], 
multiple=True, defaultextension=".txt")

 for path in file_path:

 fo = open(path, "r")

 for line in fo:
 if myCase(line.lower()):
 myList.append(line.lower())
 fo.close()


def myCase(c):

 if c in myList:
 return False

 if len(c) < 8 or len(c) > 80:
 return False

return True



This processes a fair bit of data


It's quicker to look for something in a set than in a list, so if you
can use a set instead of a list, do so.

Also, checking the length of a string is quick, quicker than searching
a list.

Therefore, before processing the file, do:

mySet = set(myList)

and then you can say:

def myCase(c):
if len(c) < 8 or len(c) > 80:
return False

if c in mySet:
return False

return True

which can be shortened to:

def myCase(c):
return 8 <= len(c) <= 80 and c in mySet

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


Re: can I get 0./0. to return nan instead of exception?

2014-06-19 Thread Joel Goldstick
On Jun 19, 2014 7:05 AM, "Neal Becker"  wrote:
>
> Can I change behavior of py3 to return nan for 0./0. instead of raising an
> exception?

There is no nan in python.
>
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: can I get 0./0. to return nan instead of exception?

2014-06-19 Thread Chris “Kwpolska” Warrick
On Thu, Jun 19, 2014 at 1:31 PM, Joel Goldstick
 wrote:
>
> On Jun 19, 2014 7:05 AM, "Neal Becker"  wrote:
>>
>> Can I change behavior of py3 to return nan for 0./0. instead of raising an
>> exception?
>
> There is no nan in python.

Wrong:

>>> float('nan')
nan
>>>

also:

https://docs.python.org/2/library/math.html#math.isnan

> Check if the float x is a NaN (not a number). For more information on NaNs, 
> see the IEEE 754 standards.

-- 
Chris “Kwpolska” Warrick 
PGP: 5EAAEA16
stop html mail | always bottom-post | only UTF-8 makes sense
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: urllib/urllib2 support for specifying ip address

2014-06-19 Thread Robin Becker

..


Since you mention urllib2, I'm assuming this is Python 2.x, not 3.x.
The exact version may be significant.


I can use python >= 3.3 if required.



Can you simply query the server by IP address rather than host name?
According to the docs, urllib2.urlopen() doesn't check the
certificate, so it should be accepted. Or does the server insist on
the hostname being correct?

Failing that, you could monkey-patch socket.create_connection, which
seems to be the thing that ultimately does the work. Something like
this:

import socket.
orig_create_connection = socket.create_connection
def create_connection(address, *args, **kwargs):
 if address == "domainA": address = "1.2.3.4"
 return orig_create_connection(address, *args, **kwargs)
socket.create_connection = create_connection
# Proceed to use urllib2.urlopen()

Untested, but may do what you want.



this seems like a way forward



Normally, though, I'd look at just changing the hosts file, if at all
possible. You're right that it does change state for your whole
computer, but it's generally the easiest solution.

ChrisA

me too, but I want to start torturing from about 10 different servers so plumbum 
+ a python script seems like a good choice and I would not really want to hack 
the hosts files back and forth on a regular basis.

--
Robin Becker

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


Re: can I get 0./0. to return nan instead of exception?

2014-06-19 Thread Chris Angelico
On Thu, Jun 19, 2014 at 9:31 PM, Joel Goldstick
 wrote:
> On Jun 19, 2014 7:05 AM, "Neal Becker"  wrote:
>>
>> Can I change behavior of py3 to return nan for 0./0. instead of raising an
>> exception?
>
> There is no nan in python.

Yes, there is, but it's not normal to get it as a division result like that.

One way is to explicitly try/except:

try:
result = operand_1 / operand_2
except ZeroDivisionError:
result = float("nan")

You may also be able to use the fpectl module, if it's available on
your system. Alternatively, use either decimal.Decimal or one of the
numpy types, both of which give you more flexibility in error handling
than the inbuilt float type gives. If you're doing heavy computational
work in Python and expect exact IEEE floating point semantics, you
should probably be using numpy anyway.

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


Re: urllib/urllib2 support for specifying ip address

2014-06-19 Thread Chris Angelico
On Thu, Jun 19, 2014 at 9:51 PM, Robin Becker  wrote:
>> Since you mention urllib2, I'm assuming this is Python 2.x, not 3.x.
>> The exact version may be significant.
>>
> I can use python >= 3.3 if required.

The main reason I ask is in case something's changed. Basically, what
I did was go to my Python 2 installation (which happens to be 2.7.3,
because that's what Debian Wheezy ships with - not sure why it hasn't
been updated beyond that), pull up urllib2.py, and step through
manually, seeing where the hostname gets turned into an IP address.
Hence, this code:

>> import socket.
>> orig_create_connection = socket.create_connection
>> def create_connection(address, *args, **kwargs):
>>  if address == "domainA": address = "1.2.3.4"
>>  return orig_create_connection(address, *args, **kwargs)
>> socket.create_connection = create_connection
>> # Proceed to use urllib2.urlopen()
>>
>> Untested, but may do what you want.
>>
>
> this seems like a way forward

So if it works, that's great! If it doesn't, and you're on a different
version of Python (2.6? 2.4 even?), you might want to look at
repeating the exercise I did, with your actual Python.

But as a general rule, I'd recommend going with Python 3.x unless you
have a good reason for using 2.x. If a feature's been added to let you
mock in a different IP address, it'll be in 3.something but probably
not in 2.7.

>> Normally, though, I'd look at just changing the hosts file, if at all
>> possible. You're right that it does change state for your whole
>> computer, but it's generally the easiest solution.
>>
>> ChrisA
>>
> me too, but I want to start torturing from about 10 different servers so
> plumbum + a python script seems like a good choice and I would not really
> want to hack the hosts files back and forth on a regular basis.

Fair enough. In that case, the best thing to do would probably be
monkey-patching, with code along the lines of what I posted above.
Make the change as small and as specific as you can.

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


Re: Backport fix on #16611 to Python 2.7

2014-06-19 Thread Makoto Kuwata
Sorry, I failed to post reply:

-- Forwarded message --
From: Makoto Kuwata 
Date: Wed, Jun 18, 2014 at 5:32 PM
Subject: Re: Backport fix on #16611 to Python 2.7
To: Terry Reedy 


On Wed, Jun 18, 2014 at 12:31 PM, Terry Reedy  wrote:

>
> Do you have any plan to upgrade to 3.4, so you get *all* the bugfixes
> possible?
>
>
Please ask to Google. Google AppEngine doesn't support 3.4 yet.


On 6/17/2014 9:08 PM, Mark Lawrence wrote:

> The simple answer is no.  The longer answer is, if you want to propose a
>> patch to backport the fix, it's more likely that somebody will do the
>> work to commit it as support for 2.7 has been extended until 2020.
>> Please note that I said "more likely", there's no guarantee given that
>> Python relies so much on volunteers.
>>
>
I got it. Thank you.



>
> The extended support is mostly focused on build (compiler) and security
> (internet) issues, to support software already written and *working* on 2.7.
>
> That said, if someone were to modify the patch to it could be imported to
> 2.7 (at least changing file names) or make changes to the relevant files by
> hand; run the tests, with whatever changes are needed so that they do run;
> and change the code as needed so all tests pass; sign the contributor
> agreement; and post a properly formatted test to the tracker and indicate a
> readiness to respond to comments; then it might get some attention.
>
> --
> Terry Jan Reedy
>

I'm sorry if I bothered you. I just want to know whether the existing
bugfix will be backported or not.
I should be more careful to post even a small question.

--
regards,
makoto kuwata
-- 
https://mail.python.org/mailman/listinfo/python-list


DHCP query script not work.

2014-06-19 Thread 不坏阿峰
Dear all

i got code recipes from here. and i want to run it on win 7. 
http://code.activestate.com/recipes/577649-dhcp-query/

i have do some modify and use print to check how it is work, but i am stucked 
now. 

hope someone can help me. thanks a lot.

i meet this error:

Traceback (most recent call last):
  File "D:/Workspace/TestExcel/Test/test_DHCP.py", line 138, in 
offer = DHCPOffer(data, discoverPacket.transactionID)
  File "D:/Workspace/TestExcel/Test/test_DHCP.py", line 82, in __init__
self.unpack()
  File "D:/Workspace/TestExcel/Test/test_DHCP.py", line 95, in unpack
dnsNB = int(data[268] / 4)
TypeError: unsupported operand type(s) for /: 'str' and 'int'


__author__ = 'Administrator'

'''
Created on Mar 27, 2011

@author: hassane
'''
import socket
import struct
from uuid import getnode as get_mac
from random import randint


def getMacInBytes():
print get_mac()
mac = str(hex(get_mac()))
print mac
mac = mac[2:]
mac = mac[:-1]  # i edited
print mac, len(mac)
while len(mac) < 12:
mac = '0' + mac
print mac
macb = b''
for i in range(0, 12, 2):
print mac[i:i + 2]
m = int(mac[i:i + 2], 16)
#print m
macb += struct.pack('!B', m)
print repr(macb), struct.calcsize('!B'),"++"
print macb,"=="
return macb


class DHCPDiscover:
def __init__(self):
self.transactionID = b''
for i in range(4):
t = randint(0, 255)
self.transactionID += struct.pack('!B', t)
print self.transactionID, "=="
def buildPacket(self):
macb = getMacInBytes()
print repr(macb)
packet = b''
packet += b'\x01'  # Message type: Boot Request (1)
packet += b'\x01'  # Hardware type: Ethernet
packet += b'\x06'  # Hardware address length: 6
packet += b'\x00'  # Hops: 0
packet += self.transactionID  # Transaction ID
packet += b'\x00\x00'  # Seconds elapsed: 0
packet += b'\x80\x00'  # Bootp flags: 0x8000 (Broadcast) + reserved 
flags
packet += b'\x00\x00\x00\x00'  # Client IP address: 0.0.0.0
packet += b'\x00\x00\x00\x00'  # Your (client) IP address: 0.0.0.0
packet += b'\x00\x00\x00\x00'  # Next server IP address: 0.0.0.0
packet += b'\x00\x00\x00\x00'  # Relay agent IP address: 0.0.0.0
# packet += b'\x00\x26\x9e\x04\x1e\x9b'   #Client MAC address: 
00:26:9e:04:1e:9b
packet += macb
packet += b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'  #Client hardware 
address padding: 
packet += b'\x00' * 67  #Server host name not given
packet += b'\x00' * 125  #Boot file name not given
packet += b'\x63\x82\x53\x63'  #Magic cookie: DHCP
packet += b'\x35\x01\x01'  #Option: (t=53,l=1) DHCP Message Type = DHCP 
Discover
#packet += b'\x3d\x06\x00\x26\x9e\x04\x1e\x9b'   #Option: (t=61,l=6) 
Client identifier
packet += b'\x3d\x06' + macb
packet += b'\x37\x03\x03\x01\x06'  #Option: (t=55,l=3) Parameter 
Request List
packet += b'\xff'  #End Option
return packet

class DHCPOffer:
def __init__(self, data, transID):
self.data = data
self.transID = transID
self.offerIP = ''
self.nextServerIP = ''
self.DHCPServerIdentifier = ''
self.leaseTime = ''
self.router = ''
self.subnetMask = ''
self.DNS = []
self.unpack()

def unpack(self):
if self.data[4:8] == self.transID:
self.offerIP = '.'.join(map(lambda x: str(x), data[16:20]))
self.nextServerIP = '.'.join(map(lambda x: str(x), data[20:24]))  # 
c'est une option
self.DHCPServerIdentifier = '.'.join(map(lambda x: str(x), 
data[245:249]))
self.leaseTime = str(struct.unpack('!L', data[251:255])[0])
self.router = '.'.join(map(lambda x: str(x), data[257:261]))
self.subnetMask = '.'.join(map(lambda x: str(x), data[263:267]))
#print self.router, self.subnetMask, self.leaseTime, 
self.DHCPServerIdentifier, repr(self.offerIP)
print repr(data)
print repr(data[268])
dnsNB = int(data[268] / 4)
for i in range(0, 4 * dnsNB, 4):
self.DNS.append('.'.join(map(lambda x: str(x), data[269 + i:269 
+ i + 4])))

def printOffer(self):
key = ['DHCP Server', 'Offered IP address', 'subnet mask', 'lease time 
(s)', 'default gateway']
val = [self.DHCPServerIdentifier, self.offerIP, self.subnetMask, 
self.leaseTime, self.router]
for i in range(4):
print('{0:20s} : {1:15s}'.format(key[i], val[i]))

print('{0:20s}'.format('DNS Servers') + ' : ', ) #end=''   here also 
have error.
if self.DNS:
print('{0:15s}'.format(self.DNS[0]))
if len(self.DNS) > 1:
for i in range(1, len(self.DNS)):
print('{

Re: DHCP query script not work.

2014-06-19 Thread Steven D'Aprano
On Thu, 19 Jun 2014 05:56:57 -0700, 不坏阿峰 wrote:


> Traceback (most recent call last):
>   File "D:/Workspace/TestExcel/Test/test_DHCP.py", line 138, in 
> offer = DHCPOffer(data, discoverPacket.transactionID)
>   File "D:/Workspace/TestExcel/Test/test_DHCP.py", line 82, in __init__
> self.unpack()
>   File "D:/Workspace/TestExcel/Test/test_DHCP.py", line 95, in unpack
> dnsNB = int(data[268] / 4)
> TypeError: unsupported operand type(s) for /: 'str' and 'int'


data[268] returns a string. You cannot divide a string by an int.

Perhaps you need to change the line to this?

dnsNB = int(data[268]) / 4



-- 
Steven D'Aprano
-- 
https://mail.python.org/mailman/listinfo/python-list


pyhon 1.5.2 problem

2014-06-19 Thread Pat Fourie
Good Day all,

I have the following problem.

This is the python code

#

Import SER

#

SER.set_speed('115200','8N1')

..

..

..

When I run the above code I get the following error :

 

SER.set_speed('115200','8N1')

AttributeError : set_speed

 

Can anyone help as this did work before.I have recompiled everything but the
problem still

Exists.

In anticipation,

Many Thanks

Pat

p...@icon.co.za

 


-- 
This message has been scanned for viruses and
dangerous content by Pinpoint, and is
believed to be clean.

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


Re: DHCP query script not work.

2014-06-19 Thread Peter Otten
不坏阿峰 wrote:

> i got code recipes from here. and i want to run it on win 7.
> http://code.activestate.com/recipes/577649-dhcp-query/
> 
> i have do some modify and use print to check how it is work, but i am
> stucked now.
> 
> hope someone can help me. thanks a lot.
> 
> i meet this error:
> 
> Traceback (most recent call last):
>   File "D:/Workspace/TestExcel/Test/test_DHCP.py", line 138, in 
> offer = DHCPOffer(data, discoverPacket.transactionID)
>   File "D:/Workspace/TestExcel/Test/test_DHCP.py", line 82, in __init__
> self.unpack()
>   File "D:/Workspace/TestExcel/Test/test_DHCP.py", line 95, in unpack
> dnsNB = int(data[268] / 4)
> TypeError: unsupported operand type(s) for /: 'str' and 'int'

The script is written for Python 3, and you seem to be using a Python 2 
interpreter. While

dnsNB = int(data[268]/4)

would become

dnsNB = ord(data[268])/4

in Python 2 that's probably not the only change that needs to be made. For 
someone not familiar with Python the easiest fix is to install Python 3.4 
(you don't need to unistall Python 2) and to run the script as is.

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


Re: DHCP query script not work.

2014-06-19 Thread soneedu
On Thursday, June 19, 2014 8:23:17 PM UTC+7, Peter Otten wrote:
> 不坏阿峰 wrote:
> 
> 
> 
> > i got code recipes from here. and i want to run it on win 7.
> 
> > http://code.activestate.com/recipes/577649-dhcp-query/
> 
> > 
> 
> > i have do some modify and use print to check how it is work, but i am
> 
> > stucked now.
> 
> > 
> 
> > hope someone can help me. thanks a lot.
> 
> > 
> 
> > i meet this error:
> 
> > 
> 
> > Traceback (most recent call last):
> 
> >   File "D:/Workspace/TestExcel/Test/test_DHCP.py", line 138, in 
> 
> > offer = DHCPOffer(data, discoverPacket.transactionID)
> 
> >   File "D:/Workspace/TestExcel/Test/test_DHCP.py", line 82, in __init__
> 
> > self.unpack()
> 
> >   File "D:/Workspace/TestExcel/Test/test_DHCP.py", line 95, in unpack
> 
> > dnsNB = int(data[268] / 4)
> 
> > TypeError: unsupported operand type(s) for /: 'str' and 'int'
> 
> 
> 
> The script is written for Python 3, and you seem to be using a Python 2 
> 
> interpreter. While
> 
> 
> 
> dnsNB = int(data[268]/4)
> 
> 
> 
> would become
> 
> 
> 
> dnsNB = ord(data[268])/4
> 
> 
> 
> in Python 2 that's probably not the only change that needs to be made. For 
> 
> someone not familiar with Python the easiest fix is to install Python 3.4 
> 
> (you don't need to unistall Python 2) and to run the script as is.

yes, i use Python 2.7. i am a beginner learn network program part.  i can not 
modify it myself now, i have trid some days.  hope some expert can help me 
correct this code in Python 2.7.

many thanks in advanced.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pyhon 1.5.2 problem

2014-06-19 Thread Peter Otten
Pat Fourie wrote:

> Good Day all,
> 
> I have the following problem.
> 
> This is the python code
> 
> #
> 
> Import SER
> 
> #
> 
> SER.set_speed('115200','8N1')
> 
> ..
> 
> ..
> 
> ..
> 
> When I run the above code I get the following error :
> 
>  
> 
> SER.set_speed('115200','8N1')
> 
> AttributeError : set_speed
> 
>  
> 
> Can anyone help as this did work before.I have recompiled everything but
> the problem still
> 
> Exists.
> 
> In anticipation,

Did you create a new file called SER.py recently? If so rename that and 
don't forget to delete the corresponding SER.pyc.

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


Re: DHCP query script not work.

2014-06-19 Thread 不坏阿峰
在 2014年6月19日星期四UTC+7下午8时23分17秒,Peter Otten写道:
> 不坏阿峰 wrote:
> 
> 
> 
> > i got code recipes from here. and i want to run it on win 7.
> 
> > http://code.activestate.com/recipes/577649-dhcp-query/
> 
> > 
> 
> > i have do some modify and use print to check how it is work, but i am
> 
> > stucked now.
> 
> > 
> 
> > hope someone can help me. thanks a lot.
> 
> > 
> 
> > i meet this error:
> 
> > 
> 
> > Traceback (most recent call last):
> 
> >   File "D:/Workspace/TestExcel/Test/test_DHCP.py", line 138, in 
> 
> > offer = DHCPOffer(data, discoverPacket.transactionID)
> 
> >   File "D:/Workspace/TestExcel/Test/test_DHCP.py", line 82, in __init__
> 
> > self.unpack()
> 
> >   File "D:/Workspace/TestExcel/Test/test_DHCP.py", line 95, in unpack
> 
> > dnsNB = int(data[268] / 4)
> 
> > TypeError: unsupported operand type(s) for /: 'str' and 'int'
> 
> 
> 
> The script is written for Python 3, and you seem to be using a Python 2 
> 
> interpreter. While
> 
> 
> 
> dnsNB = int(data[268]/4)
> 
> 
> 
> would become
> 
> 
> 
> dnsNB = ord(data[268])/4
> 
> 
> 
> in Python 2 that's probably not the only change that needs to be made. For 
> 
> someone not familiar with Python the easiest fix is to install Python 3.4 
> 
> (you don't need to unistall Python 2) and to run the script as is.

yes, i use Python 2.7. i am a beginner learn network program part.  i can not 
modify it myself now, i have trid some days.  hope some expert can help me 
correct this code in Python 2.7. 

many thanks in advanced.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to check if a value is a floating point or not

2014-06-19 Thread Sturla Molden
 wrote:
> I am making a calculator and i need it to support floating point values
> but i am using the function isnumeric to check if the user has entered an
> int value. I need the same for floating point types so i could implement
> an or in the if statement that checks the values the user has entered and
> allow it to check and use floating points. If you need the source code i
> am happy to give it to you. Thank you for your help

It's better to ask forgiveness than ask permission...

You don't have to check anything. If the user enters something that cannot
be coverted to a float, the function float() will raise an exception:

try: 
x = float(value)
except ValueError:
# not a float
pass


Sturla

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


Re: DHCP query script not work.

2014-06-19 Thread Anssi Saari
不坏阿峰  writes:

> Dear all
>
> i got code recipes from here. and i want to run it on win 7. 
> http://code.activestate.com/recipes/577649-dhcp-query/

It works for me as is in Windows 7. It's a Python 3 script though which
might be your problem.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: DHCP query script not work.

2014-06-19 Thread 不坏阿峰
On Thursday, June 19, 2014 8:49:21 PM UTC+7, Anssi Saari wrote:
> 不坏阿峰  writes:
> 
> 
> 
> > Dear all
> 
> >
> 
> > i got code recipes from here. and i want to run it on win 7. 
> 
> > http://code.activestate.com/recipes/577649-dhcp-query/
> 
> 
> 
> It works for me as is in Windows 7. It's a Python 3 script though which
> 
> might be your problem.


i got that my issue is the Python version , my is 2.7. i am not familiar with 
3.and my tools coded by 2.7.   

i am stucked on this script.  tks for ur reply.  hope have someone change this 
script work on 2.7


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


Re: pyhon 1.5.2 problem

2014-06-19 Thread Steven D'Aprano
Are you really using Python 1.5.2? Wow. That's really old :-)

Please copy and paste the *full* traceback that Python shows.

A few more comments below:

On Thu, 19 Jun 2014 14:55:36 +0200, Pat Fourie wrote:

> This is the python code
> 
> #
> Import SER

No it isn't. "Import SER" is a syntax error. Python is case-sensitive, 
you mean "import SER" in lowercase. But the problem is, if you re-type 
the code in your message, instead of copying and pasting it, who knows 
what other new errors you introduce? We could waste hours trying to debug 
code containing errors that don't exist in the original.

Always COPY AND PASTE the EXACT code, do not re-type it from memory.

> #
> SER.set_speed('115200','8N1')

> When I run the above code I get the following error :
>  
> SER.set_speed('115200','8N1')
> AttributeError : set_speed

Do you have two files called SER, perhaps in different directories? One 
contains set_speed function, the other does not?

You should rename one of the files. Also watch out for left-over SER.pyc 
files, you should delete them.




-- 
Steven D'Aprano
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Understanding Python Code

2014-06-19 Thread Ian Kelly
On Thu, Jun 19, 2014 at 3:48 AM,   wrote:
> I am trying to see this line,
> prev_f_sum = sum(f_prev[k]*a[k][st] for k in states)
>
> a[k][st], and f_prev[k] I could take out and understood.
> Now as it is doing sum() so it must be over a list,
> I am trying to understand the number of entities in the list, thinking 
> whether to put len(), and see for which entities it is doing the sum.

It's summing a generator expression, not a list.  If it helps to
understand it, you could rewrite that line like this:

values_to_be_summed = []
for k in states:
values_to_be_summed.append(f_prev[k]*a[k][st])
prev_f_sum = sum(values_to_be_summed)

So the number of entities in the list is len(states).
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Create flowcharts from Python

2014-06-19 Thread Wolfgang Keller
> Is there a library for Python that can easily create flowcharts using
> a simple API?

Graphviz (->TikZ->LaTeX->PDF)

> But the users want to see this as a  visual flowchart too. It would
> be the best to have it automatically arranged; or at least open it an
> editor so they can move the nodes and see how they are connected.

I think Dia and yEd can im-/export dot (Graphviz format) and/or TikZ.

Sincerely,

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


Re: urllib/urllib2 support for specifying ip address

2014-06-19 Thread Robin Becker

On 19/06/2014 13:03, Chris Angelico wrote:
.

I can use python >= 3.3 if required.


The main reason I ask is in case something's changed. Basically, what
I did was go to my Python 2 installation (which happens to be 2.7.3,
because that's what Debian Wheezy ships with - not sure why it hasn't
been updated beyond that), pull up urllib2.py, and step through
manually, seeing where the hostname gets turned into an IP address.
Hence, this code:

.
in practice this approach worked well with urllib in python27.
--
Robin Becker
--
https://mail.python.org/mailman/listinfo/python-list


Re: urllib/urllib2 support for specifying ip address

2014-06-19 Thread Chris Angelico
On Fri, Jun 20, 2014 at 12:19 AM, Robin Becker  wrote:
> in practice [monkeypatching socket] worked well with urllib in python27.

Excellent! That's empirical evidence of success, then.

Like with all monkey-patching, you need to keep it as visible as
possible, but if your driver script is only a page or two of code, it
should be pretty clear what's going on.

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


Re: Understanding Python Code

2014-06-19 Thread subhabangalore
On Thursday, June 19, 2014 7:39:42 PM UTC+5:30, Ian wrote:
> On Thu, Jun 19, 2014 at 3:48 AM, wrote:
> 
> > I am trying to see this line,
> 
> > prev_f_sum = sum(f_prev[k]*a[k][st] for k in states)
> 
> >
> 
> > a[k][st], and f_prev[k] I could take out and understood.
> 
> > Now as it is doing sum() so it must be over a list,
> 
> > I am trying to understand the number of entities in the list, thinking 
> > whether to put len(), and see for which entities it is doing the sum.
> 
> 
> 
> It's summing a generator expression, not a list.  If it helps to
> 
> understand it, you could rewrite that line like this:
> 
> 
> 
> values_to_be_summed = []
> 
> for k in states:
> 
> values_to_be_summed.append(f_prev[k]*a[k][st])
> 
> prev_f_sum = sum(values_to_be_summed)
> 
> 
> 
> So the number of entities in the list is len(states).

Dear Group,

Thank you for your kind answer. As I put from the error I discovered it. Please 
see my experiment almost near to your answer. I am trying one or two questions 
like, why it is appending only two values at a time. If you want to assist you 
may kindly help me assist me.
Regards,
Subhabrata Banerjee.
***
MY EXPERIMENT
***
else:
for k in states:
print "YYY1",f_prev[k]
print "YYY2",a[k][st]
prev_f_sum1=f_prev[k]*a[k][st]
print "YYY3",prev_f_sum1
prev_f_sum2 = sum(f_prev[k]*a[k][st] for k in 
states)
print "YYY4",prev_f_sum2
***
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Not Responding When Dealing with Large Data

2014-06-19 Thread Peter Pearson
On Thu, 19 Jun 2014 12:25:23 +0100, MRAB  wrote:
[snip]
> and then you can say:
>
>  def myCase(c):
>  if len(c) < 8 or len(c) > 80:
>  return False
>
>  if c in mySet:
>  return False
>
>  return True
>
> which can be shortened to:
>
>  def myCase(c):
>  return 8 <= len(c) <= 80 and c in mySet

Don't you mean . . .

return 8 <= len(c) <= 80 and c not in mySet
?


-- 
To email me, substitute nowhere->spamcop, invalid->net.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Not Responding When Dealing with Large Data

2014-06-19 Thread MRAB

On 2014-06-19 17:21, Peter Pearson wrote:

On Thu, 19 Jun 2014 12:25:23 +0100, MRAB  wrote:
[snip]

and then you can say:

 def myCase(c):
 if len(c) < 8 or len(c) > 80:
 return False

 if c in mySet:
 return False

 return True

which can be shortened to:

 def myCase(c):
 return 8 <= len(c) <= 80 and c in mySet


Don't you mean . . .

 return 8 <= len(c) <= 80 and c not in mySet
?


Yes, you're right.
--
https://mail.python.org/mailman/listinfo/python-list


Re: Under what kind of situation, time.sleep(n) would sleep much longer than n seconds?

2014-06-19 Thread Christian Gollwitzer

Am 19.06.14 09:42, schrieb Chris Angelico:

On Thu, Jun 19, 2014 at 5:18 PM, Christian Gollwitzer  wrote:

Am 19.06.14 01:38, schrieb Chris Angelico:


a good console UI just requires this:

something = raw_input("Enter something: ")
print("Result: "+result)



That is actually one of the worst console UIs possible



I disagree. It may not be the *best* console UI, but it's not as bad
as you think. Yes, what I wrote was a massive oversimplification, but
compare this:

https://github.com/Rosuav/runningtime/blob/master/runningtime.py#L44

That's a simple, straight-forward UI. If you put the .py file onto
your desktop and double-click it, you'll see a series of prompts, and
this works on Windows, OS/2, probably Mac OS, and quite a few Linux
desktops.


While I don't understand the purpose of the program (is it a game?), it 
shows exactly why this is a bad idea. Here is my try (OSX):


Apfelkiste:Tests chris$ python runningtime.py
Enter track length in m: 20
Enter speed limit [400km/h]: 300
Enter track length in m: 10
Enter speed limit [400km/h]: 100
Enter track length in m: 0
()
[  0.00] Power
[  7.85] Enter next section (10m speed 100)
[  8.00] Cruise
[  9.49] Enter next section (0m speed 0)
Traceback (most recent call last):
  File "runningtime.py", line 205, in 
nextsection, nextspeed = next(section)
StopIteration

Suppose I want to run it again, but have length 30 in the first step.

1.)How am I going to do this? I have to restart it and key in 4 numbers, 
whereas I only wanted to change 1. Now let that be 10 segments.


2.) There is no way to save the input or the result. Or it may not be 
obvious. I could prepare a file with the numbers, then do


python runningtime.py  output
But then I don't see the prompts and have to be careful not to enter a 
speed for a length.


3.) The program doesn't tell me how to break out of the entering process 
and start the computation. Is it a 0? Is it an empty string? I'm getting 
Tracebacks in either case (could be wrong python version, I'm using the 
OSX default 2.7.2)


All these problems arise because the program forces me to enter the data 
in a predefined sequence. So no, this is not a good user experience. In 
a GUI it would be trivial to have an editable listbox for track length 
and speed, and a set of buttons to save, load, run the computation.


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


Re: Understanding Python Code

2014-06-19 Thread subhabangalore
On Thursday, June 19, 2014 7:57:38 PM UTC+5:30, wrote:
> On Thursday, June 19, 2014 7:39:42 PM UTC+5:30, Ian wrote:
> 
> > On Thu, Jun 19, 2014 at 3:48 AM, wrote:
> 
> > 
> 
> > > I am trying to see this line,
> 
> > 
> 
> > > prev_f_sum = sum(f_prev[k]*a[k][st] for k in states)
> 
> > 
> 
> > >
> 
> > 
> 
> > > a[k][st], and f_prev[k] I could take out and understood.
> 
> > 
> 
> > > Now as it is doing sum() so it must be over a list,
> 
> > 
> 
> > > I am trying to understand the number of entities in the list, thinking 
> > > whether to put len(), and see for which entities it is doing the sum.
> 
> > 
> 
> > 
> 
> > 
> 
> > It's summing a generator expression, not a list.  If it helps to
> 
> > 
> 
> > understand it, you could rewrite that line like this:
> 
> > 
> 
> > 
> 
> > 
> 
> > values_to_be_summed = []
> 
> > 
> 
> > for k in states:
> 
> > 
> 
> > values_to_be_summed.append(f_prev[k]*a[k][st])
> 
> > 
> 
> > prev_f_sum = sum(values_to_be_summed)
> 
> > 
> 
> > 
> 
> > 
> 
> > So the number of entities in the list is len(states).
> 
> 
> 
> Dear Group,
> 
> 
> 
> Thank you for your kind answer. As I put from the error I discovered it. 
> Please see my experiment almost near to your answer. I am trying one or two 
> questions like, why it is appending only two values at a time. If you want to 
> assist you may kindly help me assist me.
> 
> Regards,
> 
> Subhabrata Banerjee.
> 
> ***
> 
> MY EXPERIMENT
> 
> ***
> 
> else:
> 
>   for k in states:
> 
>   print "YYY1",f_prev[k]
> 
>   print "YYY2",a[k][st]
> 
>   prev_f_sum1=f_prev[k]*a[k][st]
> 
>   print "YYY3",prev_f_sum1
> 
>   prev_f_sum2 = sum(f_prev[k]*a[k][st] for k in 
> states)
> 
>   print "YYY4",prev_f_sum2
> 
> ***
Dear Group,
Generally most of the issues are tackled here, but as I am trying to cross 
check my understanding I found another question,

f_curr[st] = e[st][x_i] * prev_f_sum

Here, if I give one print command and see the results, 
print "$$2",f_curr

It is showing an iterative update like,
$$2 {'Healthy': 0.3},
$$2 {'Healthy': 0.3, 'Fever': 0.04001}

I was trying to ask how the size is being updated, from 1 to 2 back to 1 again 
2... is it for any loop then which one, I tried to change but not being able 
to if any one of the esteemed members may kindly help me.

Regards,
Subhabrata Banerjee.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Understanding Python Code

2014-06-19 Thread Ian Kelly
On Thu, Jun 19, 2014 at 12:44 PM,   wrote:
> Dear Group,
> Generally most of the issues are tackled here, but as I am trying to cross 
> check my understanding I found another question,
>
> f_curr[st] = e[st][x_i] * prev_f_sum
>
> Here, if I give one print command and see the results,
> print "$$2",f_curr
>
> It is showing an iterative update like,
> $$2 {'Healthy': 0.3},
> $$2 {'Healthy': 0.3, 'Fever': 0.04001}
>
> I was trying to ask how the size is being updated, from 1 to 2 back to 1 
> again 2... is it for any loop then which one, I tried to change but not being 
> able
> to if any one of the esteemed members may kindly help me.

That statement is inside the for loop that builds the f_curr dict. One
state gets calculated on each iteration. The first time it prints, one
state has been added. The second time it prints, two states have been
added. You only have two states, so at that point the loop is done.
The next time it prints, it's on the next iteration of the outer (i,
x_i) loop and it's building a new f_curr dict. So then you see it
adding one state and then the second state to the new dict. And so on
and so forth until the outer loop completes.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Under what kind of situation, time.sleep(n) would sleep much longer than n seconds?

2014-06-19 Thread Chris Angelico
On Fri, Jun 20, 2014 at 3:17 AM, Christian Gollwitzer  wrote:
> While I don't understand the purpose of the program (is it a game?), it
> shows exactly why this is a bad idea.

It's a tool for calculating stuff about railway tracks. Never mind
about the details of what it does with the info, but the input phase
you're talking about is basically building up a speed map of the track
- straight-line track has an effective speed limit of 400km/h, curves
have lower limits.

> Here is my try (OSX):
>
> Apfelkiste:Tests chris$ python runningtime.py
> Enter track length in m: 20
> Enter speed limit [400km/h]: 300
> Enter track length in m: 10
> Enter speed limit [400km/h]: 100
> Enter track length in m: 0
> ()
> [  0.00] Power
> [  7.85] Enter next section (10m speed 100)
> [  8.00] Cruise
> [  9.49] Enter next section (0m speed 0)
> Traceback (most recent call last):
>   File "runningtime.py", line 205, in 
> nextsection, nextspeed = next(section)
> StopIteration

Well, you didn't put in enough track for the train to even get
started. Basically, you built thirty meters of railway line, then put
a suburban train on it (264 meters long - the figure's at the top of
the program, although I wouldn't expect anyone to know it; however, it
should make perfect sense that a train is more than 30m long!). So the
program crashed, because this is an early alpha that's designed to be
used by someone who knows what he's doing. If you crank those figures
up a bit and, say, put a few km of track down, then it won't bomb.

> Suppose I want to run it again, but have length 30 in the first step.

That would still be extremely odd, but suppose you want length 3000 in
the first step.

> 1.)How am I going to do this? I have to restart it and key in 4 numbers,
> whereas I only wanted to change 1. Now let that be 10 segments.
>
> 2.) There is no way to save the input or the result. Or it may not be
> obvious. I could prepare a file with the numbers, then do
>
> python runningtime.py  output
> But then I don't see the prompts and have to be careful not to enter a speed
> for a length.

The program is designed to be used with either copy/paste or
redirection (you'll note a line comment in the code about redirection)
for that sort of scenario, and there's a TODO in the code to have it
read sys.argv. Thing is, you're looking at an extremely early alpha
that I developed alongside the one person who actually intends to use
it; any time spent on a GUI would be wasted at this stage, and even
parsing sys.argv to figure out which are file names and which are
other things would probably be a waste. Making something more
resilient would require design effort (first thought: read two numbers
per line, the length and the curve speed, and if it's a single number,
it's straight track at maximum speed) and thus would require
explanation ("so you need to put the two numbers on the same line").
It can be left for later.

Main point being that the existing UI works, and took almost no
effort. It gives us 99% of what we need for 1% of the work. The rest
of what we want can be obtained with small refinements, rather than a
full rewrite into a GUI.

> 3.) The program doesn't tell me how to break out of the entering process and
> start the computation. Is it a 0? Is it an empty string? I'm getting
> Tracebacks in either case (could be wrong python version, I'm using the OSX
> default 2.7.2)

The traceback when you enter a 0 is because you didn't give it enough
track to work with. The traceback on the empty string is because
that's a Python 3 program - it uses input() not raw_input() - and
you're asking it to eval an empty string. To be honest, I'm impressed
that it works as well as it does on 2.7; I never tested it. Definitely
some of the multi-arg print calls will produce messy output on 2.7
(they'll be printing tuples), but apparently the rest of the code is
so simple that a single __future__ directive and "try: input=raw_input
 except NameError: pass" would make it work on 2.7. But we don't need
2.7 support.

> All these problems arise because the program forces me to enter the data in
> a predefined sequence. So no, this is not a good user experience. In a GUI
> it would be trivial to have an editable listbox for track length and speed,
> and a set of buttons to save, load, run the computation.

You're thinking in terms of the wrong sort of user and the wrong
scenario. Is it "a good user experience" to drop you into a completely
promptless input space, wait for you to hit Ctrl-D, and then echo back
every line you typed, in order? Because that's what the standard Unix
sort command does if you give it no args and no redirection. Is that
horrible design? Nope.

What runningtime.py has may not be 100% perfect, but it's better than
the editable listbox for several reasons:

1) Editing is actually not a common operation. Normal is to go through
a piece of track (as defined by some external resource), figure out
how long it'll take to go through it, an

Re: Under what kind of situation, time.sleep(n) would sleep much longer than n seconds?

2014-06-19 Thread Terry Reedy

On 6/19/2014 3:42 AM, Chris Angelico wrote:

On Thu, Jun 19, 2014 at 5:18 PM, Christian Gollwitzer  wrote:



My advice:

1) First try parsing the command line. (Example: All Unix tools)

2) If you require more interaction and maybe state preservation, just write
a couple of functions and run it in IPython (Example: SciPy)

3) Use a real GUI framework

It turns out, that 3) is actually not only easier to use, but often easier
to write than 1)


I disagree. It may not be the *best* console UI, but it's not as bad
as you think. Yes, what I wrote was a massive oversimplification, but
compare this:

https://github.com/Rosuav/runningtime/blob/master/runningtime.py#L44

That's a simple, straight-forward UI. If you put the .py file onto
your desktop and double-click it, you'll see a series of prompts, and
this works on Windows, OS/2, probably Mac OS, and quite a few Linux
desktops. (Although I didn't put a shebang on that file, so it might
not work on your typical Linux.) How do you make something that
provides command line arguments to a double-clicked-on icon? Different
for every platform. (And seldom as easy as it is on OS/2.) If you run
that in a terminal, you'll see a series of prompts, and it works on
probably every Python implementation EVER. If you pull it up in IDLE,
it'll probably work there too, although I haven't tried it.


Most any* console script runs fine** in Idle once you load it into the 
editor and press F5. Prompts and prints go the shell window (default 
blue on white) and input comes from the same (default black on white).


* I said most because there must be exceptions, but have no 
characterization.


** Better than the windows console in some respects.

I hope that by the end of the summer, the requirement to load in the 
editor will be gone. (Run F5 saves to a file anyway for actual 
execution.) There should also be an option to put output in a new window.


--
Terry Jan Reedy

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


Re: Under what kind of situation, time.sleep(n) would sleep much longer than n seconds?

2014-06-19 Thread Chris Angelico
On Fri, Jun 20, 2014 at 12:33 PM, Terry Reedy  wrote:
> Most any* console script runs fine** in Idle once you load it into the
> editor and press F5. Prompts and prints go the shell window (default blue on
> white) and input comes from the same (default black on white).

I figured it'd be easy, just couldn't say for sure. (To me, IDLE is
primarily an interactive interpreter, rather than an editor / script
runner.) Thanks for confirming.

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


Re: how to check if a value is a floating point or not

2014-06-19 Thread Nicholas Cannon
Guys i am only a beginner at python most of the stuff you are saying i need to 
do i dont understand.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to check if a value is a floating point or not

2014-06-19 Thread Ian Kelly
On Fri, Jun 20, 2014 at 12:14 AM, Nicholas Cannon
 wrote:
> Guys i am only a beginner at python most of the stuff you are saying i need 
> to do i dont understand.

All we're saying is that the simplest and most accurate way to
determine whether a string can be converted to an int or a float is to
try converting it and see if it succeeds.  If it fails, it will raise
an exception that you can catch using the try-except syntax.  Here's
what your checkint function might look like:

def checkint(a):
try:
int(a)
except ValueError:
return False
else:
return True
-- 
https://mail.python.org/mailman/listinfo/python-list