[Tutor] urllib2 issue getting realm

2011-08-31 Thread Johan Geldenhuys
Hi everybody,

I am trying to use a very simple piece of code to get the realm from
different HTTPS URLs.

This realm is essential for successful authentication on the HTTPS session.

If have to run this for a few different hosts and capture the realm.
For one host, it works perfectly, but when I try the same code to get the
next realm, it fails. I suspect that I need to close some type of
connections or something, but I can't put my finger on it.

This what I try:

>>> ips = ['192.168.10.190', '192.168.10.191', '192.168.10.192',
'192.168.10.193']
>>> URL = "https://%s/axis-cgi/jpg/image.cgi?resolution=1280x800";
>>> import urllib2
>>> try:
... req = urllib2.Request(URL % ips[0])
... handle = urllib2.urlopen(req)
... except IOError, e:
... print `e`
... 
HTTPError()
>>> 
>>> e
HTTPError()
>>> authline = e.headers.get('www-authenticate', '')
>>> authline
'Digest realm="AXIS_00408CB71F14",
nonce="0002c497Y6450989253d0ea85587e89821031c60ab9768", stale=FALSE,
qop="auth", Basic realm="AXIS_00408CB71F14"'
>>>
>>> handle
  File "", line 1, in 
'''  : name 'handle' is not defined '''
>>> req

>>> req.host
'192.168.10.190'
>>>



At this point, I am happy. It worked. I expect the try to fail to get the
exception.

For the next one:

>>> try:
... req = urllib2.Request(URL % ips[1])
... handle = urllib2.urlopen(req)
... except IOError, e:
... print `e`
... 
>>>

See, no "e" printed which means that something worked. The exception didn't
happen and I don't know why...Anybody?

I tried doing this:

>>> del req
>>> del handle
>>> del e

But with the same result:

>>> try:
... req = urllib2.Request(URL % ips[1])
... handle = urllib2.urlopen(req)
... except IOError, e:
... print `e`
... 
>>> e
  File "", line 1, in 
'''  : name 'e' is not defined '''
>>> req

>>> handle
>




Regards 
  
Johan 



___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] urllib2 issue getting realm

2011-08-31 Thread Sander Sweers
On 31 August 2011 09:46, Johan Geldenhuys  wrote:
> I am trying to use a very simple piece of code to get the realm from
> different HTTPS URLs.
>
> This realm is essential for successful authentication on the HTTPS session.

I think you got 2 things mixed up, http authentication and encrypted
http (https). Just having a https url does not mean you need to
authenticate. Take 'https://mail.google.com' as an example.

> If have to run this for a few different hosts and capture the realm.
> For one host, it works perfectly, but when I try the same code to get the
> next realm, it fails. I suspect that I need to close some type of
> connections or something, but I can't put my finger on it.


> For the next one:
>
 try:
> ...     req = urllib2.Request(URL % ips[1])
> ...     handle = urllib2.urlopen(req)
> ... except IOError, e:
> ...     print `e`
> ...

>
> See, no "e" printed which means that something worked. The exception didn't
> happen and I don't know why...Anybody?

Yes, when you type the url into your browser. I suspect it does not
ask you to authenticate via http authentication. Therefor no exception
is raised and you never print the headers.

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] urllib2 issue getting realm

2011-08-31 Thread Steven D'Aprano

Johan Geldenhuys wrote:

Hi everybody,

I am trying to use a very simple piece of code to get the realm from
different HTTPS URLs.

This realm is essential for successful authentication on the HTTPS session.


What happens if you paste

https://192.168.10.191/axis-cgi/jpg/image.cgi?resolution=1280x800

into a web browser?


--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] urllib2 issue getting realm

2011-08-31 Thread Johan Geldenhuys
Focusing on the code below, do you know why it would raise the exception for 
the first IP and not for the second?

Thank you
Johan
Sent from my iPhone 4

On 31/08/2011, at 22:09, Sander Sweers  wrote:

> On 31 August 2011 09:46, Johan Geldenhuys  wrote:
>> I am trying to use a very simple piece of code to get the realm from
>> different HTTPS URLs.
>> 
>> This realm is essential for successful authentication on the HTTPS session.
> 
> I think you got 2 things mixed up, http authentication and encrypted
> http (https). Just having a https url does not mean you need to
> authenticate. Take 'https://mail.google.com' as an example.
> 
>> If have to run this for a few different hosts and capture the realm.
>> For one host, it works perfectly, but when I try the same code to get the
>> next realm, it fails. I suspect that I need to close some type of
>> connections or something, but I can't put my finger on it.
> 
> 
>> For the next one:
>> 
> try:
>> ... req = urllib2.Request(URL % ips[1])
>> ... handle = urllib2.urlopen(req)
>> ... except IOError, e:
>> ... print `e`
>> ...
> 
>> 
>> See, no "e" printed which means that something worked. The exception didn't
>> happen and I don't know why...Anybody?
> 
> Yes, when you type the url into your browser. I suspect it does not
> ask you to authenticate via http authentication. Therefor no exception
> is raised and you never print the headers.
> 
> Greets
> Sander
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] urllib2 issue getting realm

2011-08-31 Thread Sander Sweers
On 31 August 2011 14:27, Johan Geldenhuys  wrote:
> On 31/08/2011, at 22:09, Sander Sweers  wrote:
>> On 31 August 2011 09:46, Johan Geldenhuys  wrote:
>>> I am trying to use a very simple piece of code to get the realm from
>>> different HTTPS URLs.
>>>
>>> This realm is essential for successful authentication on the HTTPS session.
>>
>> I think you got 2 things mixed up, http authentication and encrypted
>> http (https). Just having a https url does not mean you need to
>> authenticate. Take 'https://mail.google.com' as an example.
>>
>>> If have to run this for a few different hosts and capture the realm.
>>> For one host, it works perfectly, but when I try the same code to get the
>>> next realm, it fails. I suspect that I need to close some type of
>>> connections or something, but I can't put my finger on it.
>> 
>>
>>> For the next one:
>>>
>> try:
>>> ...     req = urllib2.Request(URL % ips[1])
>>> ...     handle = urllib2.urlopen(req)
>>> ... except IOError, e:
>>> ...     print `e`
>>> ...
>>
>>>
>>> See, no "e" printed which means that something worked. The exception didn't
>>> happen and I don't know why...Anybody?
>>
>> Yes, when you type the url into your browser. I suspect it does not
>> ask you to authenticate via http authentication. Therefor no exception
>> is raised and you never print the headers.

Top posting is evil ;-).

> Focusing on the code below, do you know why it would raise the exception for 
> the first
> IP and not for the second?

Run this and you should see which error is being raise. Do note we
catch urllib2.HTTPError instead of IOError.

try:
req = urllib2.Request(URL % ips[1])
handle = urllib2.urlopen(req)
print 'Success'
print handle.getcode()
print handle.headers
except urllib2.HTTPError as e:
print 'Exception caught'
print e
print e.getcode()
print e.hdrs

Greets
Sander
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Getting values from different functions (def's)

2011-08-31 Thread Susana Iraiis Delgado Rodriguez
Hello list !!
I'm developing a Python GUI application. I alreday developed a very simple
window with buttons, each button will do a different task, but the most
important button will need to get information gotten in previous python's
functions. Let's say I have four functions but at the end I want to collet
all the information gotten.
from Tkinter import *
import tkSimpleDialog
import tkMessageBox
import tkFileDialog
def directorio():
 print 'Seleccione directorio donde empezar'
 dirname =
tkFileDialog.askdirectory(parent=root,initialdir="/",title='Selecciona la
ruta a escanear')
 if len(dirname ) > 0:
  print "You chose %s" % dirname
def extension():
 print "Escribe la extension que necesitas buscar"
 ext=tkSimpleDialog.askstring('Extension a buscar:','')
 print 'Buscando archivos: ',ext
def csv():
 print "Nombre del csv a crear"
 inv=tkSimpleDialog.askstring('Nombre de .csv:','')
 print 'Archivo de salida: ',inv
def boton4():
#In this button I want to make a bigger process, but I need the root
selected and the two strings the user types.
 print csv.inv #Obviously this throws an error
root = Tk()
top = Toplevel()
root.minsize(400,200)
toolbar = Frame(root)
b = Button(toolbar, text="Selecciona ruta", width=15, command=directorio)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="Escriba extension", width=15, command=extension)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="Nombre de csv", width=15, command=csv)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="Salir", width=6, command=boton4)
b.pack(side=LEFT, padx=2, pady=2)
toolbar.pack(side=TOP, fill=X)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Getting values from different functions (def's)

2011-08-31 Thread Alan Gauld

On 31/08/11 18:17, Susana Iraiis Delgado Rodriguez wrote:

Hello list !!
I'm developing a Python GUI application. I alreday developed a very
simple window with buttons, each button will do a different task, but
the most important button will need to get information gotten in
previous python's functions. Let's say I have four functions but at the
end I want to collet all the information gotten.


Instead of (or as well as) printing the data you will need to store it 
in variables. Then you can use those variables in the other function.




from Tkinter import *
import tkSimpleDialog
import tkMessageBox
import tkFileDialog


# define storage variables
dir = ""
extn = ""
csv_name = ""


def directorio():

global dir# need to specify the global one


  print 'Seleccione directorio donde empezar'
  dirname = > tkFileDialog.askdirectory(parent=root,

   initialdir="/",
   title='Selecciona > la ruta a escanear')

  if len(dirname ) > 0:
   print "You chose %s" % dirname


 dir = dirname  # store the value


def extension():

global extn

  print "Escribe la extension que necesitas buscar"
  ext=tkSimpleDialog.askstring('Extension a buscar:','')
  print 'Buscando archivos: ',ext

extn = ext


def csv():

global csv_name

  print "Nombre del csv a crear"
  inv=tkSimpleDialog.askstring('Nombre de .csv:','')
  print 'Archivo de salida: ',inv

csv_name = inv


def boton4():
#In this button I want to make a bigger process, but I need the root
selected and the two strings the user types.
  print csv.inv #Obviously this throws an error


print dir,csv_name,extn

But course in a GUI you would normally not use print but instead 
populate the text field of a label or Text widget or some such

device.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Quote of the Day version 1.0

2011-08-31 Thread Cranky Frankie
I made some headway on the quote of the day program. I just tried to
do it simple using two assumptions:

- long quotes are going to print funny until I figure out the string
splitting stuff
- hard coding the quotes and authors in the program is simple, and I
can use a spreadsheet to generate the strings when I put in the rest
of the quotes (I have a lot of them).

This code works. Now I just have to figure out:

- how to get Ubuntu to run it at startup
- how to associate .py files in Ubuntu to IDLE

Thanks for all who commented, I really appreciate it. Pyhton is fun!





# Quote_a_day_V1.py
#
# This program displays a random quotation
#
# Frank L. Palmeri August 31, 2011

import random

print("\n\tHere is today's quote of the day:\n")

author = (
"Kahlil Gibran",
"Henrik Ibsen",
"Dwight Eisenhower",
"Will Rogers",
"Will Rogers",
"Jean de LaFontaine",
"Eleanor Hibbert",
"Baruch Spinoza",
"Albert Camus",
"Thomas a Kempi"
)

quotation = (
"A candle loses nothing of its light when lighting another.",
"The strongest man in the world is he who stands most alone.",
"Leadership consists of nothing but taking responsibility for
everything that goes wrong and giving your subordinates credit for
everything that goes well.",
"Even if you're on the right track, you'll get run over if you
just sit there.",
"I belong to no organized party. I am a Democrat.",
"Patience and time do more than strength or passion.",
"Never regret. If it's good, it's wonderful. If it's bad, it's experience.",
"I have made a ceaseless effort not to ridicule, not to bewail,
not to scorn human actions, but to understand them.",
"In the depth of winter I finally learned there was in me an
invincible summer.",
"Who has a harder fight than he who is striving to overcome himself."
)

numAuthors = len(author)

printAuthor = random.randrange(numAuthors)

print(quotation[printAuthor])

print("by ", author[printAuthor])

input("\nPress the enter key to exit.")




-- 
Frank L. "Cranky Frankie" Palmeri
Risible Riding Raconteur & Writer

" . . . and the extended forecast,
until you come back to me, baby,
is high tonight, low tomorrow,
and precipitation is expected."
- Tom Waits, "Emotional Weather Report"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Quote of the Day version 1.0

2011-08-31 Thread Prasad, Ramit
-Original Message-
I made some headway on the quote of the day program. I just tried to
do it simple using two assumptions:

- long quotes are going to print funny until I figure out the string
splitting stuff
- hard coding the quotes and authors in the program is simple, and I
can use a spreadsheet to generate the strings when I put in the rest
of the quotes (I have a lot of them).

This code works. Now I just have to figure out:

- how to get Ubuntu to run it at startup
- how to associate .py files in Ubuntu to IDLE

Thanks for all who commented, I really appreciate it. Pyhton is fun!





# Quote_a_day_V1.py
#
# This program displays a random quotation
#
# Frank L. Palmeri August 31, 2011

import random

print("\n\tHere is today's quote of the day:\n")

author = (
"Kahlil Gibran",
"Henrik Ibsen",
"Dwight Eisenhower",
"Will Rogers",
"Will Rogers",
"Jean de LaFontaine",
"Eleanor Hibbert",
"Baruch Spinoza",
"Albert Camus",
"Thomas a Kempi"
)

quotation = (
"A candle loses nothing of its light when lighting another.",
"The strongest man in the world is he who stands most alone.",
"Leadership consists of nothing but taking responsibility for
everything that goes wrong and giving your subordinates credit for
everything that goes well.",
"Even if you're on the right track, you'll get run over if you
just sit there.",
"I belong to no organized party. I am a Democrat.",
"Patience and time do more than strength or passion.",
"Never regret. If it's good, it's wonderful. If it's bad, it's experience.",
"I have made a ceaseless effort not to ridicule, not to bewail,
not to scorn human actions, but to understand them.",
"In the depth of winter I finally learned there was in me an
invincible summer.",
"Who has a harder fight than he who is striving to overcome himself."
)

numAuthors = len(author)

printAuthor = random.randrange(numAuthors)

print(quotation[printAuthor])

print("by ", author[printAuthor])

input("\nPress the enter key to exit.")


I would suggest storing the authors and quotes in a list[] instead of a 
tuple(). This will allow you make modifications directly to the list. Lists are 
mutable (changeable) while tuples are not. This will leave you in better shape 
if you decide to use pickle/shelve to store the lists in a file for reuse.

# tuple example 
>>> t = (1,2,3)
>>> t
(1, 2, 3)
>>> t[0]
1
>>> t[0] = 5
TypeError: 'tuple' object does not support item assignment

# list example
>>> l = [1,2,3]
>>> l
[1, 2, 3]
>>> l[0]
1
>>> l[0] = 5
>>> l[0]
5
>>> l.append( 2100 ) # allows you to easily add new elements
>>> l
[5, 2, 3, 2100]

As for string splitting, storing the full string as you are is the best option. 
You should leave your client (commandline/text, web, GUI) to decide what is 
appropriate for splitting and where it should be split.


Although, if you want my opinion, I would probably create a quote class that 
stores some information. This way it is easier to make modifications and 
additions to the capabilities of the Quote. Not to mention this bundles the 
information together and you never have to worry about your author list and 
quote list getting out of sync. And if you derive Quote from object you 
*should* be able to pickle the list of Quotes very easily.


(The following is untested).

class Quote(object):
def __init__(self, quote, author, date=None, misc=None):
self.quote = quote
.



Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] meaning of % in: if n % x == 0:

2011-08-31 Thread Lisi
??  If either n or x or both were 0, and % were the same thing as *, the 
statement would be true, but from the context I don't think that % does mean 
the same as *, because * appears very soon after in the same fragment of 
code. 

Lisi

I'm sorry I am making such heavy weather of all this.  Blame 2 things: anno 
domini and an exaggerated (obsessive) need to understand language.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] meaning of % in: if n % x == 0:

2011-08-31 Thread Hugo Arts
On Wed, Aug 31, 2011 at 9:35 PM, Lisi  wrote:
> ??  If either n or x or both were 0, and % were the same thing as *, the
> statement would be true, but from the context I don't think that % does mean
> the same as *, because * appears very soon after in the same fragment of
> code.
>
> Lisi
>
> I'm sorry I am making such heavy weather of all this.  Blame 2 things: anno
> domini and an exaggerated (obsessive) need to understand language.

% is the remainder operator:

http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex

it is how much remains after you perform an integer division, e.g. 23
% 5 == 3, since 20 / 5 == 4 and then you are left with 3.

 n % y == 0 if n is divisible by y. This is useful in factoring prime
numbers, and in the case of y == 2, for checking if the number n is
even.

Hugo
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] meaning of % in: if n % x == 0:

2011-08-31 Thread Joel Goldstick
On Wed, Aug 31, 2011 at 3:58 PM, Hugo Arts  wrote:

> On Wed, Aug 31, 2011 at 9:35 PM, Lisi  wrote:
> > ??  If either n or x or both were 0, and % were the same thing as *, the
> > statement would be true, but from the context I don't think that % does
> mean
> > the same as *, because * appears very soon after in the same fragment of
> > code.
> >
> > Lisi
> >
> > I'm sorry I am making such heavy weather of all this.  Blame 2 things:
> anno
> > domini and an exaggerated (obsessive) need to understand language.
>
> % is the remainder operator:
>
>
> http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex
>
> it is how much remains after you perform an integer division, e.g. 23
> % 5 == 3, since 20 / 5 == 4 and then you are left with 3.
>
>  n % y == 0 if n is divisible by y. This is useful in factoring prime
> numbers, and in the case of y == 2, for checking if the number n is
> even.
>
> Hugo
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Here is a little example that shows how using the 'mod' or 'modulus'
operator can select only values that are divisible by 3.

>>> for i in range(16):
... if not i % 3:
...   print i
...
0
3
6
9
12
15


-- 
Joel Goldstick
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] urllib2 issue getting realm

2011-08-31 Thread Johan Geldenhuys
Thanks Sanders
Will give that a go

Johan
Sent from my iPhone 4

On 31/08/2011, at 23:03, Sander Sweers  wrote:

> On 31 August 2011 14:27, Johan Geldenhuys  wrote:
>> On 31/08/2011, at 22:09, Sander Sweers  wrote:
>>> On 31 August 2011 09:46, Johan Geldenhuys  wrote:
 I am trying to use a very simple piece of code to get the realm from
 different HTTPS URLs.
 
 This realm is essential for successful authentication on the HTTPS session.
>>> 
>>> I think you got 2 things mixed up, http authentication and encrypted
>>> http (https). Just having a https url does not mean you need to
>>> authenticate. Take 'https://mail.google.com' as an example.
>>> 
 If have to run this for a few different hosts and capture the realm.
 For one host, it works perfectly, but when I try the same code to get the
 next realm, it fails. I suspect that I need to close some type of
 connections or something, but I can't put my finger on it.
>>> 
>>> 
 For the next one:
 
>>> try:
 ... req = urllib2.Request(URL % ips[1])
 ... handle = urllib2.urlopen(req)
 ... except IOError, e:
 ... print `e`
 ...
>>> 
 
 See, no "e" printed which means that something worked. The exception didn't
 happen and I don't know why...Anybody?
>>> 
>>> Yes, when you type the url into your browser. I suspect it does not
>>> ask you to authenticate via http authentication. Therefor no exception
>>> is raised and you never print the headers.
> 
> Top posting is evil ;-).
> 
>> Focusing on the code below, do you know why it would raise the exception for 
>> the first
>> IP and not for the second?
> 
> Run this and you should see which error is being raise. Do note we
> catch urllib2.HTTPError instead of IOError.
> 
> try:
>req = urllib2.Request(URL % ips[1])
>handle = urllib2.urlopen(req)
>print 'Success'
>print handle.getcode()
>print handle.headers
> except urllib2.HTTPError as e:
>print 'Exception caught'
>print e
>print e.getcode()
>print e.hdrs
> 
> Greets
> Sander
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Quote of the Day version 1.0

2011-08-31 Thread Sander Sweers
On 31 August 2011 21:14, Cranky Frankie  wrote:
> I made some headway on the quote of the day program. I just tried to
> do it simple using two assumptions:
>
> - long quotes are going to print funny until I figure out the string
> splitting stuff

Define funny? Normally the linux console will wrap everything up
nicely for you. On a desktop (Gnome/Kde) there are other ways to
display notify texts.

> - hard coding the quotes and authors in the program is simple, and I
> can use a spreadsheet to generate the strings when I put in the rest
> of the quotes (I have a lot of them).

Think about how to store and retrieve these quotes. You could read
from a file and pick a random quotes.

> This code works. Now I just have to figure out:
>
> - how to get Ubuntu to run it at startup

Highly dependant on how and where you login.

> - how to associate .py files in Ubuntu to IDLE

This depends on a couple of factors and not really about learning
python. The Ubuntu forums and wiki are the best place to start.

> Pyhton is fun!

Lets make it more fun :-). Consider the below example (also on [1])
which introduces a different approach to printing quotes. Do not
hesitate to ask questions as I added tuple unpacking and string
formatting which you might not have covered in depth yet in your
tutorial.

import random

quotes = (
("Kahlil Gibran", "A candle loses nothing of its light when
lighting another."),
("Henrik Ibsen", "The strongest man in the world is he who stands
most alone."),
("Dwight Eisenhower", "Leadership consists of nothing but taking
responsibility for everything that goes wrong and giving your
subordinates credit for everything that goes well."),
("Will Rogers", "Even if you're on the right track, you'll get run
over if you just sit there."),
("Will Rogers", "I belong to no organized party. I am a Democrat."),
("Jean de LaFontaine", "Patience and time do more than strength or
passion."),
("Eleanor Hibbert", "Never regret. If it's good, it's wonderful.
If it's bad, it's experience."),
("Baruch Spinoza", "I have made a ceaseless effort not to
ridicule, not to bewail, not to scorn human actions, but to understand
them."),
("Albert Camus", "In the depth of winter I finally learned there
was in me an invincible summer."),
("Thomas a Kempi", "Who has a harder fight than he who is striving
to overcome himself."))

author, quote = random.choice(quotes)
print "%s\n\tBy %s" % (quote, author)

Greets
Sander

[1] http://pastebin.com/bdE2ynaG
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Quote of the Day version 1.0

2011-08-31 Thread Prasad, Ramit
[snip]

> Do not hesitate to ask questions as I added tuple unpacking and string
>formatting which you might not have covered in depth yet in your
>tutorial.

[snip]

>author, quote = random.choice(quotes)
>print "%s\n\tBy %s" % (quote, author)

I figured I might as well add my preferred method of string formatting. :)
print 'The quote "{0}" is by {1}. I {2} {1}'.format(quote, author, 'love') # 
although you might hate {1} ;)

Ramit

P.S. Notice the mixed quote convention.


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] reclassify values in an array

2011-08-31 Thread questions anon
Dear All,
I have been going round in circles trying to solve something that sounds
simple. I have a huge array and I would like to reclassify the values.
Firstly just make them zeros and ones, for example if the values in the
array are less than 100 make them 0 and if greater than 100 make them 1. And
then finally sum them together.
I have attempted a few methods, see code below. Any feedback will be greatly
appreciated.

Attempt 1:
big_array=N.ma.concatenate(all_FFDI)
for i in big_array:
if i<100:
i=0
elif i>=100:
i=1
print big_array
sum=big_array.sum(axis=0)
print "the sum is", sum


Attempt 2:
big_array=N.ma.concatenate(all_FFDI)
for i, value in enumerate(big_array):
if value==100:
big_array[i]=0
elif value>=100:
big_array[i]=1
print big_array
sum=big_array.sum(axis=0)
print "the sum is", sum
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Quote of the Day version 1.0

2011-08-31 Thread Alan Gauld

On 31/08/11 20:14, Cranky Frankie wrote:


This code works. Now I just have to figure out:
- how to associate .py files in Ubuntu to IDLE


You probably don't want to do that. IDLE is fine for developing code but 
you don't want to run  it in IDLE for general use you want to use the 
interpreter. And the shebang (#!) line at the start will do that for you.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] meaning of % in: if n % x == 0:

2011-08-31 Thread Alan Gauld

On 31/08/11 20:35, Lisi wrote:

??  If either n or x or both were 0, and % were the same thing as *, the
statement would be true, but from the context I don't think that % does mean
the same as *, because * appears very soon after in the same fragment of
code.



It's the remainder operator:

IF N MOD X = 0

in BASIC

It's explained in the Simple Sequences topic of my tutorial and 
mentioned again in the Raw Materials topic under integers.


The use of % as the operator goes back to C. Many of Python's
operators are just inherited directly from C.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reclassify values in an array

2011-08-31 Thread Alan Gauld

On 01/09/11 00:17, questions anon wrote:

Dear All,
I have been going round in circles trying to solve something that sounds
simple. I have a huge array and I would like to reclassify the values.
Firstly just make them zeros and ones,...
And then finally sum them together.


And what has been the problem?


I have attempted a few methods, see code below.


I'm not familiar with NumPy (which I assume is what you are using?)
However the second approach looks more likely to succeed than the first. 
Assuming enumerate works with NumPy arrays. Is there any

reason why you cannot use a normal list?

Then it would just be:

result = sum(1 for item in array if item >= 100)

HTH,

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] meaning of % in: if n % x == 0:

2011-08-31 Thread Steven D'Aprano

Hugo Arts wrote:


 n % y == 0 if n is divisible by y. This is useful in factoring prime
numbers


If you find a way to factor *prime numbers*, you're doing something wrong.

:)

(By definition, a prime number has no factors apart from itself and one, 
which are trivial.)


You mean, factorising numbers into the product of primes.



--
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] meaning of % in: if n % x == 0:

2011-08-31 Thread bob gailer

% is not remainder - it is modulo.

Difference shows up when left agument is negative.

--
Bob Gailer
919-636-4239
Chapel Hill NC

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] meaning of % in: if n % x == 0:

2011-08-31 Thread Hugo Arts
ah, my mistake. I was in a hurry writing that post, which is a really
bad idea :/

On Thu, Sep 1, 2011 at 2:09 AM, Steven D'Aprano  wrote:
> Hugo Arts wrote:
>
>>  n % y == 0 if n is divisible by y. This is useful in factoring prime
>> numbers
>
> If you find a way to factor *prime numbers*, you're doing something wrong.
>
> :)
>
> (By definition, a prime number has no factors apart from itself and one,
> which are trivial.)
>
> You mean, factorising numbers into the product of primes.
>
>
>
> --
> Steven
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] reclassify values in an array

2011-08-31 Thread Andre' Walker-Loud
Hi anonymous questioner,

Like Alan, I suspect you are using numpy as

import numpy as N

there is probably a numpy email list where this would be more appropriate 
(personally I don't object, but I don't want to speak for all the subscribers).

the 2nd attempt is closer to the right answer.  To help yourself answer the 
question, try

> for i, value in enumerate(big_array):
print i,value

and see what you get.  Are you allowed to compare value with 100?

Then, when performing the sum, you are asking to sum over axis=0.  I assume you 
are trying to sum all the individual elements, rather than sum the rows.  
asking to sum over axis=0 is telling numpy to treat each row as an object, and 
sum all those objects, preserving all other dimensions of your array.  In your 
case, you have a 2 dimensional array, so summing over axis=0 is taking all the 
rows of your array (matrix) and summing them to produce a new row.  
Specifically, it will take the first entry of each row, and add them to make 
the first  entry of the summed row, then likewise for each additional entry.

In math language, you are doing

r_j = sum_i big_array_{i,j}

if you do

big_array.sum()

then it will sum all of the individual elements

sum = sum_i sum_j big_array_{i,j}


play around more with the interactive interpreter.  If you try these things, 
and they fail, reproduce your code from the top to bottom, adding only one line 
at a time, and see what happens (at least for these simple short code 
snippets).  That should help you improve your understanding faster - which I 
assume is one of your goals :)


Andre






On Aug 31, 2011, at 4:17 PM, questions anon wrote:

> Dear All,
> I have been going round in circles trying to solve something that sounds 
> simple. I have a huge array and I would like to reclassify the values. 
> Firstly just make them zeros and ones, for example if the values in the array 
> are less than 100 make them 0 and if greater than 100 make them 1. And then 
> finally sum them together. 
> I have attempted a few methods, see code below. Any feedback will be greatly 
> appreciated.
> 
> Attempt 1:
> big_array=N.ma.concatenate(all_FFDI)
> for i in big_array:
> if i<100:
> i=0
> elif i>=100:
> i=1
> print big_array
> sum=big_array.sum(axis=0)
> print "the sum is", sum
> 
> 
> Attempt 2:
> big_array=N.ma.concatenate(all_FFDI)
> for i, value in enumerate(big_array):
> if value==100:
> big_array[i]=0
> elif value>=100:
> big_array[i]=1
> print big_array
> sum=big_array.sum(axis=0)
> print "the sum is", sum
> 
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor